Decompiled source of Vs Twitch v1.1.0

Microsoft.Extensions.Configuration.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
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.Microsoft.Extensions.Configuration;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration.Memory;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Primitives;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration")]
[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("Implementation of key-value pair based configuration for Microsoft.Extensions.Configuration. Includes the memory configuration provider.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Configuration")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.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]
	[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.Microsoft.Extensions.Configuration
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Error_NoSources => GetResourceString("Error_NoSources");

		internal static string InvalidNullArgument => GetResourceString("InvalidNullArgument");

		internal static string StreamConfigurationProvidersAlreadyLoaded => GetResourceString("StreamConfigurationProvidersAlreadyLoaded");

		internal static string StreamConfigurationSourceStreamCannotBeNull => GetResourceString("StreamConfigurationSourceStreamCannotBeNull");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace Microsoft.Extensions.FileProviders
{
	internal sealed class EmptyDisposable : IDisposable
	{
		public static EmptyDisposable Instance { get; } = new EmptyDisposable();


		private EmptyDisposable()
		{
		}

		public void Dispose()
		{
		}
	}
}
namespace Microsoft.Extensions.Internal
{
	internal static class ChangeCallbackRegistrar
	{
		internal static IDisposable UnsafeRegisterChangeCallback<T>(Action<object?> callback, object? state, CancellationToken token, Action<T> onFailure, T onFailureState)
		{
			bool flag = false;
			if (!ExecutionContext.IsFlowSuppressed())
			{
				ExecutionContext.SuppressFlow();
				flag = true;
			}
			try
			{
				return token.Register(callback, state);
			}
			catch (ObjectDisposedException)
			{
				onFailure(onFailureState);
			}
			finally
			{
				if (flag)
				{
					ExecutionContext.RestoreFlow();
				}
			}
			return EmptyDisposable.Instance;
		}
	}
}
namespace Microsoft.Extensions.Configuration
{
	public static class ChainedBuilderExtensions
	{
		public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder configurationBuilder, IConfiguration config)
		{
			return configurationBuilder.AddConfiguration(config, shouldDisposeConfiguration: false);
		}

		public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder configurationBuilder, IConfiguration config, bool shouldDisposeConfiguration)
		{
			System.ThrowHelper.ThrowIfNull(configurationBuilder, "configurationBuilder");
			System.ThrowHelper.ThrowIfNull(config, "config");
			configurationBuilder.Add(new ChainedConfigurationSource
			{
				Configuration = config,
				ShouldDisposeConfiguration = shouldDisposeConfiguration
			});
			return configurationBuilder;
		}
	}
	public class ChainedConfigurationProvider : IConfigurationProvider, IDisposable
	{
		private readonly IConfiguration _config;

		private readonly bool _shouldDisposeConfig;

		public IConfiguration Configuration => _config;

		public ChainedConfigurationProvider(ChainedConfigurationSource source)
		{
			System.ThrowHelper.ThrowIfNull(source, "source");
			_config = source.Configuration ?? throw new ArgumentException(System.SR.Format(System.SR.InvalidNullArgument, "source.Configuration"), "source");
			_shouldDisposeConfig = source.ShouldDisposeConfiguration;
		}

		public bool TryGet(string key, out string? value)
		{
			value = _config[key];
			return !string.IsNullOrEmpty(value);
		}

		public void Set(string key, string? value)
		{
			_config[key] = value;
		}

		public IChangeToken GetReloadToken()
		{
			return _config.GetReloadToken();
		}

		public void Load()
		{
		}

		public IEnumerable<string> GetChildKeys(IEnumerable<string> earlierKeys, string? parentPath)
		{
			IConfiguration configuration;
			if (parentPath != null)
			{
				IConfiguration section = _config.GetSection(parentPath);
				configuration = section;
			}
			else
			{
				configuration = _config;
			}
			List<string> list = new List<string>();
			foreach (IConfigurationSection child in configuration.GetChildren())
			{
				list.Add(child.Key);
			}
			list.AddRange(earlierKeys);
			list.Sort(ConfigurationKeyComparer.Comparison);
			return list;
		}

		public void Dispose()
		{
			if (_shouldDisposeConfig)
			{
				(_config as IDisposable)?.Dispose();
			}
		}
	}
	public class ChainedConfigurationSource : IConfigurationSource
	{
		public IConfiguration? Configuration
		{
			get; [param: DisallowNull]
			set;
		}

		public bool ShouldDisposeConfiguration { get; set; }

		public IConfigurationProvider Build(IConfigurationBuilder builder)
		{
			return new ChainedConfigurationProvider(this);
		}
	}
	public class ConfigurationBuilder : IConfigurationBuilder
	{
		private readonly List<IConfigurationSource> _sources = new List<IConfigurationSource>();

		public IList<IConfigurationSource> Sources => _sources;

		public IDictionary<string, object> Properties { get; } = new Dictionary<string, object>();


		public IConfigurationBuilder Add(IConfigurationSource source)
		{
			System.ThrowHelper.ThrowIfNull(source, "source");
			_sources.Add(source);
			return this;
		}

		public IConfigurationRoot Build()
		{
			List<IConfigurationProvider> list = new List<IConfigurationProvider>();
			foreach (IConfigurationSource source in _sources)
			{
				IConfigurationProvider item = source.Build(this);
				list.Add(item);
			}
			return new ConfigurationRoot(list);
		}
	}
	public class ConfigurationKeyComparer : IComparer<string>
	{
		private const char KeyDelimiter = ':';

		public static ConfigurationKeyComparer Instance { get; } = new ConfigurationKeyComparer();


		internal static Comparison<string> Comparison { get; } = Instance.Compare;


		public int Compare(string? x, string? y)
		{
			ReadOnlySpan<char> readOnlySpan = x.AsSpan();
			ReadOnlySpan<char> readOnlySpan2 = y.AsSpan();
			readOnlySpan = SkipAheadOnDelimiter(readOnlySpan);
			readOnlySpan2 = SkipAheadOnDelimiter(readOnlySpan2);
			while (!readOnlySpan.IsEmpty && !readOnlySpan2.IsEmpty)
			{
				int num = readOnlySpan.IndexOf(':');
				int num2 = readOnlySpan2.IndexOf(':');
				int num3 = Compare((num == -1) ? readOnlySpan : readOnlySpan.Slice(0, num), (num2 == -1) ? readOnlySpan2 : readOnlySpan2.Slice(0, num2));
				if (num3 != 0)
				{
					return num3;
				}
				readOnlySpan = ((num == -1) ? default(ReadOnlySpan<char>) : SkipAheadOnDelimiter(readOnlySpan.Slice(num + 1)));
				readOnlySpan2 = ((num2 == -1) ? default(ReadOnlySpan<char>) : SkipAheadOnDelimiter(readOnlySpan2.Slice(num2 + 1)));
			}
			if (!readOnlySpan.IsEmpty)
			{
				return 1;
			}
			if (!readOnlySpan2.IsEmpty)
			{
				return -1;
			}
			return 0;
			static int Compare(ReadOnlySpan<char> a, ReadOnlySpan<char> b)
			{
				int result;
				bool flag = int.TryParse(a.ToString(), out result);
				int result2;
				bool flag2 = int.TryParse(b.ToString(), out result2);
				if (!flag && !flag2)
				{
					return a.CompareTo(b, StringComparison.OrdinalIgnoreCase);
				}
				if (flag && flag2)
				{
					return result - result2;
				}
				return (!flag) ? 1 : (-1);
			}
			static ReadOnlySpan<char> SkipAheadOnDelimiter(ReadOnlySpan<char> a)
			{
				while (!a.IsEmpty && a[0] == ':')
				{
					a = a.Slice(1);
				}
				return a;
			}
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	[DebuggerTypeProxy(typeof(ConfigurationManagerDebugView))]
	public sealed class ConfigurationManager : IConfigurationManager, IConfiguration, IConfigurationBuilder, IConfigurationRoot, IDisposable
	{
		private sealed class ConfigurationManagerDebugView
		{
			private readonly ConfigurationManager _current;

			[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
			public ConfigurationSectionDebugView[] Items => ConfigurationSectionDebugView.FromConfiguration(_current, _current).ToArray();

			public ConfigurationManagerDebugView(ConfigurationManager current)
			{
				_current = current;
			}
		}

		private sealed class ConfigurationSources : IList<IConfigurationSource>, ICollection<IConfigurationSource>, IEnumerable<IConfigurationSource>, IEnumerable
		{
			private readonly List<IConfigurationSource> _sources = new List<IConfigurationSource>();

			private readonly ConfigurationManager _config;

			public IConfigurationSource this[int index]
			{
				get
				{
					return _sources[index];
				}
				set
				{
					_sources[index] = value;
					_config.ReloadSources();
				}
			}

			public int Count => _sources.Count;

			public bool IsReadOnly => false;

			public ConfigurationSources(ConfigurationManager config)
			{
				_config = config;
			}

			public void Add(IConfigurationSource source)
			{
				_sources.Add(source);
				_config.AddSource(source);
			}

			public void Clear()
			{
				_sources.Clear();
				_config.ReloadSources();
			}

			public bool Contains(IConfigurationSource source)
			{
				return _sources.Contains(source);
			}

			public void CopyTo(IConfigurationSource[] array, int arrayIndex)
			{
				_sources.CopyTo(array, arrayIndex);
			}

			public List<IConfigurationSource>.Enumerator GetEnumerator()
			{
				return _sources.GetEnumerator();
			}

			public int IndexOf(IConfigurationSource source)
			{
				return _sources.IndexOf(source);
			}

			public void Insert(int index, IConfigurationSource source)
			{
				_sources.Insert(index, source);
				_config.ReloadSources();
			}

			public bool Remove(IConfigurationSource source)
			{
				bool result = _sources.Remove(source);
				_config.ReloadSources();
				return result;
			}

			public void RemoveAt(int index)
			{
				_sources.RemoveAt(index);
				_config.ReloadSources();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}

			IEnumerator<IConfigurationSource> IEnumerable<IConfigurationSource>.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private sealed class ConfigurationBuilderProperties : IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable
		{
			private readonly Dictionary<string, object> _properties = new Dictionary<string, object>();

			private readonly ConfigurationManager _config;

			public object this[string key]
			{
				get
				{
					return _properties[key];
				}
				set
				{
					_properties[key] = value;
					_config.ReloadSources();
				}
			}

			public ICollection<string> Keys => _properties.Keys;

			public ICollection<object> Values => _properties.Values;

			public int Count => _properties.Count;

			public bool IsReadOnly => false;

			public ConfigurationBuilderProperties(ConfigurationManager config)
			{
				_config = config;
			}

			public void Add(string key, object value)
			{
				_properties.Add(key, value);
				_config.ReloadSources();
			}

			public void Add(KeyValuePair<string, object> item)
			{
				((ICollection<KeyValuePair<string, object>>)_properties).Add(item);
				_config.ReloadSources();
			}

			public void Clear()
			{
				_properties.Clear();
				_config.ReloadSources();
			}

			public bool Contains(KeyValuePair<string, object> item)
			{
				return _properties.Contains(item);
			}

			public bool ContainsKey(string key)
			{
				return _properties.ContainsKey(key);
			}

			public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
			{
				((ICollection<KeyValuePair<string, object>>)_properties).CopyTo(array, arrayIndex);
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				return _properties.GetEnumerator();
			}

			public bool Remove(string key)
			{
				bool result = _properties.Remove(key);
				_config.ReloadSources();
				return result;
			}

			public bool Remove(KeyValuePair<string, object> item)
			{
				bool result = ((ICollection<KeyValuePair<string, object>>)_properties).Remove(item);
				_config.ReloadSources();
				return result;
			}

			public bool TryGetValue(string key, [NotNullWhen(true)] out object value)
			{
				return _properties.TryGetValue(key, out value);
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return _properties.GetEnumerator();
			}
		}

		private readonly ConfigurationSources _sources;

		private readonly ConfigurationBuilderProperties _properties;

		private readonly ReferenceCountedProviderManager _providerManager = new ReferenceCountedProviderManager();

		private readonly List<IDisposable> _changeTokenRegistrations = new List<IDisposable>();

		private ConfigurationReloadToken _changeToken = new ConfigurationReloadToken();

		public string? this[string key]
		{
			get
			{
				using ReferenceCountedProviders referenceCountedProviders = _providerManager.GetReference();
				return ConfigurationRoot.GetConfiguration(referenceCountedProviders.Providers, key);
			}
			set
			{
				using ReferenceCountedProviders referenceCountedProviders = _providerManager.GetReference();
				ConfigurationRoot.SetConfiguration(referenceCountedProviders.Providers, key, value);
			}
		}

		IDictionary<string, object> IConfigurationBuilder.Properties => _properties;

		public IList<IConfigurationSource> Sources => _sources;

		IEnumerable<IConfigurationProvider> IConfigurationRoot.Providers => _providerManager.NonReferenceCountedProviders;

		public ConfigurationManager()
		{
			_sources = new ConfigurationSources(this);
			_properties = new ConfigurationBuilderProperties(this);
			_sources.Add(new MemoryConfigurationSource());
		}

		public IConfigurationSection GetSection(string key)
		{
			return new ConfigurationSection(this, key);
		}

		public IEnumerable<IConfigurationSection> GetChildren()
		{
			return this.GetChildrenImplementation(null);
		}

		public void Dispose()
		{
			DisposeRegistrations();
			_providerManager.Dispose();
		}

		IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source)
		{
			System.ThrowHelper.ThrowIfNull(source, "source");
			_sources.Add(source);
			return this;
		}

		IConfigurationRoot IConfigurationBuilder.Build()
		{
			return this;
		}

		IChangeToken IConfiguration.GetReloadToken()
		{
			return _changeToken;
		}

		void IConfigurationRoot.Reload()
		{
			using (ReferenceCountedProviders referenceCountedProviders = _providerManager.GetReference())
			{
				foreach (IConfigurationProvider provider in referenceCountedProviders.Providers)
				{
					provider.Load();
				}
			}
			RaiseChanged();
		}

		internal ReferenceCountedProviders GetProvidersReference()
		{
			return _providerManager.GetReference();
		}

		private void RaiseChanged()
		{
			Interlocked.Exchange(ref _changeToken, new ConfigurationReloadToken()).OnReload();
		}

		private void AddSource(IConfigurationSource source)
		{
			IConfigurationProvider configurationProvider = source.Build(this);
			configurationProvider.Load();
			_changeTokenRegistrations.Add(ChangeToken.OnChange(configurationProvider.GetReloadToken, RaiseChanged));
			_providerManager.AddProvider(configurationProvider);
			RaiseChanged();
		}

		private void ReloadSources()
		{
			DisposeRegistrations();
			_changeTokenRegistrations.Clear();
			List<IConfigurationProvider> list = new List<IConfigurationProvider>();
			foreach (IConfigurationSource source in _sources)
			{
				list.Add(source.Build(this));
			}
			foreach (IConfigurationProvider item in list)
			{
				item.Load();
				_changeTokenRegistrations.Add(ChangeToken.OnChange(item.GetReloadToken, RaiseChanged));
			}
			_providerManager.ReplaceProviders(list);
			RaiseChanged();
		}

		private void DisposeRegistrations()
		{
			foreach (IDisposable changeTokenRegistration in _changeTokenRegistrations)
			{
				changeTokenRegistration.Dispose();
			}
		}

		private string DebuggerToString()
		{
			return $"Sections = {ConfigurationSectionDebugView.FromConfiguration(this, this).Count}";
		}
	}
	public abstract class ConfigurationProvider : IConfigurationProvider
	{
		private ConfigurationReloadToken _reloadToken = new ConfigurationReloadToken();

		protected IDictionary<string, string?> Data { get; set; }

		protected ConfigurationProvider()
		{
			Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
		}

		public virtual bool TryGet(string key, out string? value)
		{
			return Data.TryGetValue(key, out value);
		}

		public virtual void Set(string key, string? value)
		{
			Data[key] = value;
		}

		public virtual void Load()
		{
		}

		public virtual IEnumerable<string> GetChildKeys(IEnumerable<string> earlierKeys, string? parentPath)
		{
			List<string> list = new List<string>();
			if (parentPath == null)
			{
				foreach (KeyValuePair<string, string> datum in Data)
				{
					list.Add(Segment(datum.Key, 0));
				}
			}
			else
			{
				foreach (KeyValuePair<string, string> datum2 in Data)
				{
					if (datum2.Key.Length > parentPath.Length && datum2.Key.StartsWith(parentPath, StringComparison.OrdinalIgnoreCase) && datum2.Key[parentPath.Length] == ':')
					{
						list.Add(Segment(datum2.Key, parentPath.Length + 1));
					}
				}
			}
			list.AddRange(earlierKeys);
			list.Sort(ConfigurationKeyComparer.Comparison);
			return list;
		}

		private static string Segment(string key, int prefixLength)
		{
			int num = key.IndexOf(':', prefixLength);
			if (num >= 0)
			{
				return key.Substring(prefixLength, num - prefixLength);
			}
			return key.Substring(prefixLength);
		}

		public IChangeToken GetReloadToken()
		{
			return _reloadToken;
		}

		protected void OnReload()
		{
			Interlocked.Exchange(ref _reloadToken, new ConfigurationReloadToken()).OnReload();
		}

		public override string ToString()
		{
			return GetType().Name;
		}
	}
	public class ConfigurationReloadToken : IChangeToken
	{
		private readonly CancellationTokenSource _cts = new CancellationTokenSource();

		public bool ActiveChangeCallbacks { get; private set; } = true;


		public bool HasChanged => _cts.IsCancellationRequested;

		public IDisposable RegisterChangeCallback(Action<object?> callback, object? state)
		{
			return ChangeCallbackRegistrar.UnsafeRegisterChangeCallback(callback, state, _cts.Token, delegate(ConfigurationReloadToken s)
			{
				s.ActiveChangeCallbacks = false;
			}, this);
		}

		public void OnReload()
		{
			_cts.Cancel();
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	[DebuggerTypeProxy(typeof(ConfigurationRootDebugView))]
	public class ConfigurationRoot : IConfigurationRoot, IConfiguration, IDisposable
	{
		private sealed class ConfigurationRootDebugView
		{
			private readonly ConfigurationRoot _current;

			[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
			public ConfigurationSectionDebugView[] Items => ConfigurationSectionDebugView.FromConfiguration(_current, _current).ToArray();

			public ConfigurationRootDebugView(ConfigurationRoot current)
			{
				_current = current;
			}
		}

		private readonly IList<IConfigurationProvider> _providers;

		private readonly List<IDisposable> _changeTokenRegistrations;

		private ConfigurationReloadToken _changeToken = new ConfigurationReloadToken();

		public IEnumerable<IConfigurationProvider> Providers => _providers;

		public string? this[string key]
		{
			get
			{
				return GetConfiguration(_providers, key);
			}
			set
			{
				SetConfiguration(_providers, key, value);
			}
		}

		public ConfigurationRoot(IList<IConfigurationProvider> providers)
		{
			System.ThrowHelper.ThrowIfNull(providers, "providers");
			_providers = providers;
			_changeTokenRegistrations = new List<IDisposable>(providers.Count);
			foreach (IConfigurationProvider provider in providers)
			{
				provider.Load();
				_changeTokenRegistrations.Add(ChangeToken.OnChange(provider.GetReloadToken, RaiseChanged));
			}
		}

		public IEnumerable<IConfigurationSection> GetChildren()
		{
			return this.GetChildrenImplementation(null);
		}

		public IChangeToken GetReloadToken()
		{
			return _changeToken;
		}

		public IConfigurationSection GetSection(string key)
		{
			return new ConfigurationSection(this, key);
		}

		public void Reload()
		{
			foreach (IConfigurationProvider provider in _providers)
			{
				provider.Load();
			}
			RaiseChanged();
		}

		private void RaiseChanged()
		{
			Interlocked.Exchange(ref _changeToken, new ConfigurationReloadToken()).OnReload();
		}

		public void Dispose()
		{
			foreach (IDisposable changeTokenRegistration in _changeTokenRegistrations)
			{
				changeTokenRegistration.Dispose();
			}
			foreach (IConfigurationProvider provider in _providers)
			{
				(provider as IDisposable)?.Dispose();
			}
		}

		internal static string? GetConfiguration(IList<IConfigurationProvider> providers, string key)
		{
			for (int num = providers.Count - 1; num >= 0; num--)
			{
				if (providers[num].TryGet(key, out var value))
				{
					return value;
				}
			}
			return null;
		}

		internal static void SetConfiguration(IList<IConfigurationProvider> providers, string key, string? value)
		{
			if (providers.Count == 0)
			{
				throw new InvalidOperationException(System.SR.Error_NoSources);
			}
			foreach (IConfigurationProvider provider in providers)
			{
				provider.Set(key, value);
			}
		}

		private string DebuggerToString()
		{
			return $"Sections = {ConfigurationSectionDebugView.FromConfiguration(this, this).Count}";
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	[DebuggerTypeProxy(typeof(ConfigurationSectionDebugView))]
	public class ConfigurationSection : IConfigurationSection, IConfiguration
	{
		private sealed class ConfigurationSectionDebugView
		{
			private readonly ConfigurationSection _current;

			private readonly IConfigurationProvider _provider;

			public string Path => _current.Path;

			public string Key => _current.Key;

			public string Value => _current.Value;

			public IConfigurationProvider Provider => _provider;

			public List<Microsoft.Extensions.Configuration.ConfigurationSectionDebugView> Sections => Microsoft.Extensions.Configuration.ConfigurationSectionDebugView.FromConfiguration(_current, _current._root);

			public ConfigurationSectionDebugView(ConfigurationSection current)
			{
				_current = current;
				_provider = Microsoft.Extensions.Configuration.ConfigurationSectionDebugView.GetValueProvider(_current._root, _current.Path);
			}
		}

		private readonly IConfigurationRoot _root;

		private readonly string _path;

		private string _key;

		public string Path => _path;

		public string Key => _key ?? (_key = ConfigurationPath.GetSectionKey(_path));

		public string? Value
		{
			get
			{
				return _root[Path];
			}
			set
			{
				_root[Path] = value;
			}
		}

		public string? this[string key]
		{
			get
			{
				return _root[Path + ConfigurationPath.KeyDelimiter + key];
			}
			set
			{
				_root[Path + ConfigurationPath.KeyDelimiter + key] = value;
			}
		}

		public ConfigurationSection(IConfigurationRoot root, string path)
		{
			System.ThrowHelper.ThrowIfNull(root, "root");
			System.ThrowHelper.ThrowIfNull(path, "path");
			_root = root;
			_path = path;
		}

		public IConfigurationSection GetSection(string key)
		{
			return _root.GetSection(Path + ConfigurationPath.KeyDelimiter + key);
		}

		public IEnumerable<IConfigurationSection> GetChildren()
		{
			return _root.GetChildrenImplementation(Path);
		}

		public IChangeToken GetReloadToken()
		{
			return _root.GetReloadToken();
		}

		private string DebuggerToString()
		{
			string text = "Path = " + Path;
			int count = Microsoft.Extensions.Configuration.ConfigurationSectionDebugView.FromConfiguration(this, _root).Count;
			if (count > 0)
			{
				text += $", Sections = {count}";
			}
			if (Value != null)
			{
				text = text + ", Value = " + Value;
				IConfigurationProvider valueProvider = Microsoft.Extensions.Configuration.ConfigurationSectionDebugView.GetValueProvider(_root, Path);
				if (valueProvider != null)
				{
					text += $", Provider = {valueProvider}";
				}
			}
			return text;
		}
	}
	internal sealed class ConfigurationSectionDebugView
	{
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private readonly IConfigurationSection _section;

		public string Path { get; }

		public string Key => _section.Key;

		public string FullPath => _section.Path;

		public string? Value => _section.Value;

		public IConfigurationProvider? Provider { get; }

		public ConfigurationSectionDebugView(IConfigurationSection section, string path, IConfigurationProvider? provider)
		{
			_section = section;
			Path = path;
			Provider = provider;
		}

		public override string ToString()
		{
			string text = "Path = " + Path;
			if (Value != null)
			{
				text = text + ", Value = " + Value;
			}
			if (Provider != null)
			{
				text += $", Provider = {Provider}";
			}
			return text;
		}

		internal static List<ConfigurationSectionDebugView> FromConfiguration(IConfiguration current, IConfigurationRoot root)
		{
			List<ConfigurationSectionDebugView> list = new List<ConfigurationSectionDebugView>();
			Stack<IConfiguration> stack = new Stack<IConfiguration>();
			stack.Push(current);
			int startIndex = ((current is IConfigurationSection configurationSection) ? (configurationSection.Path.Length + 1) : 0);
			while (stack.Count > 0)
			{
				IConfiguration configuration = stack.Pop();
				if (configuration is IConfigurationSection configurationSection2 && configuration != current)
				{
					IConfigurationProvider valueProvider = GetValueProvider(root, configurationSection2.Path);
					string path = configurationSection2.Path.Substring(startIndex);
					list.Add(new ConfigurationSectionDebugView(configurationSection2, path, valueProvider));
				}
				foreach (IConfigurationSection child in configuration.GetChildren())
				{
					stack.Push(child);
				}
			}
			list.Sort((ConfigurationSectionDebugView i1, ConfigurationSectionDebugView i2) => ConfigurationKeyComparer.Instance.Compare(i1.Path, i2.Path));
			return list;
		}

		internal static IConfigurationProvider? GetValueProvider(IConfigurationRoot root, string key)
		{
			foreach (IConfigurationProvider item in root.Providers.Reverse())
			{
				if (item.TryGet(key, out var _))
				{
					return item;
				}
			}
			return null;
		}
	}
	internal static class InternalConfigurationRootExtensions
	{
		internal static IEnumerable<IConfigurationSection> GetChildrenImplementation(this IConfigurationRoot root, string? path)
		{
			string path2 = path;
			IConfigurationRoot root2 = root;
			using ReferenceCountedProviders referenceCountedProviders = (root2 as ConfigurationManager)?.GetProvidersReference();
			IEnumerable<IConfigurationProvider> enumerable = referenceCountedProviders?.Providers;
			IEnumerable<IConfigurationSection> enumerable2 = from key in (enumerable ?? root2.Providers).Aggregate(Enumerable.Empty<string>(), (IEnumerable<string> seed, IConfigurationProvider source) => source.GetChildKeys(seed, path2)).Distinct<string>(StringComparer.OrdinalIgnoreCase)
				select root2.GetSection((path2 == null) ? key : (path2 + ConfigurationPath.KeyDelimiter + key));
			if (referenceCountedProviders == null)
			{
				return enumerable2;
			}
			return enumerable2.ToList();
		}
	}
	public static class MemoryConfigurationBuilderExtensions
	{
		public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder)
		{
			System.ThrowHelper.ThrowIfNull(configurationBuilder, "configurationBuilder");
			configurationBuilder.Add(new MemoryConfigurationSource());
			return configurationBuilder;
		}

		public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder, IEnumerable<KeyValuePair<string, string?>>? initialData)
		{
			System.ThrowHelper.ThrowIfNull(configurationBuilder, "configurationBuilder");
			configurationBuilder.Add(new MemoryConfigurationSource
			{
				InitialData = initialData
			});
			return configurationBuilder;
		}
	}
	internal abstract class ReferenceCountedProviders : IDisposable
	{
		private sealed class ActiveReferenceCountedProviders : ReferenceCountedProviders
		{
			private long _refCount = 1L;

			private volatile List<IConfigurationProvider> _providers;

			public override List<IConfigurationProvider> Providers
			{
				get
				{
					return _providers;
				}
				set
				{
					_providers = value;
				}
			}

			public override List<IConfigurationProvider> NonReferenceCountedProviders => _providers;

			public ActiveReferenceCountedProviders(List<IConfigurationProvider> providers)
			{
				_providers = providers;
			}

			public override void AddReference()
			{
				Interlocked.Increment(ref _refCount);
			}

			public override void Dispose()
			{
				if (Interlocked.Decrement(ref _refCount) != 0L)
				{
					return;
				}
				foreach (IConfigurationProvider provider in _providers)
				{
					(provider as IDisposable)?.Dispose();
				}
			}
		}

		private sealed class DisposedReferenceCountedProviders : ReferenceCountedProviders
		{
			public override List<IConfigurationProvider> Providers { get; set; }

			public override List<IConfigurationProvider> NonReferenceCountedProviders => Providers;

			public DisposedReferenceCountedProviders(List<IConfigurationProvider> providers)
			{
				Providers = providers;
			}

			public override void AddReference()
			{
			}

			public override void Dispose()
			{
			}
		}

		public abstract List<IConfigurationProvider> Providers { get; set; }

		public abstract List<IConfigurationProvider> NonReferenceCountedProviders { get; }

		public static ReferenceCountedProviders Create(List<IConfigurationProvider> providers)
		{
			return new ActiveReferenceCountedProviders(providers);
		}

		public static ReferenceCountedProviders CreateDisposed(List<IConfigurationProvider> providers)
		{
			return new DisposedReferenceCountedProviders(providers);
		}

		public abstract void AddReference();

		public abstract void Dispose();
	}
	internal sealed class ReferenceCountedProviderManager : IDisposable
	{
		private readonly object _replaceProvidersLock = new object();

		private ReferenceCountedProviders _refCountedProviders = ReferenceCountedProviders.Create(new List<IConfigurationProvider>());

		private bool _disposed;

		public IEnumerable<IConfigurationProvider> NonReferenceCountedProviders => _refCountedProviders.NonReferenceCountedProviders;

		public ReferenceCountedProviders GetReference()
		{
			lock (_replaceProvidersLock)
			{
				if (_disposed)
				{
					return ReferenceCountedProviders.CreateDisposed(_refCountedProviders.NonReferenceCountedProviders);
				}
				_refCountedProviders.AddReference();
				return _refCountedProviders;
			}
		}

		public void ReplaceProviders(List<IConfigurationProvider> providers)
		{
			ReferenceCountedProviders refCountedProviders = _refCountedProviders;
			lock (_replaceProvidersLock)
			{
				if (_disposed)
				{
					throw new ObjectDisposedException("ConfigurationManager");
				}
				_refCountedProviders = ReferenceCountedProviders.Create(providers);
			}
			refCountedProviders.Dispose();
		}

		public void AddProvider(IConfigurationProvider provider)
		{
			lock (_replaceProvidersLock)
			{
				if (_disposed)
				{
					throw new ObjectDisposedException("ConfigurationManager");
				}
				_refCountedProviders.Providers = new List<IConfigurationProvider>(_refCountedProviders.Providers) { provider };
			}
		}

		public void Dispose()
		{
			ReferenceCountedProviders refCountedProviders = _refCountedProviders;
			lock (_replaceProvidersLock)
			{
				_disposed = true;
			}
			refCountedProviders.Dispose();
		}
	}
	public abstract class StreamConfigurationProvider : ConfigurationProvider
	{
		private bool _loaded;

		public StreamConfigurationSource Source { get; }

		public StreamConfigurationProvider(StreamConfigurationSource source)
		{
			System.ThrowHelper.ThrowIfNull(source, "source");
			Source = source;
		}

		public abstract void Load(Stream stream);

		public override void Load()
		{
			if (_loaded)
			{
				throw new InvalidOperationException(System.SR.StreamConfigurationProvidersAlreadyLoaded);
			}
			if (Source.Stream == null)
			{
				throw new InvalidOperationException(System.SR.StreamConfigurationSourceStreamCannotBeNull);
			}
			Load(Source.Stream);
			_loaded = true;
		}
	}
	public abstract class StreamConfigurationSource : IConfigurationSource
	{
		public Stream? Stream
		{
			get; [param: DisallowNull]
			set;
		}

		public abstract IConfigurationProvider Build(IConfigurationBuilder builder);
	}
}
namespace Microsoft.Extensions.Configuration.Memory
{
	public class MemoryConfigurationProvider : ConfigurationProvider, IEnumerable<KeyValuePair<string, string?>>, IEnumerable
	{
		private readonly MemoryConfigurationSource _source;

		public MemoryConfigurationProvider(MemoryConfigurationSource source)
		{
			System.ThrowHelper.ThrowIfNull(source, "source");
			_source = source;
			if (_source.InitialData == null)
			{
				return;
			}
			foreach (KeyValuePair<string, string> initialDatum in _source.InitialData)
			{
				base.Data.Add(initialDatum.Key, initialDatum.Value);
			}
		}

		public void Add(string key, string? value)
		{
			base.Data.Add(key, value);
		}

		public IEnumerator<KeyValuePair<string, string?>> GetEnumerator()
		{
			return base.Data.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public class MemoryConfigurationSource : IConfigurationSource
	{
		public IEnumerable<KeyValuePair<string, string?>>? InitialData { get; set; }

		public IConfigurationProvider Build(IConfigurationBuilder builder)
		{
			return new MemoryConfigurationProvider(this);
		}
	}
}

Microsoft.Extensions.DependencyInjection.Abstractions.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using FxResources.Microsoft.Extensions.DependencyInjection.Abstractions;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection.Abstractions")]
[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("Abstractions for dependency injection.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.DependencyInjection.IServiceCollection")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection.Abstractions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.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]
	[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.Microsoft.Extensions.DependencyInjection.Abstractions
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string AmbiguousConstructorMatch => GetResourceString("AmbiguousConstructorMatch");

		internal static string CannotResolveService => GetResourceString("CannotResolveService");

		internal static string NoConstructorMatch => GetResourceString("NoConstructorMatch");

		internal static string NoServiceRegistered => GetResourceString("NoServiceRegistered");

		internal static string ServiceCollectionReadOnly => GetResourceString("ServiceCollectionReadOnly");

		internal static string TryAddIndistinguishableTypeToEnumerable => GetResourceString("TryAddIndistinguishableTypeToEnumerable");

		internal static string MultipleCtorsMarkedWithAttribute => GetResourceString("MultipleCtorsMarkedWithAttribute");

		internal static string MarkedCtorMissingArgumentTypes => GetResourceString("MarkedCtorMissingArgumentTypes");

		internal static string CannotCreateAbstractClasses => GetResourceString("CannotCreateAbstractClasses");

		internal static string MultipleCtorsFoundWithBestLength => GetResourceString("MultipleCtorsFoundWithBestLength");

		internal static string UnableToResolveService => GetResourceString("UnableToResolveService");

		internal static string CtorNotLocated => GetResourceString("CtorNotLocated");

		internal static string MultipleCtorsFound => GetResourceString("MultipleCtorsFound");

		internal static string KeyedServicesNotSupported => GetResourceString("KeyedServicesNotSupported");

		internal static string NonKeyedDescriptorMisuse => GetResourceString("NonKeyedDescriptorMisuse");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | 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,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace Microsoft.Extensions.Internal
{
	internal static class ParameterDefaultValue
	{
		public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue)
		{
			bool tryToGetDefaultValue;
			bool num = CheckHasDefaultValue(parameter, out tryToGetDefaultValue);
			defaultValue = null;
			if (num)
			{
				if (tryToGetDefaultValue)
				{
					defaultValue = parameter.DefaultValue;
				}
				bool flag = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>);
				if (defaultValue == null && parameter.ParameterType.IsValueType && !flag)
				{
					defaultValue = CreateValueType(parameter.ParameterType);
				}
				if (defaultValue != null && flag)
				{
					Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType);
					if (underlyingType != null && underlyingType.IsEnum)
					{
						defaultValue = Enum.ToObject(underlyingType, defaultValue);
					}
				}
			}
			return num;
			[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")]
			static object? CreateValueType(Type t)
			{
				return RuntimeHelpers.GetUninitializedObject(t);
			}
		}

		public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue)
		{
			tryToGetDefaultValue = true;
			try
			{
				return parameter.HasDefaultValue;
			}
			catch (FormatException) when (parameter.ParameterType == typeof(DateTime))
			{
				tryToGetDefaultValue = false;
				return true;
			}
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection
{
	public static class ActivatorUtilities
	{
		private readonly struct FactoryParameterContext
		{
			public Type ParameterType { get; }

			public bool HasDefaultValue { get; }

			public object DefaultValue { get; }

			public int ArgumentIndex { get; }

			public object ServiceKey { get; }

			public FactoryParameterContext(Type parameterType, bool hasDefaultValue, object defaultValue, int argumentIndex, object serviceKey)
			{
				ParameterType = parameterType;
				HasDefaultValue = hasDefaultValue;
				DefaultValue = defaultValue;
				ArgumentIndex = argumentIndex;
				ServiceKey = serviceKey;
			}
		}

		private sealed class ConstructorInfoEx
		{
			public readonly ConstructorInfo Info;

			public readonly ParameterInfo[] Parameters;

			public readonly bool IsPreferred;

			private readonly object[] _parameterKeys;

			public ConstructorInfoEx(ConstructorInfo constructor)
			{
				Info = constructor;
				Parameters = constructor.GetParameters();
				IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);
				for (int i = 0; i < Parameters.Length; i++)
				{
					FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);
					if (fromKeyedServicesAttribute != null)
					{
						if (_parameterKeys == null)
						{
							_parameterKeys = new object[Parameters.Length];
						}
						_parameterKeys[i] = fromKeyedServicesAttribute.Key;
					}
				}
			}

			public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
			{
				ParameterInfo parameterInfo = Parameters[parameterIndex];
				object[] parameterKeys = _parameterKeys;
				object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null);
				if (obj != null)
				{
					if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
					{
						return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, obj);
					}
					throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
				}
				return serviceProviderIsService.IsService(parameterInfo.ParameterType);
			}

			public object GetService(IServiceProvider serviceProvider, int parameterIndex)
			{
				ParameterInfo parameterInfo = Parameters[parameterIndex];
				object[] parameterKeys = _parameterKeys;
				object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null);
				if (obj != null)
				{
					if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
					{
						return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, obj);
					}
					throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
				}
				return serviceProvider.GetService(parameterInfo.ParameterType);
			}
		}

		private readonly ref struct ConstructorMatcher
		{
			private readonly ConstructorInfoEx _constructor;

			private readonly object[] _parameterValues;

			public ConstructorInfoEx ConstructorInfo => _constructor;

			public ConstructorMatcher(ConstructorInfoEx constructor, object[] parameterValues)
			{
				_constructor = constructor;
				_parameterValues = parameterValues;
			}

			public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
			{
				for (int i = 0; i < givenParameters.Length; i++)
				{
					Type c = givenParameters[i]?.GetType();
					bool flag = false;
					for (int j = 0; j < _constructor.Parameters.Length; j++)
					{
						if (_parameterValues[j] == null && _constructor.Parameters[j].ParameterType.IsAssignableFrom(c))
						{
							flag = true;
							_parameterValues[j] = givenParameters[i];
							break;
						}
					}
					if (!flag)
					{
						return -1;
					}
				}
				for (int k = 0; k < _constructor.Parameters.Length; k++)
				{
					if (_parameterValues[k] == null && !_constructor.IsService(serviceProviderIsService, k))
					{
						if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[k], out object defaultValue))
						{
							return -1;
						}
						_parameterValues[k] = defaultValue;
					}
				}
				return _constructor.Parameters.Length;
			}

			public object CreateInstance(IServiceProvider provider)
			{
				for (int i = 0; i < _constructor.Parameters.Length; i++)
				{
					if (_parameterValues[i] != null)
					{
						continue;
					}
					object service = _constructor.GetService(provider, i);
					if (service == null)
					{
						if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object defaultValue))
						{
							throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, _constructor.Parameters[i].ParameterType, _constructor.Info.DeclaringType));
						}
						_parameterValues[i] = defaultValue;
					}
					else
					{
						_parameterValues[i] = service;
					}
				}
				try
				{
					return _constructor.Info.Invoke(_parameterValues);
				}
				catch (TargetInvocationException ex) when (ex.InnerException != null)
				{
					ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
					throw;
				}
			}

			public void MapParameters(int?[] parameterMap, object[] givenParameters)
			{
				for (int i = 0; i < _constructor.Parameters.Length; i++)
				{
					if (parameterMap[i].HasValue)
					{
						_parameterValues[i] = givenParameters[parameterMap[i].Value];
					}
				}
			}
		}

		private static readonly MethodInfo GetServiceInfo = new Func<IServiceProvider, Type, Type, bool, object, object>(GetService).Method;

		public static object CreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, params object[] parameters)
		{
			if (provider == null)
			{
				throw new ArgumentNullException("provider");
			}
			if (instanceType.IsAbstract)
			{
				throw new InvalidOperationException(System.SR.CannotCreateAbstractClasses);
			}
			ConstructorInfoEx[] array = CreateConstructorInfoExs(instanceType);
			object[] ctorArgs2 = null;
			object[] array2 = null;
			ConstructorMatcher constructorMatcher = default(ConstructorMatcher);
			IServiceProviderIsService service = provider.GetService<IServiceProviderIsService>();
			ConstructorInfoEx constructorInfoEx;
			if (service != null)
			{
				for (int i = 0; i < array.Length; i++)
				{
					constructorInfoEx = array[i];
					if (!constructorInfoEx.IsPreferred)
					{
						continue;
					}
					for (int j = i + 1; j < array.Length; j++)
					{
						if (array[j].IsPreferred)
						{
							ThrowMultipleCtorsMarkedWithAttributeException();
						}
					}
					InitializeCtorArgValues(ref ctorArgs2, constructorInfoEx.Parameters.Length);
					constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs2);
					if (constructorMatcher.Match(parameters, service) == -1)
					{
						ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
					}
					return constructorMatcher.CreateInstance(provider);
				}
				int num = -1;
				ConstructorMatcher constructorMatcher2 = default(ConstructorMatcher);
				bool flag = false;
				for (int k = 0; k < array.Length; k++)
				{
					constructorInfoEx = array[k];
					InitializeCtorArgValues(ref ctorArgs2, constructorInfoEx.Parameters.Length);
					constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs2);
					int num2 = constructorMatcher.Match(parameters, service);
					if (num < num2)
					{
						num = num2;
						if (k == array.Length - 1)
						{
							array2 = ctorArgs2;
						}
						else
						{
							array2 = new object[num2];
							ctorArgs2.CopyTo(array2, 0);
						}
						constructorMatcher2 = new ConstructorMatcher(constructorMatcher.ConstructorInfo, array2);
						flag = false;
					}
					else if (num == num2)
					{
						flag = true;
					}
				}
				if (num != -1)
				{
					if (flag)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFoundWithBestLength, instanceType, num));
					}
					return constructorMatcher2.CreateInstance(provider);
				}
			}
			Type[] array3;
			if (parameters.Length == 0)
			{
				array3 = Type.EmptyTypes;
			}
			else
			{
				array3 = new Type[parameters.Length];
				for (int l = 0; l < array3.Length; l++)
				{
					array3[l] = parameters[l]?.GetType();
				}
			}
			FindApplicableConstructor(instanceType, array3, array, out var matchingConstructor, out var matchingParameterMap);
			constructorInfoEx = FindConstructorEx(matchingConstructor, array);
			InitializeCtorArgValues(ref ctorArgs2, constructorInfoEx.Parameters.Length);
			constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs2);
			constructorMatcher.MapParameters(matchingParameterMap, parameters);
			return constructorMatcher.CreateInstance(provider);
			static void InitializeCtorArgValues(ref object[] ctorArgs, int length)
			{
				if (ctorArgs != null && ctorArgs.Length == length)
				{
					Array.Clear(ctorArgs, 0, length);
				}
				else
				{
					ctorArgs = new object[length];
				}
			}
		}

		private static ConstructorInfoEx[] CreateConstructorInfoExs([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
		{
			ConstructorInfo[] constructors = type.GetConstructors();
			ConstructorInfoEx[] array = new ConstructorInfoEx[constructors.Length];
			for (int i = 0; i < constructors.Length; i++)
			{
				array[i] = new ConstructorInfoEx(constructors[i]);
			}
			return array;
		}

		public static ObjectFactory CreateFactory([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes)
		{
			if (!RuntimeFeature.IsDynamicCodeCompiled)
			{
				return CreateFactoryReflection(instanceType, argumentTypes);
			}
			CreateFactoryInternal(instanceType, argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody);
			return Expression.Lambda<Func<IServiceProvider, object[], object>>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }).Compile().Invoke;
		}

		public static ObjectFactory<T> CreateFactory<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(Type[] argumentTypes)
		{
			if (!RuntimeFeature.IsDynamicCodeCompiled)
			{
				ObjectFactory factory = CreateFactoryReflection(typeof(T), argumentTypes);
				return (IServiceProvider serviceProvider, object[] arguments) => (T)factory(serviceProvider, arguments);
			}
			CreateFactoryInternal(typeof(T), argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody);
			return Expression.Lambda<Func<IServiceProvider, object[], T>>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }).Compile().Invoke;
		}

		private static void CreateFactoryInternal([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ParameterExpression provider, out ParameterExpression argumentArray, out Expression factoryExpressionBody)
		{
			FindApplicableConstructor(instanceType, argumentTypes, null, out var matchingConstructor, out var matchingParameterMap);
			provider = Expression.Parameter(typeof(IServiceProvider), "provider");
			argumentArray = Expression.Parameter(typeof(object[]), "argumentArray");
			factoryExpressionBody = BuildFactoryExpression(matchingConstructor, matchingParameterMap, provider, argumentArray);
		}

		public static T CreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider, params object[] parameters)
		{
			return (T)CreateInstance(provider, typeof(T), parameters);
		}

		public static T GetServiceOrCreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider)
		{
			return (T)GetServiceOrCreateInstance(provider, typeof(T));
		}

		public static object GetServiceOrCreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
		{
			return provider.GetService(type) ?? CreateInstance(provider, type);
		}

		private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool hasDefaultValue, object key)
		{
			object obj = ((key == null) ? sp.GetService(type) : GetKeyedService(sp, type, key));
			if (obj == null && !hasDefaultValue)
			{
				ThrowHelperUnableToResolveService(type, requiredBy);
			}
			return obj;
		}

		[DoesNotReturn]
		private static void ThrowHelperUnableToResolveService(Type type, Type requiredBy)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, type, requiredBy));
		}

		private static BlockExpression BuildFactoryExpression(ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, Expression factoryArgumentArray)
		{
			ParameterInfo[] parameters = constructor.GetParameters();
			Expression[] array = new Expression[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				ParameterInfo parameterInfo = parameters[i];
				Type parameterType = parameterInfo.ParameterType;
				object defaultValue;
				bool flag = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue);
				if (parameterMap[i].HasValue)
				{
					array[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i]));
				}
				else
				{
					FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false);
					Expression[] arguments = new Expression[5]
					{
						serviceProvider,
						Expression.Constant(parameterType, typeof(Type)),
						Expression.Constant(constructor.DeclaringType, typeof(Type)),
						Expression.Constant(flag),
						Expression.Constant(fromKeyedServicesAttribute?.Key, typeof(object))
					};
					array[i] = Expression.Call(GetServiceInfo, arguments);
				}
				if (flag)
				{
					ConstantExpression right = Expression.Constant(defaultValue);
					array[i] = Expression.Coalesce(array[i], right);
				}
				array[i] = Expression.Convert(array[i], parameterType);
			}
			return Expression.Block(Expression.IfThen(Expression.Equal(serviceProvider, Expression.Constant(null)), Expression.Throw(Expression.Constant(new ArgumentNullException("serviceProvider")))), Expression.New(constructor, array));
		}

		[DoesNotReturn]
		private static void ThrowHelperArgumentNullExceptionServiceProvider()
		{
			throw new ArgumentNullException("serviceProvider");
		}

		private static ObjectFactory CreateFactoryReflection([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes)
		{
			FindApplicableConstructor(instanceType, argumentTypes, null, out var constructor, out var parameterMap);
			Type declaringType = constructor.DeclaringType;
			ParameterInfo[] constructorParameters = constructor.GetParameters();
			if (constructorParameters.Length == 0)
			{
				return (IServiceProvider serviceProvider, object[] arguments) => constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, null, null);
			}
			FactoryParameterContext[] parameters = GetFactoryParameterContext();
			return (IServiceProvider serviceProvider, object[] arguments) => ReflectionFactoryCanonical(constructor, parameters, declaringType, serviceProvider, arguments);
			FactoryParameterContext[] GetFactoryParameterContext()
			{
				FactoryParameterContext[] array = new FactoryParameterContext[constructorParameters.Length];
				for (int i = 0; i < constructorParameters.Length; i++)
				{
					ParameterInfo parameterInfo = constructorParameters[i];
					FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false);
					object defaultValue;
					bool hasDefaultValue = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue);
					array[i] = new FactoryParameterContext(parameterInfo.ParameterType, hasDefaultValue, defaultValue, parameterMap[i].GetValueOrDefault(-1), fromKeyedServicesAttribute?.Key);
				}
				return array;
			}
		}

		private static void FindApplicableConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, ConstructorInfoEx[] constructors, out ConstructorInfo matchingConstructor, out int?[] matchingParameterMap)
		{
			if (!TryFindPreferredConstructor(instanceType, argumentTypes, constructors, out var matchingConstructor2, out var parameterMap) && !TryFindMatchingConstructor(instanceType, argumentTypes, out matchingConstructor2, out parameterMap))
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.CtorNotLocated, instanceType));
			}
			matchingConstructor = matchingConstructor2;
			matchingParameterMap = parameterMap;
		}

		private static ConstructorInfoEx FindConstructorEx(ConstructorInfo constructorInfo, ConstructorInfoEx[] constructorExs)
		{
			for (int i = 0; i < constructorExs.Length; i++)
			{
				if ((object)constructorExs[i].Info == constructorInfo)
				{
					return constructorExs[i];
				}
			}
			return null;
		}

		private static bool TryFindMatchingConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap)
		{
			matchingConstructor = null;
			parameterMap = null;
			ConstructorInfo[] constructors = instanceType.GetConstructors();
			foreach (ConstructorInfo constructorInfo in constructors)
			{
				if (TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2))
				{
					if (matchingConstructor != null)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFound, instanceType));
					}
					matchingConstructor = constructorInfo;
					parameterMap = parameterMap2;
				}
			}
			if (matchingConstructor != null)
			{
				return true;
			}
			return false;
		}

		private static bool TryFindPreferredConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, ConstructorInfoEx[] constructors, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap)
		{
			bool flag = false;
			matchingConstructor = null;
			parameterMap = null;
			if (constructors == null)
			{
				constructors = CreateConstructorInfoExs(instanceType);
			}
			ConstructorInfoEx[] array = constructors;
			foreach (ConstructorInfoEx constructorInfoEx in array)
			{
				if (constructorInfoEx.IsPreferred)
				{
					if (flag)
					{
						ThrowMultipleCtorsMarkedWithAttributeException();
					}
					if (!TryCreateParameterMap(constructorInfoEx.Info.GetParameters(), argumentTypes, out var parameterMap2))
					{
						ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
					}
					matchingConstructor = constructorInfoEx.Info;
					parameterMap = parameterMap2;
					flag = true;
				}
			}
			if (matchingConstructor != null)
			{
				return true;
			}
			return false;
		}

		private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap)
		{
			parameterMap = new int?[constructorParameters.Length];
			for (int i = 0; i < argumentTypes.Length; i++)
			{
				bool flag = false;
				Type c = argumentTypes[i];
				for (int j = 0; j < constructorParameters.Length; j++)
				{
					if (!parameterMap[j].HasValue && constructorParameters[j].ParameterType.IsAssignableFrom(c))
					{
						flag = true;
						parameterMap[j] = i;
						break;
					}
				}
				if (!flag)
				{
					return false;
				}
			}
			return true;
		}

		private static void ThrowMultipleCtorsMarkedWithAttributeException()
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsMarkedWithAttribute, "ActivatorUtilitiesConstructorAttribute"));
		}

		private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments()
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.MarkedCtorMissingArgumentTypes, "ActivatorUtilitiesConstructorAttribute"));
		}

		private static object ReflectionFactoryCanonical(ConstructorInfo constructor, FactoryParameterContext[] parameters, Type declaringType, IServiceProvider serviceProvider, object[] arguments)
		{
			if (serviceProvider == null)
			{
				ThrowHelperArgumentNullExceptionServiceProvider();
			}
			object[] array = new object[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				ref FactoryParameterContext reference = ref parameters[i];
				array[i] = ((reference.ArgumentIndex != -1) ? arguments[reference.ArgumentIndex] : GetService(serviceProvider, reference.ParameterType, declaringType, reference.HasDefaultValue, reference.ServiceKey)) ?? reference.DefaultValue;
			}
			return constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, array, null);
		}

		private static object GetKeyedService(IServiceProvider provider, Type type, object serviceKey)
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			if (provider is IKeyedServiceProvider keyedServiceProvider)
			{
				return keyedServiceProvider.GetKeyedService(type, serviceKey);
			}
			throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
		}
	}
	[AttributeUsage(AttributeTargets.All)]
	public class ActivatorUtilitiesConstructorAttribute : Attribute
	{
	}
	[DebuggerDisplay("{ServiceProvider,nq}")]
	public readonly struct AsyncServiceScope : IServiceScope, IDisposable, IAsyncDisposable
	{
		private readonly IServiceScope _serviceScope;

		public IServiceProvider ServiceProvider => _serviceScope.ServiceProvider;

		public AsyncServiceScope(IServiceScope serviceScope)
		{
			System.ThrowHelper.ThrowIfNull(serviceScope, "serviceScope");
			_serviceScope = serviceScope;
		}

		public void Dispose()
		{
			_serviceScope.Dispose();
		}

		public ValueTask DisposeAsync()
		{
			if (_serviceScope is IAsyncDisposable asyncDisposable)
			{
				return asyncDisposable.DisposeAsync();
			}
			_serviceScope.Dispose();
			return default(ValueTask);
		}
	}
	[AttributeUsage(AttributeTargets.Parameter)]
	public class FromKeyedServicesAttribute : Attribute
	{
		public object Key { get; }

		public FromKeyedServicesAttribute(object key)
		{
			Key = key;
		}
	}
	public interface IKeyedServiceProvider : IServiceProvider
	{
		object? GetKeyedService(Type serviceType, object? serviceKey);

		object GetRequiredKeyedService(Type serviceType, object? serviceKey);
	}
	public static class KeyedService
	{
		private sealed class AnyKeyObj
		{
			public override string ToString()
			{
				return "*";
			}
		}

		public static object AnyKey { get; } = new AnyKeyObj();

	}
	public interface IServiceCollection : IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable
	{
	}
	public interface IServiceProviderFactory<TContainerBuilder> where TContainerBuilder : notnull
	{
		TContainerBuilder CreateBuilder(IServiceCollection services);

		IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder);
	}
	public interface IServiceProviderIsKeyedService : IServiceProviderIsService
	{
		bool IsKeyedService(Type serviceType, object? serviceKey);
	}
	public interface IServiceProviderIsService
	{
		bool IsService(Type serviceType);
	}
	public interface IServiceScope : IDisposable
	{
		IServiceProvider ServiceProvider { get; }
	}
	public interface IServiceScopeFactory
	{
		IServiceScope CreateScope();
	}
	public interface ISupportRequiredService
	{
		object GetRequiredService(Type serviceType);
	}
	public delegate object ObjectFactory(IServiceProvider serviceProvider, object?[]? arguments);
	public delegate T ObjectFactory<T>(IServiceProvider serviceProvider, object?[]? arguments);
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	[DebuggerTypeProxy(typeof(ServiceCollectionDebugView))]
	public class ServiceCollection : IServiceCollection, IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable
	{
		private sealed class ServiceCollectionDebugView
		{
			private readonly ServiceCollection _services;

			[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
			public ServiceDescriptor[] Items
			{
				get
				{
					ServiceDescriptor[] array = new ServiceDescriptor[_services.Count];
					_services.CopyTo(array, 0);
					return array;
				}
			}

			public ServiceCollectionDebugView(ServiceCollection services)
			{
				_services = services;
			}
		}

		private readonly List<ServiceDescriptor> _descriptors = new List<ServiceDescriptor>();

		private bool _isReadOnly;

		public int Count => _descriptors.Count;

		public bool IsReadOnly => _isReadOnly;

		public ServiceDescriptor this[int index]
		{
			get
			{
				return _descriptors[index];
			}
			set
			{
				CheckReadOnly();
				_descriptors[index] = value;
			}
		}

		public void Clear()
		{
			CheckReadOnly();
			_descriptors.Clear();
		}

		public bool Contains(ServiceDescriptor item)
		{
			return _descriptors.Contains(item);
		}

		public void CopyTo(ServiceDescriptor[] array, int arrayIndex)
		{
			_descriptors.CopyTo(array, arrayIndex);
		}

		public bool Remove(ServiceDescriptor item)
		{
			CheckReadOnly();
			return _descriptors.Remove(item);
		}

		public IEnumerator<ServiceDescriptor> GetEnumerator()
		{
			return _descriptors.GetEnumerator();
		}

		void ICollection<ServiceDescriptor>.Add(ServiceDescriptor item)
		{
			CheckReadOnly();
			_descriptors.Add(item);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public int IndexOf(ServiceDescriptor item)
		{
			return _descriptors.IndexOf(item);
		}

		public void Insert(int index, ServiceDescriptor item)
		{
			CheckReadOnly();
			_descriptors.Insert(index, item);
		}

		public void RemoveAt(int index)
		{
			CheckReadOnly();
			_descriptors.RemoveAt(index);
		}

		public void MakeReadOnly()
		{
			_isReadOnly = true;
		}

		private void CheckReadOnly()
		{
			if (_isReadOnly)
			{
				ThrowReadOnlyException();
			}
		}

		private static void ThrowReadOnlyException()
		{
			throw new InvalidOperationException(System.SR.ServiceCollectionReadOnly);
		}

		private string DebuggerToString()
		{
			string text = $"Count = {_descriptors.Count}";
			if (_isReadOnly)
			{
				text += ", IsReadOnly = true";
			}
			return text;
		}
	}
	public static class ServiceCollectionServiceExtensions
	{
		public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return Add(services, serviceType, implementationType, ServiceLifetime.Transient);
		}

		public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient);
		}

		public static IServiceCollection AddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddTransient(typeof(TService), typeof(TImplementation));
		}

		public static IServiceCollection AddTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			return services.AddTransient(serviceType, serviceType);
		}

		public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddTransient(typeof(TService));
		}

		public static IServiceCollection AddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddTransient(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddTransient(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return Add(services, serviceType, implementationType, ServiceLifetime.Scoped);
		}

		public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped);
		}

		public static IServiceCollection AddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddScoped(typeof(TService), typeof(TImplementation));
		}

		public static IServiceCollection AddScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			return services.AddScoped(serviceType, serviceType);
		}

		public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddScoped(typeof(TService));
		}

		public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddScoped(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddScoped<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddScoped(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return Add(services, serviceType, implementationType, ServiceLifetime.Singleton);
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton);
		}

		public static IServiceCollection AddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddSingleton(typeof(TService), typeof(TImplementation));
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			return services.AddSingleton(serviceType, serviceType);
		}

		public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddSingleton(typeof(TService));
		}

		public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddSingleton(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddSingleton(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, object implementationInstance)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance");
			ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationInstance);
			services.Add(item);
			return services;
		}

		public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, TService implementationInstance) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance");
			return services.AddSingleton(typeof(TService), implementationInstance);
		}

		private static IServiceCollection Add(IServiceCollection collection, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
		{
			ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationType, lifetime);
			collection.Add(item);
			return collection;
		}

		private static IServiceCollection Add(IServiceCollection collection, Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime)
		{
			ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationFactory, lifetime);
			collection.Add(item);
			return collection;
		}

		public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Transient);
		}

		public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Transient);
		}

		public static IServiceCollection AddKeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation));
		}

		public static IServiceCollection AddKeyedTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			return services.AddKeyedTransient(serviceType, serviceKey, serviceType);
		}

		public static IServiceCollection AddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddKeyedTransient(typeof(TService), serviceKey);
		}

		public static IServiceCollection AddKeyedTransient<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedTransient<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Scoped);
		}

		public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Scoped);
		}

		public static IServiceCollection AddKeyedScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddKeyedScoped(typeof(TService), serviceKey, typeof(TImplementation));
		}

		public static IServiceCollection AddKeyedScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			return services.AddKeyedScoped(serviceType, serviceKey, serviceType);
		}

		public static IServiceCollection AddKeyedScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddKeyedScoped(typeof(TService), serviceKey);
		}

		public static IServiceCollection AddKeyedScoped<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedScoped<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Singleton);
		}

		public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton);
		}

		public static IServiceCollection AddKeyedSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TImplementation));
		}

		public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			return services.AddKeyedSingleton(serviceType, serviceKey, serviceType);
		}

		public static IServiceCollection AddKeyedSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TService));
		}

		public static IServiceCollection AddKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedSingleton<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, object implementationInstance)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance");
			ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationInstance);
			services.Add(item);
			return services;
		}

		public static IServiceCollection AddKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, TService implementationInstance) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationInstance);
		}

		private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
		{
			ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime);
			collection.Add(item);
			return collection;
		}

		private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, Func<IServiceProvider, object, object> implementationFactory, ServiceLifetime lifetime)
		{
			ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime);
			collection.Add(item);
			return collection;
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	public class ServiceDescriptor
	{
		[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
		private Type _implementationType;

		private object _implementationInstance;

		private object _implementationFactory;

		public ServiceLifetime Lifetime { get; }

		public object? ServiceKey { get; }

		public Type ServiceType { get; }

		[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
		public Type? ImplementationType
		{
			get
			{
				if (!IsKeyedService)
				{
					return _implementationType;
				}
				return null;
			}
		}

		[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
		public Type? KeyedImplementationType
		{
			get
			{
				if (!IsKeyedService)
				{
					ThrowNonKeyedDescriptor();
				}
				return _implementationType;
			}
		}

		public object? ImplementationInstance
		{
			get
			{
				if (!IsKeyedService)
				{
					return _implementationInstance;
				}
				return null;
			}
		}

		public object? KeyedImplementationInstance
		{
			get
			{
				if (!IsKeyedService)
				{
					ThrowNonKeyedDescriptor();
				}
				return _implementationInstance;
			}
		}

		public Func<IServiceProvider, object>? ImplementationFactory
		{
			get
			{
				if (!IsKeyedService)
				{
					return (Func<IServiceProvider, object>)_implementationFactory;
				}
				return null;
			}
		}

		public Func<IServiceProvider, object?, object>? KeyedImplementationFactory
		{
			get
			{
				if (!IsKeyedService)
				{
					ThrowNonKeyedDescriptor();
				}
				return (Func<IServiceProvider, object, object>)_implementationFactory;
			}
		}

		public bool IsKeyedService => ServiceKey != null;

		public ServiceDescriptor(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
			: this(serviceType, null, implementationType, lifetime)
		{
		}

		public ServiceDescriptor(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
			: this(serviceType, serviceKey, lifetime)
		{
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			_implementationType = implementationType;
		}

		public ServiceDescriptor(Type serviceType, object instance)
			: this(serviceType, null, instance)
		{
		}

		public ServiceDescriptor(Type serviceType, object? serviceKey, object instance)
			: this(serviceType, serviceKey, ServiceLifetime.Singleton)
		{
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(instance, "instance");
			_implementationInstance = instance;
		}

		public ServiceDescriptor(Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime)
			: this(serviceType, (object)null, lifetime)
		{
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(factory, "factory");
			_implementationFactory = factory;
		}

		public ServiceDescriptor(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> factory, ServiceLifetime lifetime)
		{
			Func<IServiceProvider, object, object> factory2 = factory;
			this..ctor(serviceType, serviceKey, lifetime);
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(factory2, "factory");
			if (serviceKey == null)
			{
				Func<IServiceProvider, object> implementationFactory = (IServiceProvider sp) => factory2(sp, null);
				_implementationFactory = implementationFactory;
			}
			else
			{
				_implementationFactory = factory2;
			}
		}

		private ServiceDescriptor(Type serviceType, object serviceKey, ServiceLifetime lifetime)
		{
			Lifetime = lifetime;
			ServiceType = serviceType;
			ServiceKey = serviceKey;
		}

		public override string ToString()
		{
			string text = string.Format("{0}: {1} {2}: {3} ", "ServiceType", ServiceType, "Lifetime", Lifetime);
			if (IsKeyedService)
			{
				text += string.Format("{0}: {1} ", "ServiceKey", ServiceKey);
				if (KeyedImplementationType != null)
				{
					return text + string.Format("{0}: {1}", "KeyedImplementationType", KeyedImplementationType);
				}
				if (KeyedImplementationFactory != null)
				{
					return text + string.Format("{0}: {1}", "KeyedImplementationFactory", KeyedImplementationFactory.Method);
				}
				return text + string.Format("{0}: {1}", "KeyedImplementationInstance", KeyedImplementationInstance);
			}
			if (ImplementationType != null)
			{
				return text + string.Format("{0}: {1}", "ImplementationType", ImplementationType);
			}
			if (ImplementationFactory != null)
			{
				return text + string.Format("{0}: {1}", "ImplementationFactory", ImplementationFactory.Method);
			}
			return text + string.Format("{0}: {1}", "ImplementationInstance", ImplementationInstance);
		}

		internal Type GetImplementationType()
		{
			if (ServiceKey == null)
			{
				if (ImplementationType != null)
				{
					return ImplementationType;
				}
				if (ImplementationInstance != null)
				{
					return ImplementationInstance.GetType();
				}
				if (ImplementationFactory != null)
				{
					return ImplementationFactory.GetType().GenericTypeArguments[1];
				}
			}
			else
			{
				if (KeyedImplementationType != null)
				{
					return KeyedImplementationType;
				}
				if (KeyedImplementationInstance != null)
				{
					return KeyedImplementationInstance.GetType();
				}
				if (KeyedImplementationFactory != null)
				{
					return KeyedImplementationFactory.GetType().GenericTypeArguments[2];
				}
			}
			return null;
		}

		public static ServiceDescriptor Transient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return Describe(service, implementationType, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient(Type service, Func<IServiceProvider, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(service, implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Scoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			return Describe(service, implementationType, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped(Type service, Func<IServiceProvider, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(service, implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Singleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return Describe(service, implementationType, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton(Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton<TService>(TService implementationInstance) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance");
			return Singleton(typeof(TService), implementationInstance);
		}

		public static ServiceDescriptor KeyedSingleton<TService>(object? serviceKey, TService implementationInstance) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance");
			return KeyedSingleton(typeof(TService), serviceKey, implementationInstance);
		}

		public static ServiceDescriptor Singleton(Type serviceType, object implementationInstance)
		{
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance");
			return new ServiceDescriptor(serviceType, implementationInstance);
		}

		public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, object implementationInstance)
		{
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance");
			return new ServiceDescriptor(serviceType, serviceKey, implementationInstance);
		}

		private static ServiceDescriptor DescribeKeyed<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object serviceKey, ServiceLifetime lifetime) where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed(typeof(TService), serviceKey, typeof(TImplementation), lifetime);
		}

		public static ServiceDescriptor Describe(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
		{
			return new ServiceDescriptor(serviceType, implementationType, lifetime);
		}

		public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
		{
			return new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime);
		}

		public static ServiceDescriptor Describe(Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime)
		{
			return new ServiceDescriptor(serviceType, implementationFactory, lifetime);
		}

		public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory, ServiceLifetime lifetime)
		{
			return new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime);
		}

		private string DebuggerToString()
		{
			string text = $"Lifetime = {Lifetime}, ServiceType = \"{ServiceType.FullName}\"";
			if (IsKeyedService)
			{
				text += $", ServiceKey = \"{ServiceKey}\"";
				if (KeyedImplementationType != null)
				{
					return text + ", KeyedImplementationType = \"" + KeyedImplementationType.FullName + "\"";
				}
				if (KeyedImplementationFactory != null)
				{
					return text + $", KeyedImplementationFactory = {KeyedImplementationFactory.Method}";
				}
				return text + $", KeyedImplementationInstance = {KeyedImplementationInstance}";
			}
			if (ImplementationType != null)
			{
				return text + ", ImplementationType = \"" + ImplementationType.FullName + "\"";
			}
			if (ImplementationFactory != null)
			{
				return text + $", ImplementationFactory = {ImplementationFactory.Method}";
			}
			return text + $", ImplementationInstance = {ImplementationInstance}";
		}

		private static void ThrowNonKeyedDescriptor()
		{
			throw new InvalidOperationException(System.SR.NonKeyedDescriptorMisuse);
		}
	}
	[AttributeUsage(AttributeTargets.Parameter)]
	public class ServiceKeyAttribute : Attribute
	{
	}
	public enum ServiceLifetime
	{
		Singleton,
		Scoped,
		Transient
	}
	public static class ServiceProviderKeyedServiceExtensions
	{
		public static T? GetKeyedService<T>(this IServiceProvider provider, object? serviceKey)
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			if (provider is IKeyedServiceProvider keyedServiceProvider)
			{
				return (T)keyedServiceProvider.GetKeyedService(typeof(T), serviceKey);
			}
			throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
		}

		public static object GetRequiredKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey)
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			if (provider is IKeyedServiceProvider keyedServiceProvider)
			{
				return keyedServiceProvider.GetRequiredKeyedService(serviceType, serviceKey);
			}
			throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
		}

		public static T GetRequiredKeyedService<T>(this IServiceProvider provider, object? serviceKey) where T : notnull
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			return (T)provider.GetRequiredKeyedService(typeof(T), serviceKey);
		}

		public static IEnumerable<T> GetKeyedServices<T>(this IServiceProvider provider, object? serviceKey)
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			return provider.GetRequiredKeyedService<IEnumerable<T>>(serviceKey);
		}

		[RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")]
		public static IEnumerable<object?> GetKeyedServices(this IServiceProvider provider, Type serviceType, object? serviceKey)
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType);
			return (IEnumerable<object>)provider.GetRequiredKeyedService(serviceType2, serviceKey);
		}
	}
	public static class ServiceProviderServiceExtensions
	{
		public static T? GetService<T>(this IServiceProvider provider)
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			return (T)provider.GetService(typeof(T));
		}

		public static object GetRequiredService(this IServiceProvider provider, Type serviceType)
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			if (provider is ISupportRequiredService supportRequiredService)
			{
				return supportRequiredService.GetRequiredService(serviceType);
			}
			return provider.GetService(serviceType) ?? throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType));
		}

		public static T GetRequiredService<T>(this IServiceProvider provider) where T : notnull
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			return (T)provider.GetRequiredService(typeof(T));
		}

		public static IEnumerable<T> GetServices<T>(this IServiceProvider provider)
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			return provider.GetRequiredService<IEnumerable<T>>();
		}

		[RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")]
		public static IEnumerable<object?> GetServices(this IServiceProvider provider, Type serviceType)
		{
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType);
			return (IEnumerable<object>)provider.GetRequiredService(serviceType2);
		}

		public static IServiceScope CreateScope(this IServiceProvider provider)
		{
			return provider.GetRequiredService<IServiceScopeFactory>().CreateScope();
		}

		public static AsyncServiceScope CreateAsyncScope(this IServiceProvider provider)
		{
			return new AsyncServiceScope(provider.CreateScope());
		}

		public static AsyncServiceScope CreateAsyncScope(this IServiceScopeFactory serviceScopeFactory)
		{
			return new AsyncServiceScope(serviceScopeFactory.CreateScope());
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection.Extensions
{
	public static class ServiceCollectionDescriptorExtensions
	{
		public static IServiceCollection Add(this IServiceCollection collection, ServiceDescriptor descriptor)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(descriptor, "descriptor");
			collection.Add(descriptor);
			return collection;
		}

		public static IServiceCollection Add(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(descriptors, "descriptors");
			foreach (ServiceDescriptor descriptor in descriptors)
			{
				collection.Add(descriptor);
			}
			return collection;
		}

		public static void TryAdd(this IServiceCollection collection, ServiceDescriptor descriptor)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(descriptor, "descriptor");
			int count = collection.Count;
			for (int i = 0; i < count; i++)
			{
				if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey))
				{
					return;
				}
			}
			collection.Add(descriptor);
		}

		public static void TryAdd(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(descriptors, "descriptors");
			foreach (ServiceDescriptor descriptor in descriptors)
			{
				collection.TryAdd(descriptor);
			}
		}

		public static void TryAddTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddTransient(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddTransient(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			collection.TryAddTransient(typeof(TService), typeof(TService));
		}

		public static void TryAddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			collection.TryAddTransient(typeof(TService), typeof(TImplementation));
		}

		public static void TryAddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			services.TryAdd(ServiceDescriptor.Transient(implementationFactory));
		}

		public static void TryAddScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddScoped(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddScoped(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			collection.TryAddScoped(typeof(TService), typeof(TService));
		}

		public static void TryAddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			collection.TryAddScoped(typeof(TService), typeof(TImplementation));
		}

		public static void TryAddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			services.TryAdd(ServiceDescriptor.Scoped(implementationFactory));
		}

		public static void TryAddSingleton(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			collection.TryAddSingleton(typeof(TService), typeof(TService));
		}

		public static void TryAddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			collection.TryAddSingleton(typeof(TService), typeof(TImplementation));
		}

		public static void TryAddSingleton<TService>(this IServiceCollection collection, TService instance) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(instance, "instance");
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(typeof(TService), instance);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			services.TryAdd(ServiceDescriptor.Singleton(implementationFactory));
		}

		public static void TryAddEnumerable(this IServiceCollection services, ServiceDescriptor descriptor)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(descriptor, "descriptor");
			Type implementationType = descriptor.GetImplementationType();
			if (implementationType == typeof(object) || implementationType == descriptor.ServiceType)
			{
				throw new ArgumentException(System.SR.Format(System.SR.TryAddIndistinguishableTypeToEnumerable, implementationType, descriptor.ServiceType), "descriptor");
			}
			int count = services.Count;
			for (int i = 0; i < count; i++)
			{
				ServiceDescriptor serviceDescriptor = services[i];
				if (serviceDescriptor.ServiceType == descriptor.ServiceType && serviceDescriptor.GetImplementationType() == implementationType && object.Equals(serviceDescriptor.ServiceKey, descriptor.ServiceKey))
				{
					return;
				}
			}
			services.Add(descriptor);
		}

		public static void TryAddEnumerable(this IServiceCollection services, IEnumerable<ServiceDescriptor> descriptors)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(descriptors, "descriptors");
			foreach (ServiceDescriptor descriptor in descriptors)
			{
				services.TryAddEnumerable(descriptor);
			}
		}

		public static IServiceCollection Replace(this IServiceCollection collection, ServiceDescriptor descriptor)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(descriptor, "descriptor");
			int count = collection.Count;
			for (int i = 0; i < count; i++)
			{
				if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey))
				{
					collection.RemoveAt(i);
					break;
				}
			}
			collection.Add(descriptor);
			return collection;
		}

		public static IServiceCollection RemoveAll<T>(this IServiceCollection collection)
		{
			return collection.RemoveAll(typeof(T));
		}

		public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType)
		{
			System.ThrowHelper.ThrowIfNull(serviceType, "serviceType");
			for (int num = collection.Count - 1; num >= 0; num--)
			{
				ServiceDescriptor serviceDescriptor = collection[num];
				if (serviceDescriptor.ServiceType == serviceType && serviceDescriptor.ServiceKey == null)
				{
					collection.RemoveAt(num);
				}
			}
			return collection;
		}

		public static void TryAddKeyedTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddKeyedTransient(this IServiceCollection collection, Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationType, "implementationType");
			ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddKeyedTransient(this IServiceCollection collection, Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			System.ThrowHelper.ThrowIfNull(service, "service");
			System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory");
			ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection, object? serviceKey) where TService : class
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			collection.TryAddKeyedTransient(typeof(TService), serviceKey, typeof(TService));
		}

		public static void TryAddKeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection, object? serviceKey) where TService : class where TImplementation : class, TService
		{
			System.ThrowHelper.ThrowIfNull(collection, "collection");
			collection.TryAddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation));
		}

		public static void TryAddKeyedTransient<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			services.TryAdd(ServiceDescriptor.KeyedTransient(serviceKey, implementationFactory));
		}

		public static void TryAddKeyedScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] 

Microsoft.Extensions.DependencyInjection.dll

Decompiled a month ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FxResources.Microsoft.Extensions.DependencyInjection;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.ServiceLookup;
using Microsoft.Extensions.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("MicroBenchmarks, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection")]
[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("Default implementation of dependency injection for Microsoft.Extensions.DependencyInjection.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[assembly: TypeForwardedTo(typeof(ServiceCollection))]
[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]
	[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.Microsoft.Extensions.DependencyInjection
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string AmbiguousConstructorException => GetResourceString("AmbiguousConstructorException");

		internal static string CannotResolveService => GetResourceString("CannotResolveService");

		internal static string CircularDependencyException => GetResourceString("CircularDependencyException");

		internal static string UnableToActivateTypeException => GetResourceString("UnableToActivateTypeException");

		internal static string OpenGenericServiceRequiresOpenGenericImplementation => GetResourceString("OpenGenericServiceRequiresOpenGenericImplementation");

		internal static string ArityOfOpenGenericServiceNotEqualArityOfOpenGenericImplementation => GetResourceString("ArityOfOpenGenericServiceNotEqualArityOfOpenGenericImplementation");

		internal static string TypeCannotBeActivated => GetResourceString("TypeCannotBeActivated");

		internal static string NoConstructorMatch => GetResourceString("NoConstructorMatch");

		internal static string ScopedInSingletonException => GetResourceString("ScopedInSingletonException");

		internal static string ScopedResolvedFromRootException => GetResourceString("ScopedResolvedFromRootException");

		internal static string DirectScopedResolvedFromRootException => GetResourceString("DirectScopedResolvedFromRootException");

		internal static string ConstantCantBeConvertedToServiceType => GetResourceString("ConstantCantBeConvertedToServiceType");

		internal static string ImplementationTypeCantBeConvertedToServiceType => GetResourceString("ImplementationTypeCantBeConvertedToServiceType");

		internal static string AsyncDisposableServiceDispose => GetResourceString("AsyncDisposableServiceDispose");

		internal static string GetCaptureDisposableNotSupported => GetResourceString("GetCaptureDisposableNotSupported");

		internal static string InvalidServiceDescriptor => GetResourceString("InvalidServiceDescriptor");

		internal static string ServiceDescriptorNotExist => GetResourceString("ServiceDescriptorNotExist");

		internal static string CallSiteTypeNotSupported => GetResourceString("CallSiteTypeNotSupported");

		internal static string TrimmingAnnotationsDoNotMatch => GetResourceString("TrimmingAnnotationsDoNotMatch");

		internal static string TrimmingAnnotationsDoNotMatch_NewConstraint => GetResourceString("TrimmingAnnotationsDoNotMatch_NewConstraint");

		internal static string AotCannotCreateEnumerableValueType => GetResourceString("AotCannotCreateEnumerableValueType");

		internal static string AotCannotCreateGenericValueType => GetResourceString("AotCannotCreateGenericValueType");

		internal static string NoServiceRegistered => GetResourceString("NoServiceRegistered");

		internal static string InvalidServiceKeyType => GetResourceString("InvalidServiceKeyType");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.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.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | 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,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[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 Microsoft.Extensions.Internal
{
	internal static class ParameterDefaultValue
	{
		public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue)
		{
			bool tryToGetDefaultValue;
			bool num = CheckHasDefaultValue(parameter, out tryToGetDefaultValue);
			defaultValue = null;
			if (num)
			{
				if (tryToGetDefaultValue)
				{
					defaultValue = parameter.DefaultValue;
				}
				bool flag = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>);
				if (defaultValue == null && parameter.ParameterType.IsValueType && !flag)
				{
					defaultValue = CreateValueType(parameter.ParameterType);
				}
				if (defaultValue != null && flag)
				{
					Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType);
					if (underlyingType != null && underlyingType.IsEnum)
					{
						defaultValue = Enum.ToObject(underlyingType, defaultValue);
					}
				}
			}
			return num;
			[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")]
			static object? CreateValueType(Type t)
			{
				return RuntimeHelpers.GetUninitializedObject(t);
			}
		}

		public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue)
		{
			tryToGetDefaultValue = true;
			try
			{
				return parameter.HasDefaultValue;
			}
			catch (FormatException) when (parameter.ParameterType == typeof(DateTime))
			{
				tryToGetDefaultValue = false;
				return true;
			}
		}
	}
	internal static class TypeNameHelper
	{
		private readonly struct DisplayNameOptions
		{
			public bool FullName { get; }

			public bool IncludeGenericParameters { get; }

			public bool IncludeGenericParameterNames { get; }

			public char NestedTypeDelimiter { get; }

			public DisplayNameOptions(bool fullName, bool includeGenericParameterNames, bool includeGenericParameters, char nestedTypeDelimiter)
			{
				FullName = fullName;
				IncludeGenericParameters = includeGenericParameters;
				IncludeGenericParameterNames = includeGenericParameterNames;
				NestedTypeDelimiter = nestedTypeDelimiter;
			}
		}

		private const char DefaultNestedTypeDelimiter = '+';

		private static readonly Dictionary<Type, string> _builtInTypeNames = new Dictionary<Type, string>
		{
			{
				typeof(void),
				"void"
			},
			{
				typeof(bool),
				"bool"
			},
			{
				typeof(byte),
				"byte"
			},
			{
				typeof(char),
				"char"
			},
			{
				typeof(decimal),
				"decimal"
			},
			{
				typeof(double),
				"double"
			},
			{
				typeof(float),
				"float"
			},
			{
				typeof(int),
				"int"
			},
			{
				typeof(long),
				"long"
			},
			{
				typeof(object),
				"object"
			},
			{
				typeof(sbyte),
				"sbyte"
			},
			{
				typeof(short),
				"short"
			},
			{
				typeof(string),
				"string"
			},
			{
				typeof(uint),
				"uint"
			},
			{
				typeof(ulong),
				"ulong"
			},
			{
				typeof(ushort),
				"ushort"
			}
		};

		[return: NotNullIfNotNull("item")]
		public static string? GetTypeDisplayName(object? item, bool fullName = true)
		{
			if (item != null)
			{
				return GetTypeDisplayName(item.GetType(), fullName);
			}
			return null;
		}

		public static string GetTypeDisplayName(Type type, bool fullName = true, bool includeGenericParameterNames = false, bool includeGenericParameters = true, char nestedTypeDelimiter = '+')
		{
			StringBuilder builder = null;
			DisplayNameOptions options = new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter);
			return ProcessType(ref builder, type, in options) ?? builder?.ToString() ?? string.Empty;
		}

		private static string ProcessType(ref StringBuilder builder, Type type, in DisplayNameOptions options)
		{
			string value;
			if (type.IsGenericType)
			{
				Type[] genericArguments = type.GetGenericArguments();
				if (builder == null)
				{
					builder = new StringBuilder();
				}
				ProcessGenericType(builder, type, genericArguments, genericArguments.Length, in options);
			}
			else if (type.IsArray)
			{
				if (builder == null)
				{
					builder = new StringBuilder();
				}
				ProcessArrayType(builder, type, in options);
			}
			else if (_builtInTypeNames.TryGetValue(type, out value))
			{
				if (builder == null)
				{
					return value;
				}
				builder.Append(value);
			}
			else if (type.IsGenericParameter)
			{
				if (options.IncludeGenericParameterNames)
				{
					if (builder == null)
					{
						return type.Name;
					}
					builder.Append(type.Name);
				}
			}
			else
			{
				string text = (options.FullName ? type.FullName : type.Name);
				if (builder == null)
				{
					if (options.NestedTypeDelimiter != '+')
					{
						return text.Replace('+', options.NestedTypeDelimiter);
					}
					return text;
				}
				builder.Append(text);
				if (options.NestedTypeDelimiter != '+')
				{
					builder.Replace('+', options.NestedTypeDelimiter, builder.Length - text.Length, text.Length);
				}
			}
			return null;
		}

		private static void ProcessArrayType(StringBuilder builder, Type type, in DisplayNameOptions options)
		{
			Type type2 = type;
			while (type2.IsArray)
			{
				type2 = type2.GetElementType();
			}
			ProcessType(ref builder, type2, in options);
			while (type.IsArray)
			{
				builder.Append('[');
				builder.Append(',', type.GetArrayRank() - 1);
				builder.Append(']');
				type = type.GetElementType();
			}
		}

		private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, in DisplayNameOptions options)
		{
			int num = 0;
			if (type.IsNested)
			{
				num = type.DeclaringType.GetGenericArguments().Length;
			}
			if (options.FullName)
			{
				if (type.IsNested)
				{
					ProcessGenericType(builder, type.DeclaringType, genericArguments, num, in options);
					builder.Append(options.NestedTypeDelimiter);
				}
				else if (!string.IsNullOrEmpty(type.Namespace))
				{
					builder.Append(type.Namespace);
					builder.Append('.');
				}
			}
			int num2 = type.Name.IndexOf('`');
			if (num2 <= 0)
			{
				builder.Append(type.Name);
				return;
			}
			builder.Append(type.Name, 0, num2);
			if (!options.IncludeGenericParameters)
			{
				return;
			}
			builder.Append('<');
			for (int i = num; i < length; i++)
			{
				ProcessType(ref builder, genericArguments[i], in options);
				if (i + 1 != length)
				{
					builder.Append(',');
					if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter)
					{
						builder.Append(' ');
					}
				}
			}
			builder.Append('>');
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection
{
	internal sealed class CallSiteJsonFormatter : CallSiteVisitor<CallSiteJsonFormatter.CallSiteFormatterContext, object?>
	{
		internal struct CallSiteFormatterContext
		{
			private readonly HashSet<ServiceCallSite> _processedCallSites;

			private bool _firstItem;

			public int Offset { get; }

			public StringBuilder Builder { get; }

			public CallSiteFormatterContext(StringBuilder builder, int offset, HashSet<ServiceCallSite> processedCallSites)
			{
				Builder = builder;
				Offset = offset;
				_processedCallSites = processedCallSites;
				_firstItem = true;
			}

			public bool ShouldFormat(ServiceCallSite serviceCallSite)
			{
				return _processedCallSites.Add(serviceCallSite);
			}

			public CallSiteFormatterContext IncrementOffset()
			{
				CallSiteFormatterContext result = new CallSiteFormatterContext(Builder, Offset + 4, _processedCallSites);
				result._firstItem = true;
				return result;
			}

			public CallSiteFormatterContext StartObject()
			{
				Builder.Append('{');
				return IncrementOffset();
			}

			public void EndObject()
			{
				Builder.Append('}');
			}

			public void StartProperty(string name)
			{
				if (!_firstItem)
				{
					Builder.Append(',');
				}
				else
				{
					_firstItem = false;
				}
				Builder.Append('"').Append(name).Append("\":");
			}

			public void StartArrayItem()
			{
				if (!_firstItem)
				{
					Builder.Append(',');
				}
				else
				{
					_firstItem = false;
				}
			}

			public void WriteProperty(string name, object? value)
			{
				StartProperty(name);
				if (value != null)
				{
					Builder.Append(" \"").Append(value).Append('"');
				}
				else
				{
					Builder.Append("null");
				}
			}

			public CallSiteFormatterContext StartArray()
			{
				Builder.Append('[');
				return IncrementOffset();
			}

			public void EndArray()
			{
				Builder.Append(']');
			}
		}

		internal static readonly CallSiteJsonFormatter Instance = new CallSiteJsonFormatter();

		private CallSiteJsonFormatter()
		{
		}

		public string Format(ServiceCallSite callSite)
		{
			StringBuilder stringBuilder = new StringBuilder();
			CallSiteFormatterContext argument = new CallSiteFormatterContext(stringBuilder, 0, new HashSet<ServiceCallSite>());
			VisitCallSite(callSite, argument);
			return stringBuilder.ToString();
		}

		protected override object? VisitConstructor(ConstructorCallSite constructorCallSite, CallSiteFormatterContext argument)
		{
			argument.WriteProperty("implementationType", constructorCallSite.ImplementationType);
			if (constructorCallSite.ParameterCallSites.Length != 0)
			{
				argument.StartProperty("arguments");
				CallSiteFormatterContext argument2 = argument.StartArray();
				ServiceCallSite[] parameterCallSites = constructorCallSite.ParameterCallSites;
				foreach (ServiceCallSite callSite in parameterCallSites)
				{
					argument2.StartArrayItem();
					VisitCallSite(callSite, argument2);
				}
				argument.EndArray();
			}
			return null;
		}

		protected override object? VisitCallSiteMain(ServiceCallSite callSite, CallSiteFormatterContext argument)
		{
			if (argument.ShouldFormat(callSite))
			{
				CallSiteFormatterContext argument2 = argument.StartObject();
				argument2.WriteProperty("serviceType", callSite.ServiceType);
				argument2.WriteProperty("kind", callSite.Kind);
				argument2.WriteProperty("cache", callSite.Cache.Location);
				base.VisitCallSiteMain(callSite, argument2);
				argument.EndObject();
			}
			else
			{
				argument.StartObject().WriteProperty("ref", callSite.ServiceType);
				argument.EndObject();
			}
			return null;
		}

		protected override object? VisitConstant(ConstantCallSite constantCallSite, CallSiteFormatterContext argument)
		{
			argument.WriteProperty("value", constantCallSite.DefaultValue ?? "");
			return null;
		}

		protected override object? VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, CallSiteFormatterContext argument)
		{
			return null;
		}

		protected override object? VisitIEnumerable(IEnumerableCallSite enumerableCallSite, CallSiteFormatterContext argument)
		{
			argument.WriteProperty("itemType", enumerableCallSite.ItemType);
			argument.WriteProperty("size", enumerableCallSite.ServiceCallSites.Length);
			if (enumerableCallSite.ServiceCallSites.Length != 0)
			{
				argument.StartProperty("items");
				CallSiteFormatterContext argument2 = argument.StartArray();
				ServiceCallSite[] serviceCallSites = enumerableCallSite.ServiceCallSites;
				foreach (ServiceCallSite callSite in serviceCallSites)
				{
					argument2.StartArrayItem();
					VisitCallSite(callSite, argument2);
				}
				argument.EndArray();
			}
			return null;
		}

		protected override object? VisitFactory(FactoryCallSite factoryCallSite, CallSiteFormatterContext argument)
		{
			argument.WriteProperty("method", factoryCallSite.Factory.Method);
			return null;
		}
	}
	public class DefaultServiceProviderFactory : IServiceProviderFactory<IServiceCollection>
	{
		private readonly ServiceProviderOptions _options;

		public DefaultServiceProviderFactory()
			: this(ServiceProviderOptions.Default)
		{
		}

		public DefaultServiceProviderFactory(ServiceProviderOptions options)
		{
			_options = options ?? throw new ArgumentNullException("options");
		}

		public IServiceCollection CreateBuilder(IServiceCollection services)
		{
			return services;
		}

		public IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder)
		{
			return containerBuilder.BuildServiceProvider(_options);
		}
	}
	[EventSource(Name = "Microsoft-Extensions-DependencyInjection")]
	internal sealed class DependencyInjectionEventSource : EventSource
	{
		public static class Keywords
		{
			public const EventKeywords ServiceProviderInitialized = (EventKeywords)1L;
		}

		public static readonly DependencyInjectionEventSource Log = new DependencyInjectionEventSource();

		private const int MaxChunkSize = 10240;

		private readonly List<WeakReference<ServiceProvider>> _providers = new List<WeakReference<ServiceProvider>>();

		private DependencyInjectionEventSource()
			: base(EventSourceSettings.EtwSelfDescribingEventFormat)
		{
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe.")]
		[Event(1, Level = EventLevel.Verbose)]
		private void CallSiteBuilt(string serviceType, string callSite, int chunkIndex, int chunkCount, int serviceProviderHashCode)
		{
			WriteEvent(1, serviceType, callSite, chunkIndex, chunkCount, serviceProviderHashCode);
		}

		[Event(2, Level = EventLevel.Verbose)]
		public void ServiceResolved(string serviceType, int serviceProviderHashCode)
		{
			WriteEvent(2, serviceType, serviceProviderHashCode);
		}

		[Event(3, Level = EventLevel.Verbose)]
		public void ExpressionTreeGenerated(string serviceType, int nodeCount, int serviceProviderHashCode)
		{
			WriteEvent(3, serviceType, nodeCount, serviceProviderHashCode);
		}

		[Event(4, Level = EventLevel.Verbose)]
		public void DynamicMethodBuilt(string serviceType, int methodSize, int serviceProviderHashCode)
		{
			WriteEvent(4, serviceType, methodSize, serviceProviderHashCode);
		}

		[Event(5, Level = EventLevel.Verbose)]
		public void ScopeDisposed(int serviceProviderHashCode, int scopedServicesResolved, int disposableServices)
		{
			WriteEvent(5, serviceProviderHashCode, scopedServicesResolved, disposableServices);
		}

		[Event(6, Level = EventLevel.Error)]
		public void ServiceRealizationFailed(string? exceptionMessage, int serviceProviderHashCode)
		{
			WriteEvent(6, exceptionMessage, serviceProviderHashCode);
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe.")]
		[Event(7, Level = EventLevel.Informational, Keywords = (EventKeywords)1L)]
		private void ServiceProviderBuilt(int serviceProviderHashCode, int singletonServices, int scopedServices, int transientServices, int closedGenericsServices, int openGenericsServices)
		{
			WriteEvent(7, serviceProviderHashCode, singletonServices, scopedServices, transientServices, closedGenericsServices, openGenericsServices);
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe.")]
		[Event(8, Level = EventLevel.Informational, Keywords = (EventKeywords)1L)]
		private void ServiceProviderDescriptors(int serviceProviderHashCode, string descriptors, int chunkIndex, int chunkCount)
		{
			WriteEvent(8, serviceProviderHashCode, descriptors, chunkIndex, chunkCount);
		}

		[NonEvent]
		public void ServiceResolved(ServiceProvider provider, Type serviceType)
		{
			if (IsEnabled(EventLevel.Verbose, EventKeywords.All))
			{
				ServiceResolved(serviceType.ToString(), provider.GetHashCode());
			}
		}

		[NonEvent]
		public void CallSiteBuilt(ServiceProvider provider, Type serviceType, ServiceCallSite callSite)
		{
			if (IsEnabled(EventLevel.Verbose, EventKeywords.All))
			{
				string text = CallSiteJsonFormatter.Instance.Format(callSite);
				int num = text.Length / 10240 + ((text.Length % 10240 > 0) ? 1 : 0);
				int hashCode = provider.GetHashCode();
				for (int i = 0; i < num; i++)
				{
					CallSiteBuilt(serviceType.ToString(), text.Substring(i * 10240, Math.Min(10240, text.Length - i * 10240)), i, num, hashCode);
				}
			}
		}

		[NonEvent]
		public void DynamicMethodBuilt(ServiceProvider provider, Type serviceType, int methodSize)
		{
			if (IsEnabled(EventLevel.Verbose, EventKeywords.All))
			{
				DynamicMethodBuilt(serviceType.ToString(), methodSize, provider.GetHashCode());
			}
		}

		[NonEvent]
		public void ServiceRealizationFailed(Exception exception, int serviceProviderHashCode)
		{
			if (IsEnabled(EventLevel.Error, EventKeywords.All))
			{
				ServiceRealizationFailed(exception.ToString(), serviceProviderHashCode);
			}
		}

		[NonEvent]
		public void ServiceProviderBuilt(ServiceProvider provider)
		{
			lock (_providers)
			{
				_providers.Add(new WeakReference<ServiceProvider>(provider));
			}
			WriteServiceProviderBuilt(provider);
		}

		[NonEvent]
		public void ServiceProviderDisposed(ServiceProvider provider)
		{
			lock (_providers)
			{
				for (int num = _providers.Count - 1; num >= 0; num--)
				{
					if (!_providers[num].TryGetTarget(out var target) || target == provider)
					{
						_providers.RemoveAt(num);
					}
				}
			}
		}

		[NonEvent]
		private void WriteServiceProviderBuilt(ServiceProvider provider)
		{
			if (!IsEnabled(EventLevel.Informational, (EventKeywords)1L))
			{
				return;
			}
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			StringBuilder stringBuilder = new StringBuilder("{ \"descriptors\":[ ");
			bool flag = true;
			ServiceDescriptor[] descriptors = provider.CallSiteFactory.Descriptors;
			foreach (ServiceDescriptor serviceDescriptor in descriptors)
			{
				if (flag)
				{
					flag = false;
				}
				else
				{
					stringBuilder.Append(", ");
				}
				AppendServiceDescriptor(stringBuilder, serviceDescriptor);
				switch (serviceDescriptor.Lifetime)
				{
				case ServiceLifetime.Singleton:
					num++;
					break;
				case ServiceLifetime.Scoped:
					num2++;
					break;
				case ServiceLifetime.Transient:
					num3++;
					break;
				}
				if (serviceDescriptor.ServiceType.IsGenericType)
				{
					if (serviceDescriptor.ServiceType.IsConstructedGenericType)
					{
						num4++;
					}
					else
					{
						num5++;
					}
				}
			}
			stringBuilder.Append(" ] }");
			int hashCode = provider.GetHashCode();
			ServiceProviderBuilt(hashCode, num, num2, num3, num4, num5);
			string text = stringBuilder.ToString();
			int num6 = text.Length / 10240 + ((text.Length % 10240 > 0) ? 1 : 0);
			for (int j = 0; j < num6; j++)
			{
				ServiceProviderDescriptors(hashCode, text.Substring(j * 10240, Math.Min(10240, text.Length - j * 10240)), j, num6);
			}
		}

		[NonEvent]
		private static void AppendServiceDescriptor(StringBuilder builder, ServiceDescriptor descriptor)
		{
			builder.Append("{ \"serviceType\": \"");
			builder.Append(descriptor.ServiceType);
			builder.Append("\", \"lifetime\": \"");
			builder.Append(descriptor.Lifetime);
			builder.Append("\", ");
			if (descriptor.HasImplementationType())
			{
				builder.Append("\"implementationType\": \"");
				builder.Append(descriptor.GetImplementationType());
			}
			else if (!descriptor.IsKeyedService && descriptor.ImplementationFactory != null)
			{
				builder.Append("\"implementationFactory\": \"");
				builder.Append(descriptor.ImplementationFactory.Method);
			}
			else if (descriptor.IsKeyedService && descriptor.KeyedImplementationFactory != null)
			{
				builder.Append("\"implementationFactory\": \"");
				builder.Append(descriptor.KeyedImplementationFactory.Method);
			}
			else if (descriptor.HasImplementationInstance())
			{
				object implementationInstance = descriptor.GetImplementationInstance();
				builder.Append("\"implementationInstance\": \"");
				builder.Append(implementationInstance.GetType());
				builder.Append(" (instance)");
			}
			else
			{
				builder.Append("\"unknown\": \"");
			}
			builder.Append("\" }");
		}

		protected override void OnEventCommand(EventCommandEventArgs command)
		{
			if (command.Command != EventCommand.Enable)
			{
				return;
			}
			lock (_providers)
			{
				foreach (WeakReference<ServiceProvider> provider in _providers)
				{
					if (provider.TryGetTarget(out var target))
					{
						WriteServiceProviderBuilt(target);
					}
				}
			}
		}
	}
	internal static class DependencyInjectionEventSourceExtensions
	{
		private sealed class NodeCountingVisitor : ExpressionVisitor
		{
			public int NodeCount { get; private set; }

			[return: NotNullIfNotNull("e")]
			public override Expression Visit(Expression e)
			{
				base.Visit(e);
				NodeCount++;
				return e;
			}
		}

		public static void ExpressionTreeGenerated(this DependencyInjectionEventSource source, ServiceProvider provider, Type serviceType, Expression expression)
		{
			if (source.IsEnabled(EventLevel.Verbose, EventKeywords.All))
			{
				NodeCountingVisitor nodeCountingVisitor = new NodeCountingVisitor();
				nodeCountingVisitor.Visit(expression);
				source.ExpressionTreeGenerated(serviceType.ToString(), nodeCountingVisitor.NodeCount, provider.GetHashCode());
			}
		}
	}
	public static class ServiceCollectionContainerBuilderExtensions
	{
		public static ServiceProvider BuildServiceProvider(this IServiceCollection services)
		{
			return services.BuildServiceProvider(ServiceProviderOptions.Default);
		}

		public static ServiceProvider BuildServiceProvider(this IServiceCollection services, bool validateScopes)
		{
			return services.BuildServiceProvider(new ServiceProviderOptions
			{
				ValidateScopes = validateScopes
			});
		}

		public static ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderOptions options)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (options == null)
			{
				throw new ArgumentNullException("options");
			}
			return new ServiceProvider(services, options);
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	[DebuggerTypeProxy(typeof(ServiceProviderDebugView))]
	public sealed class ServiceProvider : IServiceProvider, IKeyedServiceProvider, IDisposable, IAsyncDisposable
	{
		internal sealed class ServiceProviderDebugView
		{
			private readonly ServiceProvider _serviceProvider;

			public List<ServiceDescriptor> ServiceDescriptors => new List<ServiceDescriptor>(_serviceProvider.Root.RootProvider.CallSiteFactory.Descriptors);

			public List<object> Disposables => new List<object>(_serviceProvider.Root.Disposables);

			public bool Disposed => _serviceProvider.Root.Disposed;

			public bool IsScope => !_serviceProvider.Root.IsRootScope;

			public ServiceProviderDebugView(ServiceProvider serviceProvider)
			{
				_serviceProvider = serviceProvider;
			}
		}

		private sealed class ServiceAccessor
		{
			public ServiceCallSite CallSite { get; set; }

			public Func<ServiceProviderEngineScope, object> RealizedService { get; set; }
		}

		private readonly CallSiteValidator _callSiteValidator;

		private readonly Func<ServiceIdentifier, ServiceAccessor> _createServiceAccessor;

		internal ServiceProviderEngine _engine;

		private bool _disposed;

		private readonly ConcurrentDictionary<ServiceIdentifier, ServiceAccessor> _serviceAccessors;

		internal CallSiteFactory CallSiteFactory { get; }

		internal ServiceProviderEngineScope Root { get; }

		internal static bool VerifyOpenGenericServiceTrimmability { get; } = AppContext.TryGetSwitch("Microsoft.Extensions.DependencyInjection.VerifyOpenGenericServiceTrimmability", out var isEnabled) && isEnabled;


		internal static bool DisableDynamicEngine { get; } = AppContext.TryGetSwitch("Microsoft.Extensions.DependencyInjection.DisableDynamicEngine", out var isEnabled2) && isEnabled2;


		internal static bool VerifyAotCompatibility => !RuntimeFeature.IsDynamicCodeSupported;

		internal ServiceProvider(ICollection<ServiceDescriptor> serviceDescriptors, ServiceProviderOptions options)
		{
			Root = new ServiceProviderEngineScope(this, isRootScope: true);
			_engine = GetEngine();
			_createServiceAccessor = CreateServiceAccessor;
			_serviceAccessors = new ConcurrentDictionary<ServiceIdentifier, ServiceAccessor>();
			CallSiteFactory = new CallSiteFactory(serviceDescriptors);
			CallSiteFactory.Add(ServiceIdentifier.FromServiceType(typeof(IServiceProvider)), new ServiceProviderCallSite());
			CallSiteFactory.Add(ServiceIdentifier.FromServiceType(typeof(IServiceScopeFactory)), new ConstantCallSite(typeof(IServiceScopeFactory), Root));
			CallSiteFactory.Add(ServiceIdentifier.FromServiceType(typeof(IServiceProviderIsService)), new ConstantCallSite(typeof(IServiceProviderIsService), CallSiteFactory));
			CallSiteFactory.Add(ServiceIdentifier.FromServiceType(typeof(IServiceProviderIsKeyedService)), new ConstantCallSite(typeof(IServiceProviderIsKeyedService), CallSiteFactory));
			if (options.ValidateScopes)
			{
				_callSiteValidator = new CallSiteValidator();
			}
			if (options.ValidateOnBuild)
			{
				List<Exception> list = null;
				foreach (ServiceDescriptor serviceDescriptor in serviceDescriptors)
				{
					try
					{
						ValidateService(serviceDescriptor);
					}
					catch (Exception item)
					{
						if (list == null)
						{
							list = new List<Exception>();
						}
						list.Add(item);
					}
				}
				if (list != null)
				{
					throw new AggregateException("Some services are not able to be constructed", list.ToArray());
				}
			}
			DependencyInjectionEventSource.Log.ServiceProviderBuilt(this);
		}

		public object? GetService(Type serviceType)
		{
			return GetService(ServiceIdentifier.FromServiceType(serviceType), Root);
		}

		public object? GetKeyedService(Type serviceType, object? serviceKey)
		{
			return GetKeyedService(serviceType, serviceKey, Root);
		}

		internal object? GetKeyedService(Type serviceType, object? serviceKey, ServiceProviderEngineScope serviceProviderEngineScope)
		{
			return GetService(new ServiceIdentifier(serviceKey, serviceType), serviceProviderEngineScope);
		}

		public object GetRequiredKeyedService(Type serviceType, object? serviceKey)
		{
			return GetRequiredKeyedService(serviceType, serviceKey, Root);
		}

		internal object GetRequiredKeyedService(Type serviceType, object? serviceKey, ServiceProviderEngineScope serviceProviderEngineScope)
		{
			return GetKeyedService(serviceType, serviceKey, serviceProviderEngineScope) ?? throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType));
		}

		internal bool IsDisposed()
		{
			return _disposed;
		}

		public void Dispose()
		{
			DisposeCore();
			Root.Dispose();
		}

		public ValueTask DisposeAsync()
		{
			DisposeCore();
			return Root.DisposeAsync();
		}

		private void DisposeCore()
		{
			_disposed = true;
			DependencyInjectionEventSource.Log.ServiceProviderDisposed(this);
		}

		private void OnCreate(ServiceCallSite callSite)
		{
			_callSiteValidator?.ValidateCallSite(callSite);
		}

		private void OnResolve(ServiceCallSite callSite, IServiceScope scope)
		{
			if (callSite != null)
			{
				_callSiteValidator?.ValidateResolution(callSite, scope, Root);
			}
		}

		internal object? GetService(ServiceIdentifier serviceIdentifier, ServiceProviderEngineScope serviceProviderEngineScope)
		{
			if (_disposed)
			{
				ThrowHelper.ThrowObjectDisposedException();
			}
			ServiceAccessor orAdd = _serviceAccessors.GetOrAdd(serviceIdentifier, _createServiceAccessor);
			OnResolve(orAdd.CallSite, serviceProviderEngineScope);
			DependencyInjectionEventSource.Log.ServiceResolved(this, serviceIdentifier.ServiceType);
			return orAdd.RealizedService?.Invoke(serviceProviderEngineScope);
		}

		private void ValidateService(ServiceDescriptor descriptor)
		{
			if (descriptor.ServiceType.IsGenericType && !descriptor.ServiceType.IsConstructedGenericType)
			{
				return;
			}
			try
			{
				ServiceCallSite callSite = CallSiteFactory.GetCallSite(descriptor, new CallSiteChain());
				if (callSite != null)
				{
					OnCreate(callSite);
				}
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException($"Error while validating the service descriptor '{descriptor}': {ex.Message}", ex);
			}
		}

		private ServiceAccessor CreateServiceAccessor(ServiceIdentifier serviceIdentifier)
		{
			ServiceCallSite callSite = CallSiteFactory.GetCallSite(serviceIdentifier, new CallSiteChain());
			if (callSite != null)
			{
				DependencyInjectionEventSource.Log.CallSiteBuilt(this, serviceIdentifier.ServiceType, callSite);
				OnCreate(callSite);
				if (callSite.Cache.Location == CallSiteResultCacheLocation.Root)
				{
					object value = CallSiteRuntimeResolver.Instance.Resolve(callSite, Root);
					return new ServiceAccessor
					{
						CallSite = callSite,
						RealizedService = (ServiceProviderEngineScope scope) => value
					};
				}
				Func<ServiceProviderEngineScope, object> realizedService = _engine.RealizeService(callSite);
				return new ServiceAccessor
				{
					CallSite = callSite,
					RealizedService = realizedService
				};
			}
			return new ServiceAccessor
			{
				CallSite = callSite,
				RealizedService = (ServiceProviderEngineScope _) => null
			};
		}

		internal void ReplaceServiceAccessor(ServiceCallSite callSite, Func<ServiceProviderEngineScope, object?> accessor)
		{
			_serviceAccessors[new ServiceIdentifier(callSite.Key, callSite.ServiceType)] = new ServiceAccessor
			{
				CallSite = callSite,
				RealizedService = accessor
			};
		}

		internal IServiceScope CreateScope()
		{
			if (_disposed)
			{
				ThrowHelper.ThrowObjectDisposedException();
			}
			return new ServiceProviderEngineScope(this, isRootScope: false);
		}

		private ServiceProviderEngine GetEngine()
		{
			if (RuntimeFeature.IsDynamicCodeCompiled && !DisableDynamicEngine)
			{
				return CreateDynamicEngine();
			}
			return RuntimeServiceProviderEngine.Instance;
			[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "CreateDynamicEngine won't be called when using NativeAOT.")]
			ServiceProviderEngine CreateDynamicEngine()
			{
				return new DynamicServiceProviderEngine(this);
			}
		}

		private string DebuggerToString()
		{
			return Root.DebuggerToString();
		}
	}
	public class ServiceProviderOptions
	{
		internal static readonly ServiceProviderOptions Default = new ServiceProviderOptions();

		public bool ValidateScopes { get; set; }

		public bool ValidateOnBuild { get; set; }
	}
}
namespace Microsoft.Extensions.DependencyInjection.ServiceLookup
{
	internal sealed class CallSiteChain
	{
		private readonly struct ChainItemInfo
		{
			public int Order { get; }

			public Type ImplementationType { get; }

			public ChainItemInfo(int order, Type implementationType)
			{
				Order = order;
				ImplementationType = implementationType;
			}
		}

		private readonly Dictionary<ServiceIdentifier, ChainItemInfo> _callSiteChain;

		public CallSiteChain()
		{
			_callSiteChain = new Dictionary<ServiceIdentifier, ChainItemInfo>();
		}

		public void CheckCircularDependency(ServiceIdentifier serviceIdentifier)
		{
			if (_callSiteChain.ContainsKey(serviceIdentifier))
			{
				throw new InvalidOperationException(CreateCircularDependencyExceptionMessage(serviceIdentifier));
			}
		}

		public void Remove(ServiceIdentifier serviceIdentifier)
		{
			_callSiteChain.Remove(serviceIdentifier);
		}

		public void Add(ServiceIdentifier serviceIdentifier, Type? implementationType = null)
		{
			_callSiteChain[serviceIdentifier] = new ChainItemInfo(_callSiteChain.Count, implementationType);
		}

		private string CreateCircularDependencyExceptionMessage(ServiceIdentifier serviceIdentifier)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(System.SR.Format(System.SR.CircularDependencyException, TypeNameHelper.GetTypeDisplayName(serviceIdentifier.ServiceType)));
			stringBuilder.AppendLine();
			AppendResolutionPath(stringBuilder, serviceIdentifier);
			return stringBuilder.ToString();
		}

		private void AppendResolutionPath(StringBuilder builder, ServiceIdentifier currentlyResolving)
		{
			List<KeyValuePair<ServiceIdentifier, ChainItemInfo>> list = new List<KeyValuePair<ServiceIdentifier, ChainItemInfo>>(_callSiteChain);
			list.Sort((KeyValuePair<ServiceIdentifier, ChainItemInfo> a, KeyValuePair<ServiceIdentifier, ChainItemInfo> b) => a.Value.Order.CompareTo(b.Value.Order));
			foreach (KeyValuePair<ServiceIdentifier, ChainItemInfo> item in list)
			{
				ServiceIdentifier key = item.Key;
				Type implementationType = item.Value.ImplementationType;
				if (implementationType == null || key.ServiceType == implementationType)
				{
					builder.Append(TypeNameHelper.GetTypeDisplayName(key.ServiceType));
				}
				else
				{
					builder.Append(TypeNameHelper.GetTypeDisplayName(key.ServiceType)).Append('(').Append(TypeNameHelper.GetTypeDisplayName(implementationType))
						.Append(')');
				}
				builder.Append(" -> ");
			}
			builder.Append(TypeNameHelper.GetTypeDisplayName(currentlyResolving.ServiceType));
		}
	}
	internal sealed class CallSiteFactory : IServiceProviderIsService, IServiceProviderIsKeyedService
	{
		private struct ServiceDescriptorCacheItem
		{
			[DisallowNull]
			private ServiceDescriptor _item;

			[DisallowNull]
			private List<ServiceDescriptor> _items;

			public ServiceDescriptor Last
			{
				get
				{
					if (_items != null && _items.Count > 0)
					{
						return _items[_items.Count - 1];
					}
					return _item;
				}
			}

			public int Count
			{
				get
				{
					if (_item == null)
					{
						return 0;
					}
					return 1 + (_items?.Count ?? 0);
				}
			}

			public ServiceDescriptor this[int index]
			{
				get
				{
					if (index >= Count)
					{
						throw new ArgumentOutOfRangeException("index");
					}
					if (index == 0)
					{
						return _item;
					}
					return _items[index - 1];
				}
			}

			public int GetSlot(ServiceDescriptor descriptor)
			{
				if (descriptor == _item)
				{
					return Count - 1;
				}
				if (_items != null)
				{
					int num = _items.IndexOf(descriptor);
					if (num != -1)
					{
						return _items.Count - (num + 1);
					}
				}
				throw new InvalidOperationException(System.SR.ServiceDescriptorNotExist);
			}

			public ServiceDescriptorCacheItem Add(ServiceDescriptor descriptor)
			{
				ServiceDescriptorCacheItem result = default(ServiceDescriptorCacheItem);
				if (_item == null)
				{
					result._item = descriptor;
				}
				else
				{
					result._item = _item;
					result._items = _items ?? new List<ServiceDescriptor>();
					result._items.Add(descriptor);
				}
				return result;
			}
		}

		private const int DefaultSlot = 0;

		private readonly ServiceDescriptor[] _descriptors;

		private readonly ConcurrentDictionary<ServiceCacheKey, ServiceCallSite> _callSiteCache = new ConcurrentDictionary<ServiceCacheKey, ServiceCallSite>();

		private readonly Dictionary<ServiceIdentifier, ServiceDescriptorCacheItem> _descriptorLookup = new Dictionary<ServiceIdentifier, ServiceDescriptorCacheItem>();

		private readonly ConcurrentDictionary<ServiceIdentifier, object> _callSiteLocks = new ConcurrentDictionary<ServiceIdentifier, object>();

		private readonly StackGuard _stackGuard;

		internal ServiceDescriptor[] Descriptors => _descriptors;

		public CallSiteFactory(ICollection<ServiceDescriptor> descriptors)
		{
			_stackGuard = new StackGuard();
			_descriptors = new ServiceDescriptor[descriptors.Count];
			descriptors.CopyTo(_descriptors, 0);
			Populate();
		}

		private void Populate()
		{
			ServiceDescriptor[] descriptors = _descriptors;
			foreach (ServiceDescriptor serviceDescriptor in descriptors)
			{
				Type serviceType = serviceDescriptor.ServiceType;
				Type type;
				if (serviceType.IsGenericTypeDefinition)
				{
					Type implementationType = serviceDescriptor.GetImplementationType();
					if (implementationType == null || !implementationType.IsGenericTypeDefinition)
					{
						throw new ArgumentException(System.SR.Format(System.SR.OpenGenericServiceRequiresOpenGenericImplementation, serviceType), "descriptors");
					}
					if (implementationType.IsAbstract || implementationType.IsInterface)
					{
						throw new ArgumentException(System.SR.Format(System.SR.TypeCannotBeActivated, implementationType, serviceType));
					}
					Type[] genericArguments = serviceType.GetGenericArguments();
					Type[] genericArguments2 = implementationType.GetGenericArguments();
					if (genericArguments.Length != genericArguments2.Length)
					{
						throw new ArgumentException(System.SR.Format(System.SR.ArityOfOpenGenericServiceNotEqualArityOfOpenGenericImplementation, serviceType, implementationType), "descriptors");
					}
					if (ServiceProvider.VerifyOpenGenericServiceTrimmability)
					{
						ValidateTrimmingAnnotations(serviceType, genericArguments, implementationType, genericArguments2);
					}
				}
				else if (serviceDescriptor.TryGetImplementationType(out type) && (type.IsGenericTypeDefinition || type.IsAbstract || type.IsInterface))
				{
					throw new ArgumentException(System.SR.Format(System.SR.TypeCannotBeActivated, type, serviceType));
				}
				ServiceIdentifier key = ServiceIdentifier.FromDescriptor(serviceDescriptor);
				_descriptorLookup.TryGetValue(key, out var value);
				_descriptorLookup[key] = value.Add(serviceDescriptor);
			}
		}

		private static void ValidateTrimmingAnnotations(Type serviceType, Type[] serviceTypeGenericArguments, Type implementationType, Type[] implementationTypeGenericArguments)
		{
			for (int i = 0; i < serviceTypeGenericArguments.Length; i++)
			{
				Type obj = serviceTypeGenericArguments[i];
				Type type = implementationTypeGenericArguments[i];
				DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes = GetDynamicallyAccessedMemberTypes(obj);
				DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes2 = GetDynamicallyAccessedMemberTypes(type);
				if (!AreCompatible(dynamicallyAccessedMemberTypes, dynamicallyAccessedMemberTypes2))
				{
					throw new ArgumentException(System.SR.Format(System.SR.TrimmingAnnotationsDoNotMatch, implementationType.FullName, serviceType.FullName));
				}
				bool flag = obj.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint);
				if (type.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint) && !flag)
				{
					throw new ArgumentException(System.SR.Format(System.SR.TrimmingAnnotationsDoNotMatch_NewConstraint, implementationType.FullName, serviceType.FullName));
				}
			}
		}

		private static DynamicallyAccessedMemberTypes GetDynamicallyAccessedMemberTypes(Type serviceGenericType)
		{
			foreach (CustomAttributeData customAttributesDatum in serviceGenericType.GetCustomAttributesData())
			{
				if (customAttributesDatum.AttributeType.FullName == "System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute" && customAttributesDatum.ConstructorArguments.Count == 1 && customAttributesDatum.ConstructorArguments[0].ArgumentType.FullName == "System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes")
				{
					return (DynamicallyAccessedMemberTypes)(int)customAttributesDatum.ConstructorArguments[0].Value;
				}
			}
			return DynamicallyAccessedMemberTypes.None;
		}

		private static bool AreCompatible(DynamicallyAccessedMemberTypes serviceDynamicallyAccessedMembers, DynamicallyAccessedMemberTypes implementationDynamicallyAccessedMembers)
		{
			return serviceDynamicallyAccessedMembers.HasFlag(implementationDynamicallyAccessedMembers);
		}

		internal int? GetSlot(ServiceDescriptor serviceDescriptor)
		{
			if (_descriptorLookup.TryGetValue(ServiceIdentifier.FromDescriptor(serviceDescriptor), out var value))
			{
				return value.GetSlot(serviceDescriptor);
			}
			return null;
		}

		internal ServiceCallSite? GetCallSite(ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain)
		{
			if (!_callSiteCache.TryGetValue(new ServiceCacheKey(serviceIdentifier, 0), out var value))
			{
				return CreateCallSite(serviceIdentifier, callSiteChain);
			}
			return value;
		}

		internal ServiceCallSite? GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain)
		{
			ServiceIdentifier serviceIdentifier = ServiceIdentifier.FromDescriptor(serviceDescriptor);
			if (_descriptorLookup.TryGetValue(serviceIdentifier, out var value))
			{
				return TryCreateExact(serviceDescriptor, serviceIdentifier, callSiteChain, value.GetSlot(serviceDescriptor));
			}
			return null;
		}

		private ServiceCallSite CreateCallSite(ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain)
		{
			if (!_stackGuard.TryEnterOnCurrentStack())
			{
				return _stackGuard.RunOnEmptyStack(CreateCallSite, serviceIdentifier, callSiteChain);
			}
			lock (_callSiteLocks.GetOrAdd(serviceIdentifier, (ServiceIdentifier _) => new object()))
			{
				callSiteChain.CheckCircularDependency(serviceIdentifier);
				return TryCreateExact(serviceIdentifier, callSiteChain) ?? TryCreateOpenGeneric(serviceIdentifier, callSiteChain) ?? TryCreateEnumerable(serviceIdentifier, callSiteChain);
			}
		}

		private ServiceCallSite TryCreateExact(ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain)
		{
			if (_descriptorLookup.TryGetValue(serviceIdentifier, out var value))
			{
				return TryCreateExact(value.Last, serviceIdentifier, callSiteChain, 0);
			}
			if (serviceIdentifier.ServiceKey != null)
			{
				ServiceIdentifier key = new ServiceIdentifier(KeyedService.AnyKey, serviceIdentifier.ServiceType);
				if (_descriptorLookup.TryGetValue(key, out value))
				{
					return TryCreateExact(value.Last, serviceIdentifier, callSiteChain, 0);
				}
			}
			return null;
		}

		private ServiceCallSite TryCreateOpenGeneric(ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain)
		{
			if (serviceIdentifier.IsConstructedGenericType)
			{
				ServiceIdentifier genericTypeDefinition = serviceIdentifier.GetGenericTypeDefinition();
				if (_descriptorLookup.TryGetValue(genericTypeDefinition, out var value))
				{
					return TryCreateOpenGeneric(value.Last, serviceIdentifier, callSiteChain, 0, throwOnConstraintViolation: true);
				}
				if (serviceIdentifier.ServiceKey != null)
				{
					ServiceIdentifier key = new ServiceIdentifier(KeyedService.AnyKey, genericTypeDefinition.ServiceType);
					if (_descriptorLookup.TryGetValue(key, out value))
					{
						return TryCreateOpenGeneric(value.Last, serviceIdentifier, callSiteChain, 0, throwOnConstraintViolation: true);
					}
				}
			}
			return null;
		}

		private ServiceCallSite TryCreateEnumerable(ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain)
		{
			ServiceCacheKey serviceCacheKey = new ServiceCacheKey(serviceIdentifier, 0);
			if (_callSiteCache.TryGetValue(serviceCacheKey, out var value))
			{
				return value;
			}
			try
			{
				callSiteChain.Add(serviceIdentifier);
				Type serviceType = serviceIdentifier.ServiceType;
				if (!serviceType.IsConstructedGenericType || serviceType.GetGenericTypeDefinition() != typeof(IEnumerable<>))
				{
					return null;
				}
				Type type = serviceType.GenericTypeArguments[0];
				ServiceIdentifier serviceIdentifier2 = new ServiceIdentifier(serviceIdentifier.ServiceKey, type);
				if (ServiceProvider.VerifyAotCompatibility && type.IsValueType)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.AotCannotCreateEnumerableValueType, type));
				}
				CallSiteResultCacheLocation cacheLocation = CallSiteResultCacheLocation.Root;
				ServiceCallSite[] array;
				List<KeyValuePair<int, ServiceCallSite>> callSitesByIndex;
				int slot;
				if (!type.IsConstructedGenericType && !KeyedService.AnyKey.Equals(serviceIdentifier2.ServiceKey) && _descriptorLookup.TryGetValue(serviceIdentifier2, out var value2))
				{
					array = new ServiceCallSite[value2.Count];
					for (int i = 0; i < value2.Count; i++)
					{
						ServiceDescriptor descriptor = value2[i];
						int slot2 = value2.Count - i - 1;
						ServiceCallSite serviceCallSite = TryCreateExact(descriptor, serviceIdentifier2, callSiteChain, slot2);
						cacheLocation = GetCommonCacheLocation(cacheLocation, serviceCallSite.Cache.Location);
						array[i] = serviceCallSite;
					}
				}
				else
				{
					callSitesByIndex = new List<KeyValuePair<int, ServiceCallSite>>();
					slot = 0;
					for (int num = _descriptors.Length - 1; num >= 0; num--)
					{
						if (KeysMatch(_descriptors[num].ServiceKey, serviceIdentifier2.ServiceKey))
						{
							ServiceCallSite serviceCallSite2 = TryCreateExact(_descriptors[num], serviceIdentifier2, callSiteChain, slot);
							if (serviceCallSite2 != null)
							{
								AddCallSite(serviceCallSite2, num);
							}
						}
					}
					for (int num2 = _descriptors.Length - 1; num2 >= 0; num2--)
					{
						if (KeysMatch(_descriptors[num2].ServiceKey, serviceIdentifier2.ServiceKey))
						{
							ServiceCallSite serviceCallSite3 = TryCreateOpenGeneric(_descriptors[num2], serviceIdentifier2, callSiteChain, slot, throwOnConstraintViolation: false);
							if (serviceCallSite3 != null)
							{
								AddCallSite(serviceCallSite3, num2);
							}
						}
					}
					callSitesByIndex.Sort((KeyValuePair<int, ServiceCallSite> a, KeyValuePair<int, ServiceCallSite> b) => a.Key.CompareTo(b.Key));
					array = new ServiceCallSite[callSitesByIndex.Count];
					for (int j = 0; j < array.Length; j++)
					{
						array[j] = callSitesByIndex[j].Value;
					}
				}
				ResultCache cache = ((cacheLocation == CallSiteResultCacheLocation.Scope || cacheLocation == CallSiteResultCacheLocation.Root) ? new ResultCache(cacheLocation, serviceCacheKey) : new ResultCache(CallSiteResultCacheLocation.None, serviceCacheKey));
				return _callSiteCache[serviceCacheKey] = new IEnumerableCallSite(cache, type, array);
				void AddCallSite(ServiceCallSite callSite, int index)
				{
					slot++;
					cacheLocation = GetCommonCacheLocation(cacheLocation, callSite.Cache.Location);
					callSitesByIndex.Add(new KeyValuePair<int, ServiceCallSite>(index, callSite));
				}
			}
			finally
			{
				callSiteChain.Remove(serviceIdentifier);
			}
		}

		private static CallSiteResultCacheLocation GetCommonCacheLocation(CallSiteResultCacheLocation locationA, CallSiteResultCacheLocation locationB)
		{
			return (CallSiteResultCacheLocation)Math.Max((int)locationA, (int)locationB);
		}

		private ServiceCallSite TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, int slot)
		{
			if (serviceIdentifier.ServiceType == descriptor.ServiceType)
			{
				ServiceCacheKey key = new ServiceCacheKey(serviceIdentifier, slot);
				if (_callSiteCache.TryGetValue(key, out var value))
				{
					return value;
				}
				ResultCache resultCache = new ResultCache(descriptor.Lifetime, serviceIdentifier, slot);
				ServiceCallSite serviceCallSite;
				if (descriptor.HasImplementationInstance())
				{
					serviceCallSite = new ConstantCallSite(descriptor.ServiceType, descriptor.GetImplementationInstance());
				}
				else if (!descriptor.IsKeyedService && descriptor.ImplementationFactory != null)
				{
					serviceCallSite = new FactoryCallSite(resultCache, descriptor.ServiceType, descriptor.ImplementationFactory);
				}
				else if (descriptor.IsKeyedService && descriptor.KeyedImplementationFactory != null)
				{
					serviceCallSite = new FactoryCallSite(resultCache, descriptor.ServiceType, serviceIdentifier.ServiceKey, descriptor.KeyedImplementationFactory);
				}
				else
				{
					if (!descriptor.HasImplementationType())
					{
						throw new InvalidOperationException(System.SR.InvalidServiceDescriptor);
					}
					serviceCallSite = CreateConstructorCallSite(resultCache, serviceIdentifier, descriptor.GetImplementationType(), callSiteChain);
				}
				serviceCallSite.Key = descriptor.ServiceKey;
				return _callSiteCache[key] = serviceCallSite;
			}
			return null;
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:MakeGenericType", Justification = "MakeGenericType here is used to create a closed generic implementation type given the closed service type. Trimming annotations on the generic types are verified when 'Microsoft.Extensions.DependencyInjection.VerifyOpenGenericServiceTrimmability' is set, which is set by default when PublishTrimmed=true. That check informs developers when these generic types don't have compatible trimming annotations.")]
		[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "When ServiceProvider.VerifyAotCompatibility is true, which it is by default when PublishAot=true, this method ensures the generic types being created aren't using ValueTypes.")]
		private ServiceCallSite TryCreateOpenGeneric(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, int slot, bool throwOnConstraintViolation)
		{
			if (serviceIdentifier.IsConstructedGenericType && serviceIdentifier.ServiceType.GetGenericTypeDefinition() == descriptor.ServiceType)
			{
				ServiceCacheKey key = new ServiceCacheKey(serviceIdentifier, slot);
				if (_callSiteCache.TryGetValue(key, out var value))
				{
					return value;
				}
				Type implementationType = descriptor.GetImplementationType();
				ResultCache lifetime = new ResultCache(descriptor.Lifetime, serviceIdentifier, slot);
				Type implementationType2;
				try
				{
					Type[] genericTypeArguments = serviceIdentifier.ServiceType.GenericTypeArguments;
					if (ServiceProvider.VerifyAotCompatibility)
					{
						VerifyOpenGenericAotCompatibility(serviceIdentifier.ServiceType, genericTypeArguments);
					}
					implementationType2 = implementationType.MakeGenericType(genericTypeArguments);
				}
				catch (ArgumentException)
				{
					if (throwOnConstraintViolation)
					{
						throw;
					}
					return null;
				}
				return _callSiteCache[key] = CreateConstructorCallSite(lifetime, serviceIdentifier, implementationType2, callSiteChain);
			}
			return null;
		}

		private ConstructorCallSite CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, CallSiteChain callSiteChain)
		{
			try
			{
				callSiteChain.Add(serviceIdentifier, implementationType);
				ConstructorInfo[] constructors = implementationType.GetConstructors();
				ServiceCallSite[] parameterCallSites = null;
				if (constructors.Length == 0)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.NoConstructorMatch, implementationType));
				}
				if (constructors.Length == 1)
				{
					ConstructorInfo constructorInfo = constructors[0];
					ParameterInfo[] parameters = constructorInfo.GetParameters();
					if (parameters.Length == 0)
					{
						return new ConstructorCallSite(lifetime, serviceIdentifier.ServiceType, constructorInfo);
					}
					parameterCallSites = CreateArgumentCallSites(serviceIdentifier, implementationType, callSiteChain, parameters, throwIfCallSiteNotFound: true);
					return new ConstructorCallSite(lifetime, serviceIdentifier.ServiceType, constructorInfo, parameterCallSites);
				}
				Array.Sort(constructors, (ConstructorInfo a, ConstructorInfo b) => b.GetParameters().Length.CompareTo(a.GetParameters().Length));
				ConstructorInfo constructorInfo2 = null;
				HashSet<Type> hashSet = null;
				for (int i = 0; i < constructors.Length; i++)
				{
					ParameterInfo[] parameters2 = constructors[i].GetParameters();
					ServiceCallSite[] array = CreateArgumentCallSites(serviceIdentifier, implementationType, callSiteChain, parameters2, throwIfCallSiteNotFound: false);
					if (array == null)
					{
						continue;
					}
					if (constructorInfo2 == null)
					{
						constructorInfo2 = constructors[i];
						parameterCallSites = array;
						continue;
					}
					ParameterInfo[] parameters3;
					if (hashSet == null)
					{
						hashSet = new HashSet<Type>();
						parameters3 = constructorInfo2.GetParameters();
						foreach (ParameterInfo parameterInfo in parameters3)
						{
							hashSet.Add(parameterInfo.ParameterType);
						}
					}
					parameters3 = parameters2;
					foreach (ParameterInfo parameterInfo2 in parameters3)
					{
						if (!hashSet.Contains(parameterInfo2.ParameterType))
						{
							throw new InvalidOperationException(string.Join(Environment.NewLine, System.SR.Format(System.SR.AmbiguousConstructorException, implementationType), constructorInfo2, constructors[i]));
						}
					}
				}
				if (constructorInfo2 == null)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.UnableToActivateTypeException, implementationType));
				}
				return new ConstructorCallSite(lifetime, serviceIdentifier.ServiceType, constructorInfo2, parameterCallSites);
			}
			finally
			{
				callSiteChain.Remove(serviceIdentifier);
			}
		}

		private ServiceCallSite[] CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)
		{
			ServiceCallSite[] array = new ServiceCallSite[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				ServiceCallSite serviceCallSite = null;
				bool flag = false;
				Type parameterType = parameters[i].ParameterType;
				object[] customAttributes = parameters[i].GetCustomAttributes(inherit: true);
				foreach (object obj in customAttributes)
				{
					if (serviceIdentifier.ServiceKey != null && obj is ServiceKeyAttribute)
					{
						if (parameterType != serviceIdentifier.ServiceKey.GetType())
						{
							throw new InvalidOperationException(System.SR.InvalidServiceKeyType);
						}
						serviceCallSite = new ConstantCallSite(parameterType, serviceIdentifier.ServiceKey);
						break;
					}
					FromKeyedServicesAttribute val = (FromKeyedServicesAttribute)((obj is FromKeyedServicesAttribute) ? obj : null);
					if (val != null)
					{
						ServiceIdentifier serviceIdentifier2 = new ServiceIdentifier(val.Key, parameterType);
						serviceCallSite = GetCallSite(serviceIdentifier2, callSiteChain);
						flag = true;
						break;
					}
				}
				if (!flag && serviceCallSite == null)
				{
					serviceCallSite = GetCallSite(ServiceIdentifier.FromServiceType(parameterType), callSiteChain);
				}
				if (serviceCallSite == null && Microsoft.Extensions.Internal.ParameterDefaultValue.TryGetDefaultValue(parameters[i], out object defaultValue))
				{
					serviceCallSite = new ConstantCallSite(parameterType, defaultValue);
				}
				if (serviceCallSite == null)
				{
					if (throwIfCallSiteNotFound)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.CannotResolveService, parameterType, implementationType));
					}
					return null;
				}
				array[i] = serviceCallSite;
			}
			return array;
		}

		private static void VerifyOpenGenericAotCompatibility(Type serviceType, Type[] genericTypeArguments)
		{
			foreach (Type type in genericTypeArguments)
			{
				if (type.IsValueType)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.AotCannotCreateGenericValueType, serviceType, type));
				}
			}
		}

		public void Add(ServiceIdentifier serviceIdentifier, ServiceCallSite serviceCallSite)
		{
			_callSiteCache[new ServiceCacheKey(serviceIdentifier, 0)] = serviceCallSite;
		}

		public bool IsService(Type serviceType)
		{
			return IsService(new ServiceIdentifier(null, serviceType));
		}

		public bool IsKeyedService(Type serviceType, object? key)
		{
			return IsService(new ServiceIdentifier(key, serviceType));
		}

		internal bool IsService(ServiceIdentifier serviceIdentifier)
		{
			Type serviceType = serviceIdentifier.ServiceType;
			if ((object)serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (serviceType.IsGenericTypeDefinition)
			{
				return false;
			}
			if (_descriptorLookup.ContainsKey(serviceIdentifier))
			{
				return true;
			}
			if (serviceIdentifier.ServiceKey != null && _descriptorLookup.ContainsKey(new ServiceIdentifier(KeyedService.AnyKey, serviceType)))
			{
				return true;
			}
			if (serviceType.IsConstructedGenericType)
			{
				Type genericTypeDefinition = serviceType.GetGenericTypeDefinition();
				if ((object)genericTypeDefinition != null)
				{
					if (!(genericTypeDefinition == typeof(IEnumerable<>)))
					{
						return _descriptorLookup.ContainsKey(serviceIdentifier.GetGenericTypeDefinition());
					}
					return true;
				}
			}
			if (!(serviceType == typeof(IServiceProvider)) && !(serviceType == typeof(IServiceScopeFactory)) && !(serviceType == typeof(IServiceProviderIsService)))
			{
				return serviceType == typeof(IServiceProviderIsKeyedService);
			}
			return true;
		}

		private static bool KeysMatch(object key1, object key2)
		{
			if (key1 == null && key2 == null)
			{
				return true;
			}
			if (key1 != null && key2 != null)
			{
				if (!key1.Equals(key2) && !key1.Equals(KeyedService.AnyKey))
				{
					return key2.Equals(KeyedService.AnyKey);
				}
				return true;
			}
			return false;
		}
	}
	internal enum CallSiteKind
	{
		Factory,
		Constructor,
		Constant,
		IEnumerable,
		ServiceProvider
	}
	internal enum CallSiteResultCacheLocation
	{
		Root,
		Scope,
		Dispose,
		None
	}
	internal sealed class CallSiteRuntimeResolver : CallSiteVisitor<RuntimeResolverContext, object?>
	{
		public static CallSiteRuntimeResolver Instance { get; } = new CallSiteRuntimeResolver();


		private CallSiteRuntimeResolver()
		{
		}

		public object? Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
		{
			if (scope.IsRootScope)
			{
				object value = callSite.Value;
				if (value != null)
				{
					return value;
				}
			}
			return VisitCallSite(callSite, new RuntimeResolverContext
			{
				Scope = scope
			});
		}

		protected override object? VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context)
		{
			return context.Scope.CaptureDisposable(VisitCallSiteMain(transientCallSite, context));
		}

		protected override object VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
		{
			object[] array;
			if (constructorCallSite.ParameterCallSites.Length == 0)
			{
				array = Array.Empty<object>();
			}
			else
			{
				array = new object[constructorCallSite.ParameterCallSites.Length];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = VisitCallSite(constructorCallSite.ParameterCallSites[i], context);
				}
			}
			return constructorCallSite.ConstructorInfo.Invoke(BindingFlags.DoNotWrapExceptions, null, array, null);
		}

		protected override object? VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
		{
			object value = callSite.Value;
			if (value != null)
			{
				return value;
			}
			RuntimeResolverLock runtimeResolverLock = RuntimeResolverLock.Root;
			ServiceProviderEngineScope root = context.Scope.RootProvider.Root;
			lock (callSite)
			{
				object value2 = callSite.Value;
				if (value2 != null)
				{
					return value2;
				}
				object obj = VisitCallSiteMain(callSite, new RuntimeResolverContext
				{
					Scope = root,
					AcquiredLocks = (context.AcquiredLocks | runtimeResolverLock)
				});
				root.CaptureDisposable(obj);
				callSite.Value = obj;
				return obj;
			}
		}

		protected override object? VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
		{
			if (!context.Scope.IsRootScope)
			{
				return VisitCache(callSite, context, context.Scope, RuntimeResolverLock.Scope);
			}
			return VisitRootCache(callSite, context);
		}

		private object VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
		{
			bool lockTaken = false;
			object sync = serviceProviderEngine.Sync;
			Dictionary<ServiceCacheKey, object> resolvedServices = serviceProviderEngine.ResolvedServices;
			if ((context.AcquiredLocks & lockType) == 0)
			{
				Monitor.Enter(sync, ref lockTaken);
			}
			try
			{
				if (resolvedServices.TryGetValue(callSite.Cache.Key, out var value))
				{
					return value;
				}
				value = VisitCallSiteMain(callSite, new RuntimeResolverContext
				{
					Scope = serviceProviderEngine,
					AcquiredLocks = (context.AcquiredLocks | lockType)
				});
				serviceProviderEngine.CaptureDisposable(value);
				resolvedServices.Add(callSite.Cache.Key, value);
				return value;
			}
			finally
			{
				if (lockTaken)
				{
					Monitor.Exit(sync);
				}
			}
		}

		protected override object? VisitConstant(ConstantCallSite constantCallSite, RuntimeResolverContext context)
		{
			return constantCallSite.DefaultValue;
		}

		protected override object VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, RuntimeResolverContext context)
		{
			return context.Scope;
		}

		protected override object VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context)
		{
			Array array = CreateArray(enumerableCallSite.ItemType, enumerableCallSite.ServiceCallSites.Length);
			for (int i = 0; i < enumerableCallSite.ServiceCallSites.Length; i++)
			{
				object value = VisitCallSite(enumerableCallSite.ServiceCallSites[i], context);
				array.SetValue(value, i);
			}
			return array;
			[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "VerifyAotCompatibility ensures elementType is not a ValueType")]
			static Array CreateArray(Type elementType, int length)
			{
				return Array.CreateInstance(elementType, length);
			}
		}

		protected override object VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
		{
			return factoryCallSite.Factory(context.Scope);
		}
	}
	internal struct RuntimeResolverContext
	{
		public ServiceProviderEngineScope Scope { get; set; }

		public RuntimeResolverLock AcquiredLocks { get; set; }
	}
	[Flags]
	internal enum RuntimeResolverLock
	{
		Scope = 1,
		Root = 2
	}
	internal sealed class CallSiteValidator : CallSiteVisitor<CallSiteValidator.CallSiteValidatorState, Type?>
	{
		internal struct CallSiteValidatorState
		{
			public ServiceCallSite? Singleton
			{
				get; [param: DisallowNull]
				set;
			}
		}

		private readonly ConcurrentDictionary<ServiceCacheKey, Type> _scopedServices = new ConcurrentDictionary<ServiceCacheKey, Type>();

		public void ValidateCallSite(ServiceCallSite callSite)
		{
			VisitCallSite(callSite, default(CallSiteValidatorState));
		}

		public void ValidateResolution(ServiceCallSite callSite, IServiceScope scope, IServiceScope rootScope)
		{
			if (scope == rootScope && _scopedServices.TryGetValue(callSite.Cache.Key, out var value) && value != null)
			{
				if (callSite.ServiceType == value)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.DirectScopedResolvedFromRootException, callSite.ServiceType, "Scoped".ToLowerInvariant()));
				}
				throw new InvalidOperationException(System.SR.Format(System.SR.ScopedResolvedFromRootException, callSite.ServiceType, value, "Scoped".ToLowerInvariant()));
			}
		}

		protected override Type? VisitCallSite(ServiceCallSite callSite, CallSiteValidatorState argument)
		{
			if (!_scopedServices.TryGetValue(callSite.Cache.Key, out var value))
			{
				value = base.VisitCallSite(callSite, argument);
				_scopedServices[callSite.Cache.Key] = value;
			}
			if (value != null && argument.Singleton != null)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.ScopedInSingletonException, callSite.ServiceType, argument.Singleton.ServiceType, "Scoped".ToLowerInvariant(), "Singleton".ToLowerInvariant()));
			}
			return value;
		}

		protected override Type? VisitConstructor(ConstructorCallSite constructorCallSite, CallSiteValidatorState state)
		{
			Type type = null;
			ServiceCallSite[] parameterCallSites = constructorCallSite.ParameterCallSites;
			foreach (ServiceCallSite callSite in parameterCallSites)
			{
				Type type2 = VisitCallSite(callSite, state);
				if ((object)type == null)
				{
					type = type2;
				}
			}
			return type;
		}

		protected override Type? VisitIEnumerable(IEnumerableCallSite enumerableCallSite, CallSiteValidatorState state)
		{
			Type type = null;
			ServiceCallSite[] serviceCallSites = enumerableCallSite.ServiceCallSites;
			foreach (ServiceCallSite callSite in serviceCallSites)
			{
				Type type2 = VisitCallSite(callSite, state);
				if ((object)type == null)
				{
					type = type2;
				}
			}
			return type;
		}

		protected override Type? VisitRootCache(ServiceCallSite singletonCallSite, CallSiteValidatorState state)
		{
			state.Singleton = singletonCallSite;
			return VisitCallSiteMain(singletonCallSite, state);
		}

		protected override Type? VisitScopeCache(ServiceCallSite scopedCallSite, CallSiteValidatorState state)
		{
			if (scopedCallSite.ServiceType == typeof(IServiceScopeFactory))
			{
				return null;
			}
			VisitCallSiteMain(scopedCallSite, state);
			return scopedCallSite.ServiceType;
		}

		protected override Type? VisitConstant(ConstantCallSite constantCallSite, CallSiteValidatorState state)
		{
			return null;
		}

		protected override Type? VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, CallSiteValidatorState state)
		{
			return null;
		}

		protected override Type? VisitFactory(FactoryCallSite factoryCallSite, CallSiteValidatorState state)
		{
			return null;
		}
	}
	internal abstract class CallSiteVisitor<TArgument, TResult>
	{
		private readonly StackGuard _stackGuard;

		protected CallSiteVisitor()
		{
			_stackGuard = new StackGuard();
		}

		protected virtual TResult VisitCallSite(ServiceCallSite callSite, TArgument argument)
		{
			if (!_stackGuard.TryEnterOnCurrentStack())
			{
				return _stackGuard.RunOnEmptyStack(VisitCallSite, callSite, argument);
			}
			return callSite.Cache.Location switch
			{
				CallSiteResultCacheLocation.Root => VisitRootCache(callSite, argument), 
				CallSiteResultCacheLocation.Scope => VisitScopeCache(callSite, argument), 
				CallSiteResultCacheLocation.Dispose => VisitDisposeCache(callSite, argument), 
				CallSiteResultCacheLocation.None => VisitNoCache(callSite, argument), 
				_ => throw new ArgumentOutOfRangeException(), 
			};
		}

		protected virtual TResult VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
		{
			return callSite.Kind switch
			{
				CallSiteKind.Factory => VisitFactory((FactoryCallSite)callSite, argument), 
				CallSiteKind.IEnumerable => VisitIEnumerable((IEnumerableCallSite)callSite, argument), 
				CallSiteKind.Constructor => VisitConstructor((ConstructorCallSite)callSite, argument), 
				CallSiteKind.Constant => VisitConstant((ConstantCallSite)callSite, argument), 
				CallSiteKind.ServiceProvider => VisitServiceProvider((ServiceProviderCallSite)callSite, argument), 
				_ => throw new NotSupportedException(System.SR.Format(System.SR.CallSiteTypeNotSupported, callSite.GetType())), 
			};
		}

		protected virtual TResult VisitNoCache(ServiceCallSite callSite, TArgument argument)
		{
			return VisitCallSiteMain(callSite, argument);
		}

		protected virtual TResult VisitDisposeCache(ServiceCallSite callSite, TArgument argument)
		{
			return VisitCallSiteMain(callSite, argument);
		}

		protected virtual TResult VisitRootCache(ServiceCallSite callSite, TArgument argument)
		{
			return VisitCallSiteMain(callSite, argument);
		}

		protected virtual TResult VisitScopeCache(ServiceCallSite callSite, TArgument argument)
		{
			return VisitCallSiteMain(callSite, argument);
		}

		protected abstract TResult VisitConstructor(ConstructorCallSite constructorCallSite, TArgument argument);

		protected abstract TResult VisitConstant(ConstantCallSite constantCallSite, TArgument argument);

		protected abstract TResult VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, TArgument argument);

		protected abstract TResult VisitIEnumerable(IEnumerableCallSite enumerableCallSite, TArgument argument);

		protected abstract TResult VisitFactory(FactoryCallSite factoryCallSite, TArgument argument);
	}
	internal abstract class CompiledServiceProviderEngine : ServiceProviderEngine
	{
		public ILEmitResolverBuilder ResolverBuilder { get; }

		[RequiresDynamicCode("Creates DynamicMethods")]
		public CompiledServiceProviderEngine(ServiceProvider provider)
		{
			ResolverBuilder = new ILEmitResolverBuilder(provider);
		}

		public override Func<ServiceProviderEngineScope, object?> RealizeService(ServiceCallSite callSite)
		{
			return ResolverBuilder.Build(callSite);
		}
	}
	internal sealed class ConstantCallSite : ServiceCallSite
	{
		private readonly Type _serviceType;

		internal object? DefaultValue => base.Value;

		public override Type ServiceType => _serviceType;

		public override Type ImplementationType => DefaultValue?.GetType() ?? _serviceType;

		public override CallSiteKind Kind { get; } = CallSiteKind.Constant;


		public ConstantCallSite(Type serviceType, object? defaultValue)
			: base(ResultCache.None(serviceType))
		{
			_serviceType = serviceType ?? throw new ArgumentNullException("serviceType");
			if (defaultValue != null && !serviceType.IsInstanceOfType(defaultValue))
			{
				throw new ArgumentException(System.SR.Format(System.SR.ConstantCantBeConvertedToServiceType, defaultValue.GetType(), serviceType));
			}
			base.Value = defaultValue;
		}
	}
	internal sealed class ConstructorCallSite : ServiceCallSite
	{
		internal ConstructorInfo ConstructorInfo { get; }

		internal ServiceCallSite[] ParameterCallSites { get; }

		public override Type ServiceType { get; }

		public override Type? ImplementationType => ConstructorInfo.DeclaringType;

		public override CallSiteKind Kind { get; } = CallSiteKind.Constructor;


		public ConstructorCallSite(ResultCache cache, Type serviceType, ConstructorInfo constructorInfo)
			: this(cache, serviceType, constructorInfo, Array.Empty<ServiceCallSite>())
		{
		}

		public ConstructorCallSite(ResultCache cache, Type serviceType, ConstructorInfo constructorInfo, ServiceCallSite[] parameterCallSites)
			: base(cache)
		{
			if (!serviceType.IsAssignableFrom(constructorInfo.DeclaringType))
			{
				throw new ArgumentException(System.SR.Format(System.SR.ImplementationTypeCantBeConvertedToServiceType, constructorInfo.DeclaringType, serviceType));
			}
			ServiceType = serviceType;
			ConstructorInfo = constructorInfo;
			ParameterCallSites = parameterCallSites;
		}
	}
	internal sealed class DynamicServiceProviderEngine : CompiledServiceProviderEngine
	{
		private readonly ServiceProvider _serviceProvider;

		[RequiresDynamicCode("Creates DynamicMethods")]
		public DynamicServiceProviderEngine(ServiceProvider serviceProvider)
			: base(serviceProvider)
		{
			_serviceProvider = serviceProvider;
		}

		public override Func<ServiceProviderEngineScope, object?> RealizeService(ServiceCallSite callSite)
		{
			ServiceCallSite callSite2 = callSite;
			int callCount = 0;
			return delegate(ServiceProviderEngineScope scope)
			{
				object? result = CallSiteRuntimeResolver.Instance.Resolve(callSite2, scope);
				if (Interlocked.Increment(ref callCount) == 2)
				{
					ThreadPool.UnsafeQueueUserWorkItem(delegate
					{
						try
						{
							_serviceProvider.ReplaceServiceAccessor(callSite2, base.RealizeService(callSite2));
						}
						catch (Exception exception)
						{
							DependencyInjectionEventSource.Log.ServiceRealizationFailed(exception, _serviceProvider.GetHashCode());
						}
					}, null);
				}
				return result;
			};
		}
	}
	internal sealed class ExpressionResolverBuilder : CallSiteVisitor<object?, Expression>
	{
		private static readonly ParameterExpression ScopeParameter = Expression.Parameter(typeof(ServiceProviderEngineScope));

		private static readonly ParameterExpression ResolvedServices = Expression.Variable(typeof(IDictionary<ServiceCacheKey, object>), ScopeParameter.Name + "resolvedServices");

		private static readonly ParameterExpression Sync = Expression.Variable(typeof(object), ScopeParameter.Name + "sync");

		private static readonly BinaryExpression ResolvedServicesVariableAssignment = Expression.Assign(ResolvedServices, Expression.Property(ScopeParameter, typeof(ServiceProviderEngineScope).GetProperty("ResolvedServices", BindingFlags.Instance | BindingFlags.NonPublic)));

		private static readonly BinaryExpression SyncVariableAssignment = Expression.Assign(Sync, Expression.Property(ScopeParameter, typeof(ServiceProviderEngineScope).GetProperty("Sync", BindingFlags.Instance | BindingFlags.NonPublic)));

		private static readonly ParameterExpression CaptureDisposableParameter = Expression.Parameter(typeof(object));

		private static readonly LambdaExpression CaptureDisposable = Expression.Lambda(typeof(Func<object, object>), Expression.Call(ScopeParameter, ServiceLookupHelpers.CaptureDisposableMethodInfo, CaptureDisposableParameter), CaptureDisposableParameter);

		private static readonly ConstantExpression CallSiteRuntimeResolverInstanceExpression = Expression.Constant(CallSiteRuntimeResolver.Instance, typeof(CallSiteRuntimeResolver));

		private readonly ServiceProviderEngineScope _rootScope;

		private readonly ConcurrentDictionary<ServiceCacheKey, Func<ServiceProviderEngineScope, object>> _scopeResolverCache;

		private readonly Func<ServiceCacheKey, ServiceCallSite, Func<ServiceProviderEngineScope, object>> _buildTypeDelegate;

		public ExpressionResolverBuilder(ServiceProvider serviceProvider)
		{
			_rootScope = serviceProvider.Root;
			_scopeResolverCache = new ConcurrentDictionary<ServiceCacheKey, Func<ServiceProviderEngineScope, object>>();
			_buildTypeDelegate = (ServiceCacheKey key, ServiceCallSite cs) => BuildNoCache(cs);
		}

		public Func<ServiceProviderEngineScope, object> Build(ServiceCallSite callSite)
		{
			if (callSite.Cache.Location == CallSiteResultCacheLocation.Scope)
			{
				return _scopeResolverCache.GetOrAdd(callSite.Cache.Key, _buildTypeDelegate, callSite);
			}
			return BuildNoCache(callSite);
		}

		public Func<ServiceProviderEngineScope, object> BuildNoCache(ServiceCallSite callSite)
		{
			Expression<Func<ServiceProviderEngineScope, object>> expression = BuildExpression(callSite);
			DependencyInjectionEventSource.Log.ExpressionTreeGenerated(_rootScope.RootProvider, callSite.ServiceType, expression);
			return expression.Compile();
		}

		private Expression<Func<ServiceProviderEngineScope, object>> BuildExpression(ServiceCallSite callSite)
		{
			if (callSite.Cache.Location == CallSiteResultCacheLocation.Scope)
			{
				return Expression.Lambda<Func<ServiceProviderEngineScope, object>>(Expression.Block(new ParameterExpression[2] { ResolvedServices, Sync }, ResolvedServicesVariableAssignment, SyncVariableAssignment, BuildScopedExpression(callSite)), new ParameterExpression[1] { ScopeParameter });
			}
			return Expression.Lambda<Func<ServiceProviderEngineScope, object>>(Convert(VisitCallSite(callSite, null), typeof(object), forceValueTypeConversion: true), new ParameterExpression[1] { ScopeParameter });
		}

		protected override Expression VisitRootCache(ServiceCallSite singletonCallSite, object? context)
		{
			return Expression.Constant(CallSiteRuntimeResolver.Instance.Resolve(singletonCallSite, _rootScope));
		}

		protected override Expression VisitConstant(ConstantCallSite constantCallSite, object? context)
		{
			return Expression.Constant(constantCallSite.DefaultValue);
		}

		protected override Expression VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, object? context)
		{
			return ScopeParameter;
		}

		protected override Expression VisitFactory(FactoryCallSite factoryCallSite, object? context)
		{
			return Expression.Invoke(Expression.Constant(factoryCallSite.Factory), ScopeParameter);
		}

		protected override Expression VisitIEnumerable(IEnumerableCallSite callSite, object? context)
		{
			object context2 = context;
			IEnumerableCallSite callSite2 = callSite;
			if (callSite2.ServiceCallSites.Length == 0)
			{
				return Expression.Constant(GetArrayEmptyMethodInfo(callSite2.ItemType).Invoke(null, Array.Empty<object>()));
			}
			return NewArrayInit(callSite2.ItemType, callSite2.ServiceCallSites.Select((ServiceCallSite cs) => Convert(VisitCallSite(cs, context2), callSite2.ItemType)));
			[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "VerifyAotCompatibility ensures elementType is not a ValueType")]
			static MethodInfo GetArrayEmptyMethodInfo(Type elementType)
			{
				return ServiceLookupHelpers.GetArrayEmptyMethodInfo(elementType);
			}
			[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "VerifyAotCompatibility ensures elementType is not a ValueType")]
			static NewArrayExpression NewArrayInit(Type elementType, IEnumerable<Expression> expr)
			{
				return Expression.NewArrayInit(elementType, expr);
			}
		}

		protected override Expression VisitDisposeCache(ServiceCallSite callSite, object? context)
		{
			return TryCaptureDisposable(callSite, ScopeParameter, VisitCallSiteMain(callSite, context));
		}

		private static Expression TryCaptureDisposable(ServiceCallSite callSite, ParameterExpression scope, Expression service)
		{
			if (!callSite.CaptureDisposable)
			{
				return service;
			}
			return Expression.Invoke(GetCaptureDisposable(scope), service);
		}

		protected override Expression VisitConstructor(ConstructorCallSite callSite, object? context)
		{
			ParameterInfo[] parameters = callSite.ConstructorInfo.GetParameters();
			Expression[] array;
			if (callSite.ParameterCallSites.Length == 0)
			{
				array = Array.Empty<Expression>();
			}
			else
			{
				array = new Expression[callSite.ParameterCallSites.Length];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = Convert(VisitCallSite(callSite.ParameterCallSites[i], context), parameters[i].ParameterType);
				}
			}
			Expression expression = Expression.New(callSite.ConstructorInfo, array);
			if (callSite.ImplementationType.IsValueType)
			{
				expression = Expression.Convert(expression, typeof(object));
			}
			return expression;
		}

		private static Expression Convert(Expression expression, Type type, bool forceValueTypeConversion = false)
		{
			if (type.IsAssignableFrom(expression.Type) && (!expression.Type.IsValueType || !forceValueTypeConversion))
			{
				return expression;
			}
			return Expression.Convert(expression, type);
		}

		protected override Expression VisitScopeCache(ServiceCallSite callSite, object? context)
		{
			return Expression.Invoke(Expression.Constant(Build(callSite)), ScopeParameter);
		}

		private ConditionalExpression BuildScopedExpression(ServiceCallSite callSite)
		{
			ConstantExpression arg = Expression.Constant(callSite, typeof(ServiceCallSite));
			MethodCallExpression ifTrue = Expression.Call(CallSiteRuntimeResolverInstanceExpression, ServiceLookupHelpers.ResolveCallSiteAndScopeMethodInfo, arg, ScopeParameter);
			ConstantExpression arg2 = Expression.Constant(callSite.Cache.Key, typeof(ServiceCacheKey));
			ParameterExpression parameterExpression = Expression.Variable(typeof(object), "resolved");
			ParameterExpression resolvedServices = ResolvedServices;
			MethodCallExpression expression = Expression.Call(resolvedServices, ServiceLookupHelpers.TryGetValueMethodInfo, arg2, parameterExpression);
			Expression right = TryCaptureDisposable(callSite, ScopeParameter, VisitCallSiteMain(callSite, null));
			BinaryExpression arg3 = Expression.Assign(parameterExpression, right);
			MethodCallExpression arg4 = Expression.Call(resolvedServices, ServiceLookupHelpers.AddMethodInfo, arg2, parameterExpression);
			BlockExpression arg5 = Expression.Block(typeof(object), new ParameterExpression[1] { parameterExpression }, Expression.IfThen(Expression.Not(expression), Expression.Block(arg3, arg4)), parameterExpression);
			ParameterExpression parameterExpression2 = Expression.Variable(typeof(bool), "lockWasTaken");
			ParameterExpression sync = Sync;
			MethodCallExpression arg6 = Expression.Call(ServiceLookupHelpers.MonitorEnterMethodInfo, sync, parameterExpression2);
			MethodCallExpression ifTrue2 = Expression.Call(ServiceLookupHelpers.MonitorExitMethodInfo, sync);
			BlockExpression body = Expression.Block(arg6, arg5);
			ConditionalExpression @finally = Expression.IfThen(parameterExpression2, ifTrue2);
			return Expression.Condition(Expression.Property(ScopeParameter, typeof(ServiceProviderEngineScope).GetProperty("IsRootScope", BindingFlags.Instance | BindingFlags.Public)), ifTrue, Expression.Block(typeof(object), new ParameterExpression[1] { parameterExpression2 }, Expression.TryFinally(body, @finally)));
		}

		public static Expression GetCaptureDisposable(ParameterExpression scope)
		{
			if (scope != ScopeParameter)
			{
				throw new NotSupportedException(System.SR.GetCaptureDisposableNotSupported);
			}
			return CaptureDisposable;
		}
	}
	internal sealed class ExpressionsServiceProviderEngine : ServiceProviderEngine
	{
		private readonly ExpressionResolverBuilder _expressionResolverBuilder;

		public ExpressionsServiceProviderEngine(ServiceProvider serviceProvider)
		{
			_expressionResolverBuilder = new ExpressionResolverBuilder(serviceProvider);
		}

		public override Func<ServiceProviderEngineScope, object> RealizeService(ServiceCallSite callSite)
		{
			return _expressionResolverBuilder.Build(callSite);
		}
	}
	internal sealed class FactoryCallSite : ServiceCallSite
	{
		public Func<IServiceProvider, object> Factory { get; }

		public override Type ServiceType { get; }

		public override Type? ImplementationType => null;

		public override CallSiteKind Kind { get; }

		public FactoryCallSite(ResultCache cache, Type serviceType, Func<IServiceProvider, object> factory)
			: base(cache)
		{
			Factory = factory;
			ServiceType = serviceType;
		}

		public FactoryCallSite(ResultCache cache, Type serviceType, object serviceKey, Func<IServiceProvider, object, object> factory)
		{
			Func<IServiceProvider, object, object> factory2 = factory;
			object serviceKey2 = serviceKey;
			base..ctor(cache);
			Factory = (IServiceProvider sp) => factory2(sp, serviceKey2);
			ServiceType = serviceType;
		}
	}
	internal sealed class IEnumerableCallSite : ServiceCallSite
	{
		internal Type ItemType { get; }

		internal ServiceCallSite[] ServiceCallSites { get; }

		[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "When ServiceProvider.VerifyAotCompatibility is true, which it is by default when PublishAot=true, CallSiteFactory ensures ItemType is not a ValueType.")]
		public override Type ServiceType => typeof(IEnumerable<>).MakeGenericType(ItemType);

		[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "When ServiceProvider.VerifyAotCompatibility is true, which it is by default when PublishAot=true, CallSiteFactory ensures ItemType is not a ValueType.")]
		public override Type ImplementationType => ItemType.MakeArrayType();

		public override CallSiteKind Kind { get; } = CallSiteKind.IEnumerable;


		public IEnumerableCallSite(ResultCache cache, Type itemType, ServiceCallSite[] serviceCallSites)
			: base(cache)
		{
			ItemType = itemType;
			ServiceCallSites = serviceCallSites;
		}
	}
	internal struct ResultCache
	{
		public CallSiteResultCacheLocation Location { get; set; }

		public ServiceCacheKey Key { get; set; }

		public static ResultCache None(Type serviceType)
		{
			ServiceCacheKey cacheKey = new ServiceCacheKey(ServiceIdentifier.FromServiceType(serviceType), 0);
			return new ResultCache(CallSiteResultCacheLocation.None, cacheKey);
		}

		internal ResultCache(CallSiteResultCacheLocation lifetime, ServiceCacheKey cacheKey)
		{
			Location = lifetime;
			Key = cacheKey;
		}

		public ResultCache(ServiceLifetime lifetime, ServiceIdentifier serviceIdentifier, int slot)
		{
			switch (lifetime)
			{
			case ServiceLifetime.Singleton:
				Location = CallSiteResultCacheLocation.Root;
				break;
			case ServiceLifetime.Scoped:
				Location = CallSiteResultCacheLocation.Scope;
				break;
			case ServiceLifetime.Transient:
				Location = CallSiteResultCacheLocation.Dispose;
				break;
			default:
				Location = CallSiteResultCacheLocation.None;
				break;
			}
			Key = new ServiceCacheKey(serviceIdentifier, slot);
		}
	}
	internal sealed class RuntimeServiceProviderEngine : ServiceProviderEngine
	{
		public static RuntimeServiceProviderEngine Instance { get; } = new RuntimeServiceProviderEngine();


		private RuntimeServiceProviderEngine()
		{
		}

		public override Func<ServiceProviderEngineScope, object?> RealizeService(ServiceCallSite callSite)
		{
			ServiceCallSite callSite2 = callSite;
			return (ServiceProviderEngineScope scope) => CallSiteRuntimeResolver.Instance.Resolve(callSite2, scope);
		}
	}
	internal readonly struct ServiceCacheKey : IEquatable<ServiceCacheKey>
	{
		public ServiceIdentifier ServiceIdentifier { get; }

		public int Slot { get; }

		public ServiceCacheKey(object key, Type type, int slot)
		{
			ServiceIdentifier = new ServiceIdentifier(key, type);
			Slot = slot;
		}

		public ServiceCacheKey(ServiceIdentifier type, int slot)
		{
			ServiceIdentifier = type;
			Slot = slot;
		}

		public bool Equals(ServiceCacheKey other)
		{
			if (ServiceIdentifier.Equals(other.ServiceIdentifier))
			{
				return Slot == other.Slot;
			}
			return false;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is ServiceCacheKey other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return (ServiceIdentifier.GetHashCode() * 397) ^ Slot;
		}
	}
	internal abstract class ServiceCallSite
	{
		public abstract Type ServiceType { get; }

		public abstract Type? ImplementationType { get; }

		public abstract CallSiteKind Kind { get; }

		public ResultCache Cache { get; }

		public object? Value { get; set; }

		public object? Key { get; set; }

		public bool CaptureDisposable
		{
			get
			{
				if (!(ImplementationType == null) && !typeof(IDisposable).IsAssignableFrom(ImplementationType))
				{
					return typeof(IAsyncDisposable).IsAssignableFrom(ImplementationType);
				}
				return true;
			}
		}

		protected ServiceCallSite(ResultCache cache)
		{
			Cache = cache;
		}
	}
	internal static class ServiceDescriptorExtensions
	{
		public static bool HasImplementationInstance(this ServiceDescriptor serviceDescriptor)
		{
			return serviceDescriptor.GetImplementationInstance() != null;
		}

		public static bool HasImplementationFactory(this ServiceDescriptor serviceDescriptor)
		{
			return serviceDescriptor.GetImplementationFactory() != null;
		}

		public static bool HasImplementationType(this ServiceDescriptor serviceDescriptor)
		{
			return serviceDescriptor.GetImplementationType() != null;
		}

		public static object? GetImplementationInstance(this ServiceDescriptor serviceDescriptor)
		{
			if (!serviceDescriptor.IsKeyedService)
			{
				return serviceDescriptor.ImplementationInstance;
			}
			return serviceDescriptor.KeyedImplementationInstance;
		}

		public static object? GetImplementationFactory(this ServiceDescriptor serviceDescriptor)
		{
			if (!serviceDescriptor.IsKeyedService)
			{
				return serviceDescriptor.ImplementationFactory;
			}
			return serviceDescriptor.KeyedImplementationFactory;
		}

		[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
		public static Type? GetImplementationType(this ServiceDescriptor serviceDescriptor)
		{
			if (!serviceDescriptor.IsKeyedService)
			{
				return serviceDescriptor.ImplementationType;
			}
			return serviceDescriptor.KeyedImplementation

Microsoft.Extensions.Logging.Abstractions.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using FxResources.Microsoft.Extensions.Logging.Abstractions;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Abstractions")]
[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("Logging abstractions for Microsoft.Extensions.Logging.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Logging.ILogger\r\nMicrosoft.Extensions.Logging.ILoggerFactory\r\nMicrosoft.Extensions.Logging.ILogger<TCategoryName>\r\nMicrosoft.Extensions.Logging.LogLevel\r\nMicrosoft.Extensions.Logging.Logger<T>\r\nMicrosoft.Extensions.Logging.LoggerMessage\r\nMicrosoft.Extensions.Logging.Abstractions.NullLogger")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Logging.Abstractions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[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]
	internal sealed class IsByRefLikeAttribute : 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.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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.Microsoft.Extensions.Logging.Abstractions
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string UnexpectedNumberOfNamedParameters => GetResourceString("UnexpectedNumberOfNamedParameters");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Text
{
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string? s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string? s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public unsafe void Append(char* value, int length)
		{
			if (_pos > _chars.Length - length)
			{
				Grow(length);
			}
			Span<char> span = _chars.Slice(_pos, length);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = *(value++);
			}
			_pos += length;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
}
namespace Microsoft.Extensions.Internal
{
	internal static class TypeNameHelper
	{
		private readonly struct DisplayNameOptions
		{
			public bool FullName { get; }

			public bool IncludeGenericParameters { get; }

			public bool IncludeGenericParameterNames { get; }

			public char NestedTypeDelimiter { get; }

			public DisplayNameOptions(bool fullName, bool includeGenericParameterNames, bool includeGenericParameters, char nestedTypeDelimiter)
			{
				FullName = fullName;
				IncludeGenericParameters = includeGenericParameters;
				IncludeGenericParameterNames = includeGenericParameterNames;
				NestedTypeDelimiter = nestedTypeDelimiter;
			}
		}

		private const char DefaultNestedTypeDelimiter = '+';

		private static readonly Dictionary<Type, string> _builtInTypeNames = new Dictionary<Type, string>
		{
			{
				typeof(void),
				"void"
			},
			{
				typeof(bool),
				"bool"
			},
			{
				typeof(byte),
				"byte"
			},
			{
				typeof(char),
				"char"
			},
			{
				typeof(decimal),
				"decimal"
			},
			{
				typeof(double),
				"double"
			},
			{
				typeof(float),
				"float"
			},
			{
				typeof(int),
				"int"
			},
			{
				typeof(long),
				"long"
			},
			{
				typeof(object),
				"object"
			},
			{
				typeof(sbyte),
				"sbyte"
			},
			{
				typeof(short),
				"short"
			},
			{
				typeof(string),
				"string"
			},
			{
				typeof(uint),
				"uint"
			},
			{
				typeof(ulong),
				"ulong"
			},
			{
				typeof(ushort),
				"ushort"
			}
		};

		[return: NotNullIfNotNull("item")]
		public static string? GetTypeDisplayName(object? item, bool fullName = true)
		{
			if (item != null)
			{
				return GetTypeDisplayName(item.GetType(), fullName);
			}
			return null;
		}

		public static string GetTypeDisplayName(Type type, bool fullName = true, bool includeGenericParameterNames = false, bool includeGenericParameters = true, char nestedTypeDelimiter = '+')
		{
			StringBuilder builder = null;
			DisplayNameOptions options = new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter);
			return ProcessType(ref builder, type, in options) ?? builder?.ToString() ?? string.Empty;
		}

		private static string ProcessType(ref StringBuilder builder, Type type, in DisplayNameOptions options)
		{
			string value;
			if (type.IsGenericType)
			{
				Type[] genericArguments = type.GetGenericArguments();
				if (builder == null)
				{
					builder = new StringBuilder();
				}
				ProcessGenericType(builder, type, genericArguments, genericArguments.Length, in options);
			}
			else if (type.IsArray)
			{
				if (builder == null)
				{
					builder = new StringBuilder();
				}
				ProcessArrayType(builder, type, in options);
			}
			else if (_builtInTypeNames.TryGetValue(type, out value))
			{
				if (builder == null)
				{
					return value;
				}
				builder.Append(value);
			}
			else if (type.IsGenericParameter)
			{
				if (options.IncludeGenericParameterNames)
				{
					if (builder == null)
					{
						return type.Name;
					}
					builder.Append(type.Name);
				}
			}
			else
			{
				string text = (options.FullName ? type.FullName : type.Name);
				if (builder == null)
				{
					if (options.NestedTypeDelimiter != '+')
					{
						return text.Replace('+', options.NestedTypeDelimiter);
					}
					return text;
				}
				builder.Append(text);
				if (options.NestedTypeDelimiter != '+')
				{
					builder.Replace('+', options.NestedTypeDelimiter, builder.Length - text.Length, text.Length);
				}
			}
			return null;
		}

		private static void ProcessArrayType(StringBuilder builder, Type type, in DisplayNameOptions options)
		{
			Type type2 = type;
			while (type2.IsArray)
			{
				type2 = type2.GetElementType();
			}
			ProcessType(ref builder, type2, in options);
			while (type.IsArray)
			{
				builder.Append('[');
				builder.Append(',', type.GetArrayRank() - 1);
				builder.Append(']');
				type = type.GetElementType();
			}
		}

		private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, in DisplayNameOptions options)
		{
			int num = 0;
			if (type.IsNested)
			{
				num = type.DeclaringType.GetGenericArguments().Length;
			}
			if (options.FullName)
			{
				if (type.IsNested)
				{
					ProcessGenericType(builder, type.DeclaringType, genericArguments, num, in options);
					builder.Append(options.NestedTypeDelimiter);
				}
				else if (!string.IsNullOrEmpty(type.Namespace))
				{
					builder.Append(type.Namespace);
					builder.Append('.');
				}
			}
			int num2 = type.Name.IndexOf('`');
			if (num2 <= 0)
			{
				builder.Append(type.Name);
				return;
			}
			builder.Append(type.Name, 0, num2);
			if (!options.IncludeGenericParameters)
			{
				return;
			}
			builder.Append('<');
			for (int i = num; i < length; i++)
			{
				ProcessType(ref builder, genericArguments[i], in options);
				if (i + 1 != length)
				{
					builder.Append(',');
					if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter)
					{
						builder.Append(' ');
					}
				}
			}
			builder.Append('>');
		}
	}
}
namespace Microsoft.Extensions.Logging
{
	public readonly struct EventId : IEquatable<EventId>
	{
		public int Id { get; }

		public string? Name { get; }

		public static implicit operator EventId(int i)
		{
			return new EventId(i);
		}

		public static bool operator ==(EventId left, EventId right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(EventId left, EventId right)
		{
			return !left.Equals(right);
		}

		public EventId(int id, string? name = null)
		{
			Id = id;
			Name = name;
		}

		public override string ToString()
		{
			return Name ?? Id.ToString();
		}

		public bool Equals(EventId other)
		{
			return Id == other.Id;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (obj is EventId other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return Id;
		}
	}
	internal readonly struct FormattedLogValues : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>>
	{
		internal const int MaxCachedFormatters = 1024;

		private const string NullFormat = "[null]";

		private static int s_count;

		private static readonly ConcurrentDictionary<string, LogValuesFormatter> s_formatters = new ConcurrentDictionary<string, LogValuesFormatter>();

		private readonly LogValuesFormatter _formatter;

		private readonly object[] _values;

		private readonly string _originalMessage;

		internal LogValuesFormatter? Formatter => _formatter;

		public KeyValuePair<string, object?> this[int index]
		{
			get
			{
				if (index < 0 || index >= Count)
				{
					throw new IndexOutOfRangeException("index");
				}
				if (index == Count - 1)
				{
					return new KeyValuePair<string, object>("{OriginalFormat}", _originalMessage);
				}
				return _formatter.GetValue(_values, index);
			}
		}

		public int Count
		{
			get
			{
				if (_formatter == null)
				{
					return 1;
				}
				return _formatter.ValueNames.Count + 1;
			}
		}

		public FormattedLogValues(string? format, params object?[]? values)
		{
			if (values != null && values.Length != 0 && format != null)
			{
				if (s_count >= 1024)
				{
					if (!s_formatters.TryGetValue(format, out _formatter))
					{
						_formatter = new LogValuesFormatter(format);
					}
				}
				else
				{
					_formatter = s_formatters.GetOrAdd(format, delegate(string f)
					{
						Interlocked.Increment(ref s_count);
						return new LogValuesFormatter(f);
					});
				}
			}
			else
			{
				_formatter = null;
			}
			_originalMessage = format ?? "[null]";
			_values = values;
		}

		public IEnumerator<KeyValuePair<string, object?>> GetEnumerator()
		{
			int i = 0;
			while (i < Count)
			{
				yield return this[i];
				int num = i + 1;
				i = num;
			}
		}

		public override string ToString()
		{
			if (_formatter == null)
			{
				return _originalMessage;
			}
			return _formatter.Format(_values);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public interface IExternalScopeProvider
	{
		void ForEachScope<TState>(Action<object?, TState> callback, TState state);

		IDisposable Push(object? state);
	}
	public interface ILogger
	{
		void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter);

		bool IsEnabled(LogLevel logLevel);

		IDisposable? BeginScope<TState>(TState state) where TState : notnull;
	}
	public interface ILoggerFactory : IDisposable
	{
		ILogger CreateLogger(string categoryName);

		void AddProvider(ILoggerProvider provider);
	}
	public interface ILoggerProvider : IDisposable
	{
		ILogger CreateLogger(string categoryName);
	}
	public interface ILogger<out TCategoryName> : ILogger
	{
	}
	public interface ILoggingBuilder
	{
		IServiceCollection Services { get; }
	}
	public interface ISupportExternalScope
	{
		void SetScopeProvider(IExternalScopeProvider scopeProvider);
	}
	public class LogDefineOptions
	{
		public bool SkipEnabledCheck { get; set; }
	}
	public static class LoggerExtensions
	{
		private static readonly Func<FormattedLogValues, Exception, string> _messageFormatter = MessageFormatter;

		public static void LogDebug(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Debug, eventId, exception, message, args);
		}

		public static void LogDebug(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Debug, eventId, message, args);
		}

		public static void LogDebug(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Debug, exception, message, args);
		}

		public static void LogDebug(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Debug, message, args);
		}

		public static void LogTrace(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Trace, eventId, exception, message, args);
		}

		public static void LogTrace(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Trace, eventId, message, args);
		}

		public static void LogTrace(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Trace, exception, message, args);
		}

		public static void LogTrace(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Trace, message, args);
		}

		public static void LogInformation(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Information, eventId, exception, message, args);
		}

		public static void LogInformation(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Information, eventId, message, args);
		}

		public static void LogInformation(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Information, exception, message, args);
		}

		public static void LogInformation(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Information, message, args);
		}

		public static void LogWarning(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Warning, eventId, exception, message, args);
		}

		public static void LogWarning(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Warning, eventId, message, args);
		}

		public static void LogWarning(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Warning, exception, message, args);
		}

		public static void LogWarning(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Warning, message, args);
		}

		public static void LogError(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Error, eventId, exception, message, args);
		}

		public static void LogError(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Error, eventId, message, args);
		}

		public static void LogError(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Error, exception, message, args);
		}

		public static void LogError(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Error, message, args);
		}

		public static void LogCritical(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Critical, eventId, exception, message, args);
		}

		public static void LogCritical(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Critical, eventId, message, args);
		}

		public static void LogCritical(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Critical, exception, message, args);
		}

		public static void LogCritical(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Critical, message, args);
		}

		public static void Log(this ILogger logger, LogLevel logLevel, string? message, params object?[] args)
		{
			logger.Log(logLevel, 0, null, message, args);
		}

		public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(logLevel, eventId, null, message, args);
		}

		public static void Log(this ILogger logger, LogLevel logLevel, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(logLevel, 0, exception, message, args);
		}

		public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			System.ThrowHelper.ThrowIfNull(logger, "logger");
			logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter);
		}

		public static IDisposable? BeginScope(this ILogger logger, string messageFormat, params object?[] args)
		{
			System.ThrowHelper.ThrowIfNull(logger, "logger");
			return logger.BeginScope(new FormattedLogValues(messageFormat, args));
		}

		private static string MessageFormatter(FormattedLogValues state, Exception error)
		{
			return state.ToString();
		}
	}
	public class LoggerExternalScopeProvider : IExternalScopeProvider
	{
		private sealed class Scope : IDisposable
		{
			private readonly LoggerExternalScopeProvider _provider;

			private bool _isDisposed;

			public Scope Parent { get; }

			public object State { get; }

			internal Scope(LoggerExternalScopeProvider provider, object state, Scope parent)
			{
				_provider = provider;
				State = state;
				Parent = parent;
			}

			public override string ToString()
			{
				return State?.ToString();
			}

			public void Dispose()
			{
				if (!_isDisposed)
				{
					_provider._currentScope.Value = Parent;
					_isDisposed = true;
				}
			}
		}

		private readonly AsyncLocal<Scope> _currentScope = new AsyncLocal<Scope>();

		public void ForEachScope<TState>(Action<object?, TState> callback, TState state)
		{
			Action<object, TState> callback2 = callback;
			TState state2 = state;
			Report(_currentScope.Value);
			void Report(Scope? current)
			{
				if (current != null)
				{
					Report(current.Parent);
					callback2(current.State, state2);
				}
			}
		}

		public IDisposable Push(object? state)
		{
			Scope value = _currentScope.Value;
			Scope scope = new Scope(this, state, value);
			_currentScope.Value = scope;
			return scope;
		}
	}
	public static class LoggerFactoryExtensions
	{
		public static ILogger<T> CreateLogger<T>(this ILoggerFactory factory)
		{
			System.ThrowHelper.ThrowIfNull(factory, "factory");
			return new Logger<T>(factory);
		}

		public static ILogger CreateLogger(this ILoggerFactory factory, Type type)
		{
			System.ThrowHelper.ThrowIfNull(factory, "factory");
			System.ThrowHelper.ThrowIfNull(type, "type");
			return factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(type, fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.'));
		}
	}
	public static class LoggerMessage
	{
		private readonly struct LogValues : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			public static readonly Func<LogValues, Exception, string> Callback = (LogValues state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			public KeyValuePair<string, object> this[int index]
			{
				get
				{
					if (index == 0)
					{
						return new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat);
					}
					throw new IndexOutOfRangeException("index");
				}
			}

			public int Count => 1;

			public LogValues(LogValuesFormatter formatter)
			{
				_formatter = formatter;
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				yield return this[0];
			}

			public override string ToString()
			{
				return _formatter.Format();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			public static readonly Func<LogValues<T0>, Exception, string> Callback = (LogValues<T0> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public int Count => 2;

			public LogValues(LogValuesFormatter formatter, T0 value0)
			{
				_formatter = formatter;
				_value0 = value0;
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				int i = 0;
				while (i < Count)
				{
					yield return this[i];
					int num = i + 1;
					i = num;
				}
			}

			public override string ToString()
			{
				return _formatter.Format(_value0);
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			public static readonly Func<LogValues<T0, T1>, Exception, string> Callback = (LogValues<T0, T1> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public int Count => 3;

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				int i = 0;
				while (i < Count)
				{
					yield return this[i];
					int num = i + 1;
					i = num;
				}
			}

			public override string ToString()
			{
				return _formatter.Format(_value0, _value1);
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1, T2> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			public static readonly Func<LogValues<T0, T1, T2>, Exception, string> Callback = (LogValues<T0, T1, T2> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			private readonly T2 _value2;

			public int Count => 4;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 
				3 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
				_value2 = value2;
			}

			public override string ToString()
			{
				return _formatter.Format(_value0, _value1, _value2);
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				int i = 0;
				while (i < Count)
				{
					yield return this[i];
					int num = i + 1;
					i = num;
				}
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1, T2, T3> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			public static readonly Func<LogValues<T0, T1, T2, T3>, Exception, string> Callback = (LogValues<T0, T1, T2, T3> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			private readonly T2 _value2;

			private readonly T3 _value3;

			public int Count => 5;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 
				3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 
				4 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
				_value2 = value2;
				_value3 = value3;
			}

			private object[] ToArray()
			{
				return new object[4] { _value0, _value1, _value2, _value3 };
			}

			public override string ToString()
			{
				return _formatter.FormatWithOverwrite(ToArray());
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				int i = 0;
				while (i < Count)
				{
					yield return this[i];
					int num = i + 1;
					i = num;
				}
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1, T2, T3, T4> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			public static readonly Func<LogValues<T0, T1, T2, T3, T4>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			private readonly T2 _value2;

			private readonly T3 _value3;

			private readonly T4 _value4;

			public int Count => 6;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 
				3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 
				4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 
				5 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
				_value2 = value2;
				_value3 = value3;
				_value4 = value4;
			}

			private object[] ToArray()
			{
				return new object[5] { _value0, _value1, _value2, _value3, _value4 };
			}

			public override string ToString()
			{
				return _formatter.FormatWithOverwrite(ToArray());
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				int i = 0;
				while (i < Count)
				{
					yield return this[i];
					int num = i + 1;
					i = num;
				}
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1, T2, T3, T4, T5> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			public static readonly Func<LogValues<T0, T1, T2, T3, T4, T5>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4, T5> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			private readonly T2 _value2;

			private readonly T3 _value3;

			private readonly T4 _value4;

			private readonly T5 _value5;

			public int Count => 7;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 
				3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 
				4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 
				5 => new KeyValuePair<string, object>(_formatter.ValueNames[5], _value5), 
				6 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4, T5 value5)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
				_value2 = value2;
				_value3 = value3;
				_value4 = value4;
				_value5 = value5;
			}

			private object[] ToArray()
			{
				return new object[6] { _value0, _value1, _value2, _value3, _value4, _value5 };
			}

			public override string ToString()
			{
				return _formatter.FormatWithOverwrite(ToArray());
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				int i = 0;
				while (i < Count)
				{
					yield return this[i];
					int num = i + 1;
					i = num;
				}
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		public static Func<ILogger, IDisposable?> DefineScope(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0);
			LogValues logValues = new LogValues(formatter);
			return (ILogger logger) => logger.BeginScope(logValues);
		}

		public static Func<ILogger, T1, IDisposable?> DefineScope<T1>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1);
			return (ILogger logger, T1 arg1) => logger.BeginScope(new LogValues<T1>(formatter, arg1));
		}

		public static Func<ILogger, T1, T2, IDisposable?> DefineScope<T1, T2>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2);
			return (ILogger logger, T1 arg1, T2 arg2) => logger.BeginScope(new LogValues<T1, T2>(formatter, arg1, arg2));
		}

		public static Func<ILogger, T1, T2, T3, IDisposable?> DefineScope<T1, T2, T3>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3);
			return (ILogger logger, T1 arg1, T2 arg2, T3 arg3) => logger.BeginScope(new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3));
		}

		public static Func<ILogger, T1, T2, T3, T4, IDisposable?> DefineScope<T1, T2, T3, T4>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4);
			return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4) => logger.BeginScope(new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4));
		}

		public static Func<ILogger, T1, T2, T3, T4, T5, IDisposable?> DefineScope<T1, T2, T3, T4, T5>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5);
			return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5));
		}

		public static Func<ILogger, T1, T2, T3, T4, T5, T6, IDisposable?> DefineScope<T1, T2, T3, T4, T5, T6>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6);
			return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6));
		}

		public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, exception);
				}
			};
			void Log(ILogger logger, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues(formatter), exception, LogValues.Callback);
			}
		}

		public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1>(formatter, arg1), exception, LogValues<T1>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2>(formatter, arg1, arg2), exception, LogValues<T1, T2>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2, T3>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, arg3, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3), exception, LogValues<T1, T2, T3>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2, T3, T4>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, arg3, arg4, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4), exception, LogValues<T1, T2, T3, T4>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2, T3, T4, T5>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, arg3, arg4, arg5, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5), exception, LogValues<T1, T2, T3, T4, T5>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2, T3, T4, T5, T6>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, arg3, arg4, arg5, arg6, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6), exception, LogValues<T1, T2, T3, T4, T5, T6>.Callback);
			}
		}

		private static LogValuesFormatter CreateLogValuesFormatter(string formatString, int expectedNamedParameterCount)
		{
			LogValuesFormatter logValuesFormatter = new LogValuesFormatter(formatString);
			int count = logValuesFormatter.ValueNames.Count;
			if (count != expectedNamedParameterCount)
			{
				throw new ArgumentException(System.SR.Format(System.SR.UnexpectedNumberOfNamedParameters, formatString, expectedNamedParameterCount, count));
			}
			return logValuesFormatter;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public sealed class LoggerMessageAttribute : Attribute
	{
		public int EventId { get; set; } = -1;


		public string? EventName { get; set; }

		public LogLevel Level { get; set; } = LogLevel.None;


		public string Message { get; set; } = "";


		public bool SkipEnabledCheck { get; set; }

		public LoggerMessageAttribute()
		{
		}

		public LoggerMessageAttribute(int eventId, LogLevel level, string message)
		{
			EventId = eventId;
			Level = level;
			Message = message;
		}

		public LoggerMessageAttribute(LogLevel level, string message)
		{
			Level = level;
			Message = message;
		}

		public LoggerMessageAttribute(LogLevel level)
		{
			Level = level;
		}

		public LoggerMessageAttribute(string message)
		{
			Message = message;
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	public class Logger<T> : ILogger<T>, ILogger
	{
		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		private readonly ILogger _logger;

		public Logger(ILoggerFactory factory)
		{
			System.ThrowHelper.ThrowIfNull(factory, "factory");
			_logger = factory.CreateLogger(GetCategoryName());
		}

		IDisposable ILogger.BeginScope<TState>(TState state)
		{
			return _logger.BeginScope(state);
		}

		bool ILogger.IsEnabled(LogLevel logLevel)
		{
			return _logger.IsEnabled(logLevel);
		}

		void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
		{
			_logger.Log(logLevel, eventId, state, exception, formatter);
		}

		private static string GetCategoryName()
		{
			return TypeNameHelper.GetTypeDisplayName(typeof(T), fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.');
		}

		internal string DebuggerToString()
		{
			return DebuggerDisplayFormatting.DebuggerToString(GetCategoryName(), this);
		}
	}
	public enum LogLevel
	{
		Trace,
		Debug,
		Information,
		Warning,
		Error,
		Critical,
		None
	}
	internal sealed class LogValuesFormatter
	{
		private const string NullValue = "(null)";

		private readonly List<string> _valueNames = new List<string>();

		private readonly string _format;

		public string OriginalFormat { get; }

		public List<string> ValueNames => _valueNames;

		public LogValuesFormatter(string format)
		{
			System.ThrowHelper.ThrowIfNull(format, "format");
			OriginalFormat = format;
			Span<char> initialBuffer = stackalloc char[256];
			System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer);
			int num = 0;
			int length = format.Length;
			while (num < length)
			{
				int num2 = FindBraceIndex(format, '{', num, length);
				if (num == 0 && num2 == length)
				{
					_format = format;
					return;
				}
				int num3 = FindBraceIndex(format, '}', num2, length);
				if (num3 == length)
				{
					valueStringBuilder.Append(format.AsSpan(num, length - num));
					num = length;
					continue;
				}
				int num4 = format.AsSpan(num2, num3 - num2).IndexOfAny(',', ':');
				num4 = ((num4 < 0) ? num3 : (num4 + num2));
				valueStringBuilder.Append(format.AsSpan(num, num2 - num + 1));
				valueStringBuilder.Append(_valueNames.Count.ToString());
				_valueNames.Add(format.Substring(num2 + 1, num4 - num2 - 1));
				valueStringBuilder.Append(format.AsSpan(num4, num3 - num4 + 1));
				num = num3 + 1;
			}
			_format = valueStringBuilder.ToString();
		}

		private static int FindBraceIndex(string format, char brace, int startIndex, int endIndex)
		{
			int result = endIndex;
			int i = startIndex;
			int num = 0;
			for (; i < endIndex; i++)
			{
				if (num > 0 && format[i] != brace)
				{
					if (num % 2 != 0)
					{
						break;
					}
					num = 0;
					result = endIndex;
				}
				else
				{
					if (format[i] != brace)
					{
						continue;
					}
					if (brace == '}')
					{
						if (num == 0)
						{
							result = i;
						}
					}
					else
					{
						result = i;
					}
					num++;
				}
			}
			return result;
		}

		public string Format(object?[]? values)
		{
			object[] array = values;
			if (values != null)
			{
				for (int i = 0; i < values.Length; i++)
				{
					object obj = FormatArgument(values[i]);
					if (obj != values[i])
					{
						array = new object[values.Length];
						Array.Copy(values, array, i);
						array[i++] = obj;
						for (; i < values.Length; i++)
						{
							array[i] = FormatArgument(values[i]);
						}
						break;
					}
				}
			}
			return string.Format(CultureInfo.InvariantCulture, _format, array ?? Array.Empty<object>());
		}

		internal string FormatWithOverwrite(object?[]? values)
		{
			if (values != null)
			{
				for (int i = 0; i < values.Length; i++)
				{
					values[i] = FormatArgument(values[i]);
				}
			}
			return string.Format(CultureInfo.InvariantCulture, _format, values ?? Array.Empty<object>());
		}

		internal string Format()
		{
			return _format;
		}

		internal string Format(object? arg0)
		{
			return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0));
		}

		internal string Format(object? arg0, object? arg1)
		{
			return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1));
		}

		internal string Format(object? arg0, object? arg1, object? arg2)
		{
			return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1), FormatArgument(arg2));
		}

		public KeyValuePair<string, object?> GetValue(object?[] values, int index)
		{
			if (index < 0 || index > _valueNames.Count)
			{
				throw new IndexOutOfRangeException("index");
			}
			if (_valueNames.Count > index)
			{
				return new KeyValuePair<string, object>(_valueNames[index], values[index]);
			}
			return new KeyValuePair<string, object>("{OriginalFormat}", OriginalFormat);
		}

		public IEnumerable<KeyValuePair<string, object?>> GetValues(object[] values)
		{
			KeyValuePair<string, object>[] array = new KeyValuePair<string, object>[values.Length + 1];
			for (int i = 0; i != _valueNames.Count; i++)
			{
				array[i] = new KeyValuePair<string, object>(_valueNames[i], values[i]);
			}
			array[^1] = new KeyValuePair<string, object>("{OriginalFormat}", OriginalFormat);
			return array;
		}

		private static object FormatArgument(object value)
		{
			if (!TryFormatArgumentIfNullOrEnumerable(value, out var stringValue))
			{
				return value;
			}
			return stringValue;
		}

		private static bool TryFormatArgumentIfNullOrEnumerable<T>(T value, [NotNullWhen(true)] out object stringValue)
		{
			if (value == null)
			{
				stringValue = "(null)";
				return true;
			}
			if (!(value is string) && (object)value is IEnumerable enumerable)
			{
				Span<char> initialBuffer = stackalloc char[256];
				System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer);
				bool flag = true;
				foreach (object item in enumerable)
				{
					if (!flag)
					{
						valueStringBuilder.Append(", ");
					}
					valueStringBuilder.Append((item != null) ? item.ToString() : "(null)");
					flag = false;
				}
				stringValue = valueStringBuilder.ToString();
				return true;
			}
			stringValue = null;
			return false;
		}
	}
	internal sealed class NullExternalScopeProvider : IExternalScopeProvider
	{
		public static IExternalScopeProvider Instance { get; } = new NullExternalScopeProvider();


		private NullExternalScopeProvider()
		{
		}

		void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state)
		{
		}

		IDisposable IExternalScopeProvider.Push(object state)
		{
			return NullScope.Instance;
		}
	}
	internal sealed class NullScope : IDisposable
	{
		public static NullScope Instance { get; } = new NullScope();


		private NullScope()
		{
		}

		public void Dispose()
		{
		}
	}
	internal static class DebuggerDisplayFormatting
	{
		internal static string DebuggerToString(string name, ILogger logger)
		{
			LogLevel? logLevel = CalculateEnabledLogLevel(logger);
			string text = "Name = \"" + name + "\"";
			if (logLevel.HasValue)
			{
				return text + $", MinLevel = {logLevel}";
			}
			return text + ", Enabled = false";
		}

		internal static LogLevel? CalculateEnabledLogLevel(ILogger logger)
		{
			object obj = global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6;
			if (obj == null)
			{
				obj = new int[6] { 5, 4, 3, 2, 1, 0 };
				global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6 = (int[])obj;
			}
			ReadOnlySpan<LogLevel> readOnlySpan = new ReadOnlySpan<LogLevel>((LogLevel[]?)obj);
			LogLevel? result = null;
			ReadOnlySpan<LogLevel> readOnlySpan2 = readOnlySpan;
			for (int i = 0; i < readOnlySpan2.Length; i++)
			{
				LogLevel logLevel = readOnlySpan2[i];
				if (!logger.IsEnabled(logLevel))
				{
					break;
				}
				result = logLevel;
			}
			return result;
		}
	}
}
namespace Microsoft.Extensions.Logging.Abstractions
{
	public abstract class BufferedLogRecord
	{
		public abstract DateTimeOffset Timestamp { get; }

		public abstract LogLevel LogLevel { get; }

		public abstract EventId EventId { get; }

		public virtual string? Exception => null;

		public virtual ActivitySpanId? ActivitySpanId => null;

		public virtual ActivityTraceId? ActivityTraceId => null;

		public virtual int? ManagedThreadId => null;

		public virtual string? FormattedMessage => null;

		public virtual string? MessageTemplate => null;

		public virtual IReadOnlyList<KeyValuePair<string, object?>> Attributes => Array.Empty<KeyValuePair<string, object>>();
	}
	public interface IBufferedLogger
	{
		void LogRecords(IEnumerable<BufferedLogRecord> records);
	}
	public readonly struct LogEntry<TState>
	{
		public LogLevel LogLevel { get; }

		public string Category { get; }

		public EventId EventId { get; }

		public TState State { get; }

		public Exception? Exception { get; }

		public Func<TState, Exception?, string> Formatter { get; }

		public LogEntry(LogLevel logLevel, string category, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
		{
			LogLevel = logLevel;
			Category = category;
			EventId = eventId;
			State = state;
			Exception = exception;
			Formatter = formatter;
		}
	}
	public class NullLogger : ILogger
	{
		public static NullLogger Instance { get; } = new NullLogger();


		private NullLogger()
		{
		}

		public IDisposable BeginScope<TState>(TState state) where TState : notnull
		{
			return NullScope.Instance;
		}

		public bool IsEnabled(LogLevel logLevel)
		{
			return false;
		}

		public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
		{
		}
	}
	public class NullLoggerFactory : ILoggerFactory, IDisposable
	{
		public static readonly NullLoggerFactory Instance = new NullLoggerFactory();

		public ILogger CreateLogger(string name)
		{
			return NullLogger.Instance;
		}

		public void AddProvider(ILoggerProvider provider)
		{
		}

		public void Dispose()
		{
		}
	}
	public class NullLoggerProvider : ILoggerProvider, IDisposable
	{
		public static NullLoggerProvider Instance { get; } = new NullLoggerProvider();


		private NullLoggerProvider()
		{
		}

		public ILogger CreateLogger(string categoryName)
		{
			return NullLogger.Instance;
		}

		public void Dispose()
		{
		}
	}
	public class NullLogger<T> : ILogger<T>, ILogger
	{
		public static readonly NullLogger<T> Instance = new NullLogger<T>();

		public IDisposable BeginScope<TState>(TState state) where TState : notnull
		{
			return NullScope.Instance;
		}

		public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
		{
		}

		public bool IsEnabled(LogLevel logLevel)
		{
			return false;
		}
	}
}

Microsoft.Extensions.Logging.Configuration.dll

Decompiled a month ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using FxResources.Microsoft.Extensions.Logging.Configuration;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Binder.SourceGeneration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Configuration")]
[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("Configuration support for Microsoft.Extensions.Logging.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Logging.Configuration")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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.Microsoft.Extensions.Logging.Configuration
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ValueNotSupported => GetResourceString("ValueNotSupported");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | 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,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[GeneratedCode("Microsoft.Extensions.Configuration.Binder.SourceGeneration", "9.0.11.2809")]
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
	internal sealed class <BindingExtensions_g>F5A74730A11B46356CAC8D4F541B60C195F0D8BC2FFD3FC35209B393D568ACAE1__InterceptsLocationAttribute : Attribute
	{
		public <BindingExtensions_g>F5A74730A11B46356CAC8D4F541B60C195F0D8BC2FFD3FC35209B393D568ACAE1__InterceptsLocationAttribute(int version, string data)
		{
		}
	}
}
namespace Microsoft.Extensions.Configuration.Binder.SourceGeneration
{
	[GeneratedCode("Microsoft.Extensions.Configuration.Binder.SourceGeneration", "9.0.11.2809")]
	internal static class <BindingExtensions_g>F5A74730A11B46356CAC8D4F541B60C195F0D8BC2FFD3FC35209B393D568ACAE1__BindingExtensions
	{
		[<BindingExtensions_g>F5A74730A11B46356CAC8D4F541B60C195F0D8BC2FFD3FC35209B393D568ACAE1__InterceptsLocation(1, "FM66QDmCnbMMfGYZCBd4NS0EAABMb2dnZXJGaWx0ZXJDb25maWd1cmVPcHRpb25zLmNz")]
		[return: NotNullIfNotNull("defaultValue")]
		public static T GetValue<T>(this IConfiguration configuration, string key, T defaultValue)
		{
			return (T)(configuration.GetValueCore(typeof(T), key) ?? ((object)defaultValue));
		}

		public static object GetValueCore(this IConfiguration configuration, Type type, string key)
		{
			if (configuration == null)
			{
				throw new ArgumentNullException("configuration");
			}
			IConfigurationSection section = configuration.GetSection(key);
			string value = section.Value;
			if (value == null)
			{
				return null;
			}
			if (type == typeof(bool))
			{
				return ParseBool(value, section.Path);
			}
			return null;
		}

		public static bool ParseBool(string value, string path)
		{
			try
			{
				return bool.Parse(value);
			}
			catch (Exception innerException)
			{
				throw new InvalidOperationException($"Failed to convert configuration value at '{path}' to type '{typeof(bool)}'.", innerException);
			}
		}
	}
}
namespace Microsoft.Extensions.Logging
{
	internal sealed class LoggerFilterConfigureOptions : IConfigureOptions<LoggerFilterOptions>
	{
		private const string LogLevelKey = "LogLevel";

		private const string DefaultCategory = "Default";

		private readonly IConfiguration _configuration;

		public LoggerFilterConfigureOptions(IConfiguration configuration)
		{
			_configuration = configuration;
		}

		public void Configure(LoggerFilterOptions options)
		{
			LoadDefaultConfigValues(options);
		}

		private void LoadDefaultConfigValues(LoggerFilterOptions options)
		{
			if (_configuration == null)
			{
				return;
			}
			options.CaptureScopes = _configuration.GetValue("CaptureScopes", options.CaptureScopes);
			foreach (IConfigurationSection child in _configuration.GetChildren())
			{
				if (child.Key.Equals("LogLevel", StringComparison.OrdinalIgnoreCase))
				{
					LoadRules(options, child, null);
					continue;
				}
				IConfigurationSection section = child.GetSection("LogLevel");
				if (section != null)
				{
					string key = child.Key;
					LoadRules(options, section, key);
				}
			}
		}

		private static void LoadRules(LoggerFilterOptions options, IConfigurationSection configurationSection, string logger)
		{
			foreach (KeyValuePair<string, string> item2 in configurationSection.AsEnumerable(makePathsRelative: true))
			{
				if (TryGetSwitch(item2.Value, out var level))
				{
					string text = item2.Key;
					if (text.Equals("Default", StringComparison.OrdinalIgnoreCase))
					{
						text = null;
					}
					LoggerFilterRule item = new LoggerFilterRule(logger, text, level, null);
					options.Rules.Add(item);
				}
			}
		}

		private static bool TryGetSwitch(string value, out LogLevel level)
		{
			if (string.IsNullOrEmpty(value))
			{
				level = LogLevel.None;
				return false;
			}
			if (Enum.TryParse<LogLevel>(value, ignoreCase: true, out level))
			{
				return true;
			}
			throw new InvalidOperationException(System.SR.Format(System.SR.ValueNotSupported, value));
		}
	}
	public static class LoggingBuilderExtensions
	{
		public static ILoggingBuilder AddConfiguration(this ILoggingBuilder builder, IConfiguration configuration)
		{
			builder.AddConfiguration();
			builder.Services.AddSingleton((IConfigureOptions<LoggerFilterOptions>)new LoggerFilterConfigureOptions(configuration));
			builder.Services.AddSingleton((IOptionsChangeTokenSource<LoggerFilterOptions>)new ConfigurationChangeTokenSource<LoggerFilterOptions>(configuration));
			builder.Services.AddSingleton(new LoggingConfiguration(configuration));
			return builder;
		}
	}
	internal static class ProviderAliasUtilities
	{
		private const string AliasAttributeTypeFullName = "Microsoft.Extensions.Logging.ProviderAliasAttribute";

		internal static string GetAlias(Type providerType)
		{
			IList<CustomAttributeData> customAttributes = CustomAttributeData.GetCustomAttributes(providerType);
			for (int i = 0; i < customAttributes.Count; i++)
			{
				CustomAttributeData customAttributeData = customAttributes[i];
				if (customAttributeData.AttributeType.FullName == "Microsoft.Extensions.Logging.ProviderAliasAttribute" && customAttributeData.ConstructorArguments.Count > 0)
				{
					return customAttributeData.ConstructorArguments[0].Value?.ToString();
				}
			}
			return null;
		}
	}
}
namespace Microsoft.Extensions.Logging.Configuration
{
	public interface ILoggerProviderConfiguration<T>
	{
		IConfiguration Configuration { get; }
	}
	public interface ILoggerProviderConfigurationFactory
	{
		IConfiguration GetConfiguration(Type providerType);
	}
	internal sealed class LoggerProviderConfiguration<T> : ILoggerProviderConfiguration<T>
	{
		public IConfiguration Configuration { get; }

		public LoggerProviderConfiguration(ILoggerProviderConfigurationFactory providerConfigurationFactory)
		{
			Configuration = providerConfigurationFactory.GetConfiguration(typeof(T));
		}
	}
	public static class LoggerProviderOptions
	{
		internal const string RequiresDynamicCodeMessage = "Binding TOptions to configuration values may require generating dynamic code at runtime.";

		internal const string TrimmingRequiresUnreferencedCodeMessage = "TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.";

		[RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static void RegisterProviderOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions, TProvider>(IServiceCollection services) where TOptions : class
		{
			services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<TOptions>, LoggerProviderConfigureOptions<TOptions, TProvider>>());
			services.TryAddEnumerable(ServiceDescriptor.Singleton<IOptionsChangeTokenSource<TOptions>, LoggerProviderOptionsChangeTokenSource<TOptions, TProvider>>());
		}
	}
	internal sealed class LoggerProviderConfigurationFactory : ILoggerProviderConfigurationFactory
	{
		private readonly IEnumerable<LoggingConfiguration> _configurations;

		public LoggerProviderConfigurationFactory(IEnumerable<LoggingConfiguration> configurations)
		{
			_configurations = configurations;
		}

		public IConfiguration GetConfiguration(Type providerType)
		{
			System.ThrowHelper.ThrowIfNull(providerType, "providerType");
			string fullName = providerType.FullName;
			string alias = Microsoft.Extensions.Logging.ProviderAliasUtilities.GetAlias(providerType);
			ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
			foreach (LoggingConfiguration configuration in _configurations)
			{
				IConfigurationSection section = configuration.Configuration.GetSection(fullName);
				configurationBuilder.AddConfiguration(section);
				if (!string.IsNullOrWhiteSpace(alias))
				{
					IConfigurationSection section2 = configuration.Configuration.GetSection(alias);
					configurationBuilder.AddConfiguration(section2);
				}
			}
			return configurationBuilder.Build();
		}
	}
	internal sealed class LoggerProviderConfigureOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions, TProvider> : ConfigureFromConfigurationOptions<TOptions> where TOptions : class
	{
		[RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public LoggerProviderConfigureOptions(ILoggerProviderConfiguration<TProvider> providerConfiguration)
			: base(providerConfiguration.Configuration)
		{
		}
	}
	public class LoggerProviderOptionsChangeTokenSource<TOptions, TProvider> : ConfigurationChangeTokenSource<TOptions>
	{
		public LoggerProviderOptionsChangeTokenSource(ILoggerProviderConfiguration<TProvider> providerConfiguration)
			: base(providerConfiguration.Configuration)
		{
		}
	}
	public static class LoggingBuilderConfigurationExtensions
	{
		public static void AddConfiguration(this ILoggingBuilder builder)
		{
			builder.Services.TryAddSingleton<ILoggerProviderConfigurationFactory, LoggerProviderConfigurationFactory>();
			builder.Services.TryAddSingleton(typeof(ILoggerProviderConfiguration<>), typeof(LoggerProviderConfiguration<>));
		}
	}
	internal sealed class LoggingConfiguration
	{
		public IConfiguration Configuration { get; }

		public LoggingConfiguration(IConfiguration configuration)
		{
			Configuration = configuration;
		}
	}
}

Microsoft.Extensions.Logging.Console.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.CodeDom.Compiler;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Pipelines;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using FxResources.Microsoft.Extensions.Logging.Console;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Binder.SourceGeneration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Console.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Console")]
[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("Console logger provider implementation for Microsoft.Extensions.Logging.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Logging.Console")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[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;
		}
	}
}
internal static class Interop
{
	internal static class Libraries
	{
		internal const string Activeds = "activeds.dll";

		internal const string Advapi32 = "advapi32.dll";

		internal const string Authz = "authz.dll";

		internal const string BCrypt = "BCrypt.dll";

		internal const string Credui = "credui.dll";

		internal const string Crypt32 = "crypt32.dll";

		internal const string CryptUI = "cryptui.dll";

		internal const string Dsrole = "dsrole.dll";

		internal const string Gdi32 = "gdi32.dll";

		internal const string HttpApi = "httpapi.dll";

		internal const string IpHlpApi = "iphlpapi.dll";

		internal const string Kernel32 = "kernel32.dll";

		internal const string Logoncli = "logoncli.dll";

		internal const string Mswsock = "mswsock.dll";

		internal const string NCrypt = "ncrypt.dll";

		internal const string Netapi32 = "netapi32.dll";

		internal const string Netutils = "netutils.dll";

		internal const string NtDll = "ntdll.dll";

		internal const string Odbc32 = "odbc32.dll";

		internal const string Ole32 = "ole32.dll";

		internal const string OleAut32 = "oleaut32.dll";

		internal const string Pdh = "pdh.dll";

		internal const string Secur32 = "secur32.dll";

		internal const string Shell32 = "shell32.dll";

		internal const string SspiCli = "sspicli.dll";

		internal const string User32 = "user32.dll";

		internal const string Version = "version.dll";

		internal const string WebSocket = "websocket.dll";

		internal const string Wevtapi = "wevtapi.dll";

		internal const string WinHttp = "winhttp.dll";

		internal const string WinMM = "winmm.dll";

		internal const string Wkscli = "wkscli.dll";

		internal const string Wldap32 = "wldap32.dll";

		internal const string Ws2_32 = "ws2_32.dll";

		internal const string Wtsapi32 = "wtsapi32.dll";

		internal const string CompressionNative = "System.IO.Compression.Native";

		internal const string GlobalizationNative = "System.Globalization.Native";

		internal const string MsQuic = "msquic.dll";

		internal const string HostPolicy = "hostpolicy";

		internal const string Ucrtbase = "ucrtbase.dll";

		internal const string Xolehlp = "xolehlp.dll";

		internal const string Comdlg32 = "comdlg32.dll";

		internal const string Gdiplus = "gdiplus.dll";

		internal const string Oleaut32 = "oleaut32.dll";

		internal const string Winspool = "winspool.drv";
	}

	internal static class Kernel32
	{
		internal const int ENABLE_PROCESSED_INPUT = 1;

		internal const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4u;

		internal const int STD_OUTPUT_HANDLE = -11;

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		[LibraryImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool GetConsoleMode(IntPtr handle, out int mode);

		internal static bool IsGetConsoleModeCallSuccessful(IntPtr handle)
		{
			int mode;
			return GetConsoleMode(handle, out mode);
		}

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		[LibraryImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool SetConsoleMode(IntPtr handle, int mode);

		[DllImport("kernel32.dll", ExactSpelling = true)]
		[LibraryImport("kernel32.dll")]
		internal static extern IntPtr GetStdHandle(int nStdHandle);
	}
}
namespace FxResources.Microsoft.Extensions.Logging.Console
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
	internal static class ConsoleUtils
	{
		private static volatile int s_emitAnsiColorCodes = -1;

		public static bool EmitAnsiColorCodes
		{
			get
			{
				int num = s_emitAnsiColorCodes;
				if (num != -1)
				{
					return Convert.ToBoolean(num);
				}
				bool flag;
				if (!Console.IsOutputRedirected)
				{
					flag = Environment.GetEnvironmentVariable("NO_COLOR") == null;
				}
				else
				{
					string environmentVariable = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_CONSOLE_ALLOW_ANSI_COLOR_REDIRECTION");
					flag = environmentVariable != null && (environmentVariable == "1" || environmentVariable.Equals("true", StringComparison.OrdinalIgnoreCase));
				}
				s_emitAnsiColorCodes = Convert.ToInt32(flag);
				return flag;
			}
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded");

		internal static string QueueModeNotSupported => GetResourceString("QueueModeNotSupported");

		internal static string MaxQueueLengthBadValue => GetResourceString("MaxQueueLengthBadValue");

		internal static string WarningMessageOnDrop => GetResourceString("WarningMessageOnDrop");

		internal static string InvalidConfigurationData => GetResourceString("InvalidConfigurationData");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | 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,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class DynamicDependencyAttribute : Attribute
	{
		public string? MemberSignature { get; }

		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public Type? Type { get; }

		public string? TypeName { get; }

		public string? AssemblyName { get; }

		public string? Condition { get; set; }

		public DynamicDependencyAttribute(string memberSignature)
		{
			MemberSignature = memberSignature;
		}

		public DynamicDependencyAttribute(string memberSignature, Type type)
		{
			MemberSignature = memberSignature;
			Type = type;
		}

		public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName)
		{
			MemberSignature = memberSignature;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type)
		{
			MemberTypes = memberTypes;
			Type = type;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName)
		{
			MemberTypes = memberTypes;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class StringSyntaxAttribute : Attribute
	{
		public const string CompositeFormat = "CompositeFormat";

		public const string DateOnlyFormat = "DateOnlyFormat";

		public const string DateTimeFormat = "DateTimeFormat";

		public const string EnumFormat = "EnumFormat";

		public const string GuidFormat = "GuidFormat";

		public const string Json = "Json";

		public const string NumericFormat = "NumericFormat";

		public const string Regex = "Regex";

		public const string TimeOnlyFormat = "TimeOnlyFormat";

		public const string TimeSpanFormat = "TimeSpanFormat";

		public const string Uri = "Uri";

		public const string Xml = "Xml";

		public string Syntax { get; }

		public object?[] Arguments { get; }

		public StringSyntaxAttribute(string syntax)
		{
			Syntax = syntax;
			Arguments = Array.Empty<object>();
		}

		public StringSyntaxAttribute(string syntax, params object?[] arguments)
		{
			Syntax = syntax;
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[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.Versioning
{
	internal abstract class OSPlatformAttribute : Attribute
	{
		public string PlatformName { get; }

		private protected OSPlatformAttribute(string platformName)
		{
			PlatformName = platformName;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
	internal sealed class TargetPlatformAttribute : OSPlatformAttribute
	{
		public TargetPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public string? Message { get; }

		public UnsupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}

		public UnsupportedOSPlatformAttribute(string platformName, string? message)
			: base(platformName)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute
	{
		public string? Message { get; }

		public string? Url { get; set; }

		public ObsoletedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}

		public ObsoletedOSPlatformAttribute(string platformName, string? message)
			: base(platformName)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public UnsupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
}
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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[GeneratedCode("Microsoft.Extensions.Configuration.Binder.SourceGeneration", "9.0.11.2809")]
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
	internal sealed class <BindingExtensions_g>F2B4A495A0A2C714DBF690FC6A4076D3C1BCEB61CE646DEB898D8270EF32B0DBB__InterceptsLocationAttribute : Attribute
	{
		public <BindingExtensions_g>F2B4A495A0A2C714DBF690FC6A4076D3C1BCEB61CE646DEB898D8270EF32B0DBB__InterceptsLocationAttribute(int version, string data)
		{
		}
	}
}
namespace System.Text.Json
{
	internal sealed class PooledByteBufferWriter : PipeWriter, IDisposable
	{
		private byte[] _rentedBuffer;

		private int _index;

		private readonly Stream _stream;

		private const int MinimumBufferSize = 256;

		public const int MaximumBufferSize = 2147483591;

		public ReadOnlyMemory<byte> WrittenMemory => _rentedBuffer.AsMemory(0, _index);

		public int WrittenCount => _index;

		public int Capacity => _rentedBuffer.Length;

		public int FreeCapacity => _rentedBuffer.Length - _index;

		public override bool CanGetUnflushedBytes => true;

		public override long UnflushedBytes => _index;

		private PooledByteBufferWriter()
		{
		}

		public PooledByteBufferWriter(int initialCapacity)
			: this()
		{
			_rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity);
			_index = 0;
		}

		public PooledByteBufferWriter(int initialCapacity, Stream stream)
			: this(initialCapacity)
		{
			_stream = stream;
		}

		public void Clear()
		{
			ClearHelper();
		}

		public void ClearAndReturnBuffers()
		{
			ClearHelper();
			byte[] rentedBuffer = _rentedBuffer;
			_rentedBuffer = null;
			ArrayPool<byte>.Shared.Return(rentedBuffer);
		}

		private void ClearHelper()
		{
			_rentedBuffer.AsSpan(0, _index).Clear();
			_index = 0;
		}

		public void Dispose()
		{
			if (_rentedBuffer != null)
			{
				ClearHelper();
				byte[] rentedBuffer = _rentedBuffer;
				_rentedBuffer = null;
				ArrayPool<byte>.Shared.Return(rentedBuffer);
			}
		}

		public void InitializeEmptyInstance(int initialCapacity)
		{
			_rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity);
			_index = 0;
		}

		public static System.Text.Json.PooledByteBufferWriter CreateEmptyInstanceForCaching()
		{
			return new System.Text.Json.PooledByteBufferWriter();
		}

		public override void Advance(int count)
		{
			_index += count;
		}

		public override Memory<byte> GetMemory(int sizeHint = 256)
		{
			CheckAndResizeBuffer(sizeHint);
			return _rentedBuffer.AsMemory(_index);
		}

		public override Span<byte> GetSpan(int sizeHint = 256)
		{
			CheckAndResizeBuffer(sizeHint);
			return _rentedBuffer.AsSpan(_index);
		}

		internal void WriteToStream(Stream destination)
		{
			destination.Write(_rentedBuffer, 0, _index);
		}

		private void CheckAndResizeBuffer(int sizeHint)
		{
			int num = _rentedBuffer.Length;
			int num2 = num - _index;
			if (_index >= 1073741795)
			{
				sizeHint = Math.Max(sizeHint, 2147483591 - num);
			}
			if (sizeHint <= num2)
			{
				return;
			}
			int num3 = Math.Max(sizeHint, num);
			int num4 = num + num3;
			if ((uint)num4 > 2147483591u)
			{
				num4 = num + sizeHint;
				if ((uint)num4 > 2147483591u)
				{
					System.Text.Json.ThrowHelper.ThrowOutOfMemoryException_BufferMaximumSizeExceeded((uint)num4);
				}
			}
			byte[] rentedBuffer = _rentedBuffer;
			_rentedBuffer = ArrayPool<byte>.Shared.Rent(num4);
			Span<byte> span = rentedBuffer.AsSpan(0, _index);
			span.CopyTo(_rentedBuffer);
			span.Clear();
			ArrayPool<byte>.Shared.Return(rentedBuffer);
		}

		public override async ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			await _stream.WriteAsync(_rentedBuffer, 0, _index, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			Clear();
			return new FlushResult(isCanceled: false, isCompleted: false);
		}

		public override void CancelPendingFlush()
		{
			throw new NotImplementedException();
		}

		public override void Complete(Exception? exception = null)
		{
			throw new NotImplementedException();
		}
	}
	internal static class ThrowHelper
	{
		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowOutOfMemoryException_BufferMaximumSizeExceeded(uint capacity)
		{
			throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity));
		}
	}
}
namespace Microsoft.Extensions.Configuration.Binder.SourceGeneration
{
	[GeneratedCode("Microsoft.Extensions.Configuration.Binder.SourceGeneration", "9.0.11.2809")]
	internal static class <BindingExtensions_g>F2B4A495A0A2C714DBF690FC6A4076D3C1BCEB61CE646DEB898D8270EF32B0DBB__BindingExtensions
	{
		private static readonly Lazy<HashSet<string>> s_configKeys_ConsoleFormatterOptions = new Lazy<HashSet<string>>(() => new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "IncludeScopes", "TimestampFormat", "UseUtcTimestamp" });

		private static readonly Lazy<HashSet<string>> s_configKeys_ConsoleLoggerOptions = new Lazy<HashSet<string>>(() => new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "DisableColors", "Format", "FormatterName", "IncludeScopes", "LogToStandardErrorThreshold", "TimestampFormat", "UseUtcTimestamp", "QueueFullMode", "MaxQueueLength" });

		private static readonly Lazy<HashSet<string>> s_configKeys_JavaScriptEncoder = new Lazy<HashSet<string>>(() => new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Default", "UnsafeRelaxedJsonEscaping", "MaxOutputCharactersPerInputCharacter" });

		private static readonly Lazy<HashSet<string>> s_configKeys_JsonWriterOptions = new Lazy<HashSet<string>>(() => new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Encoder", "Indented", "IndentCharacter", "IndentSize", "MaxDepth", "SkipValidation", "NewLine" });

		private static readonly Lazy<HashSet<string>> s_configKeys_JsonConsoleFormatterOptions = new Lazy<HashSet<string>>(() => new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "JsonWriterOptions", "IncludeScopes", "TimestampFormat", "UseUtcTimestamp" });

		private static readonly Lazy<HashSet<string>> s_configKeys_SimpleConsoleFormatterOptions = new Lazy<HashSet<string>>(() => new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "ColorBehavior", "SingleLine", "IncludeScopes", "TimestampFormat", "UseUtcTimestamp" });

		[<BindingExtensions_g>F2B4A495A0A2C714DBF690FC6A4076D3C1BCEB61CE646DEB898D8270EF32B0DBB__InterceptsLocation(1, "YjSh8kLDx9Cx7IeuH14SzXoGAABDb25zb2xlRm9ybWF0dGVyT3B0aW9ucy5jcw==")]
		public static void Bind_ConsoleFormatterOptions(this IConfiguration configuration, object? instance)
		{
			if (configuration == null)
			{
				throw new ArgumentNullException("configuration");
			}
			if (instance != null)
			{
				ConsoleFormatterOptions instance2 = (ConsoleFormatterOptions)instance;
				BindCore(configuration, ref instance2, defaultValueIfNotFound: false, null);
			}
		}

		[<BindingExtensions_g>F2B4A495A0A2C714DBF690FC6A4076D3C1BCEB61CE646DEB898D8270EF32B0DBB__InterceptsLocation(1, "5QdjwXb/ESLTOXil2fXp3b0EAABDb25zb2xlTG9nZ2VyQ29uZmlndXJlT3B0aW9ucy5jcw==")]
		[<BindingExtensions_g>F2B4A495A0A2C714DBF690FC6A4076D3C1BCEB61CE646DEB898D8270EF32B0DBB__InterceptsLocation(1, "nPSYZ7dN0nAkILmhCV1YjtAgAABDb25zb2xlTG9nZ2VyRXh0ZW5zaW9ucy5PYnNvbGV0ZS5jcw==")]
		public static void Bind_ConsoleLoggerOptions(this IConfiguration configuration, object? instance)
		{
			if (configuration == null)
			{
				throw new ArgumentNullException("configuration");
			}
			if (instance != null)
			{
				ConsoleLoggerOptions instance2 = (ConsoleLoggerOptions)instance;
				BindCore(configuration, ref instance2, defaultValueIfNotFound: false, null);
			}
		}

		[<BindingExtensions_g>F2B4A495A0A2C714DBF690FC6A4076D3C1BCEB61CE646DEB898D8270EF32B0DBB__InterceptsLocation(1, "j/5I4/WUMca9STDi26uP1L0DAABKc29uQ29uc29sZUZvcm1hdHRlck9wdGlvbnMuY3M=")]
		public static void Bind_JsonConsoleFormatterOptions(this IConfiguration configuration, object? instance)
		{
			if (configuration == null)
			{
				throw new ArgumentNullException("configuration");
			}
			if (instance != null)
			{
				JsonConsoleFormatterOptions instance2 = (JsonConsoleFormatterOptions)instance;
				BindCore(configuration, ref instance2, defaultValueIfNotFound: false, null);
			}
		}

		[<BindingExtensions_g>F2B4A495A0A2C714DBF690FC6A4076D3C1BCEB61CE646DEB898D8270EF32B0DBB__InterceptsLocation(1, "Ag2VaMwE/s6d73BnEcgOJt4EAABTaW1wbGVDb25zb2xlRm9ybWF0dGVyT3B0aW9ucy5jcw==")]
		public static void Bind_SimpleConsoleFormatterOptions(this IConfiguration configuration, object? instance)
		{
			if (configuration == null)
			{
				throw new ArgumentNullException("configuration");
			}
			if (instance != null)
			{
				SimpleConsoleFormatterOptions instance2 = (SimpleConsoleFormatterOptions)instance;
				BindCore(configuration, ref instance2, defaultValueIfNotFound: false, null);
			}
		}

		public static void BindCore(IConfiguration configuration, ref ConsoleFormatterOptions instance, bool defaultValueIfNotFound, BinderOptions? binderOptions)
		{
			ValidateConfigurationKeys(typeof(ConsoleFormatterOptions), s_configKeys_ConsoleFormatterOptions, configuration, binderOptions);
			string text = configuration["IncludeScopes"];
			if (text != null && !string.IsNullOrEmpty(text))
			{
				instance.IncludeScopes = ParseBool(text, configuration.GetSection("IncludeScopes").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.IncludeScopes = instance.IncludeScopes;
			}
			string text2 = configuration["TimestampFormat"];
			if (text2 != null)
			{
				instance.TimestampFormat = text2;
			}
			else if (defaultValueIfNotFound)
			{
				string timestampFormat = instance.TimestampFormat;
				if (timestampFormat != null)
				{
					instance.TimestampFormat = timestampFormat;
				}
			}
			string text3 = configuration["UseUtcTimestamp"];
			if (text3 != null && !string.IsNullOrEmpty(text3))
			{
				instance.UseUtcTimestamp = ParseBool(text3, configuration.GetSection("UseUtcTimestamp").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.UseUtcTimestamp = instance.UseUtcTimestamp;
			}
		}

		public static void BindCore(IConfiguration configuration, ref ConsoleLoggerOptions instance, bool defaultValueIfNotFound, BinderOptions? binderOptions)
		{
			ValidateConfigurationKeys(typeof(ConsoleLoggerOptions), s_configKeys_ConsoleLoggerOptions, configuration, binderOptions);
			string text = configuration["DisableColors"];
			if (text != null && !string.IsNullOrEmpty(text))
			{
				instance.DisableColors = ParseBool(text, configuration.GetSection("DisableColors").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.DisableColors = instance.DisableColors;
			}
			string text2 = configuration["Format"];
			if (text2 != null && !string.IsNullOrEmpty(text2))
			{
				instance.Format = ParseEnum<ConsoleLoggerFormat>(text2, configuration.GetSection("Format").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.Format = instance.Format;
			}
			string text3 = configuration["FormatterName"];
			if (text3 != null)
			{
				instance.FormatterName = text3;
			}
			else if (defaultValueIfNotFound)
			{
				string formatterName = instance.FormatterName;
				if (formatterName != null)
				{
					instance.FormatterName = formatterName;
				}
			}
			string text4 = configuration["IncludeScopes"];
			if (text4 != null && !string.IsNullOrEmpty(text4))
			{
				instance.IncludeScopes = ParseBool(text4, configuration.GetSection("IncludeScopes").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.IncludeScopes = instance.IncludeScopes;
			}
			string text5 = configuration["LogToStandardErrorThreshold"];
			if (text5 != null && !string.IsNullOrEmpty(text5))
			{
				instance.LogToStandardErrorThreshold = ParseEnum<LogLevel>(text5, configuration.GetSection("LogToStandardErrorThreshold").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.LogToStandardErrorThreshold = instance.LogToStandardErrorThreshold;
			}
			string text6 = configuration["TimestampFormat"];
			if (text6 != null)
			{
				instance.TimestampFormat = text6;
			}
			else if (defaultValueIfNotFound)
			{
				string timestampFormat = instance.TimestampFormat;
				if (timestampFormat != null)
				{
					instance.TimestampFormat = timestampFormat;
				}
			}
			string text7 = configuration["UseUtcTimestamp"];
			if (text7 != null && !string.IsNullOrEmpty(text7))
			{
				instance.UseUtcTimestamp = ParseBool(text7, configuration.GetSection("UseUtcTimestamp").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.UseUtcTimestamp = instance.UseUtcTimestamp;
			}
			string text8 = configuration["QueueFullMode"];
			if (text8 != null && !string.IsNullOrEmpty(text8))
			{
				instance.QueueFullMode = ParseEnum<ConsoleLoggerQueueFullMode>(text8, configuration.GetSection("QueueFullMode").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.QueueFullMode = instance.QueueFullMode;
			}
			string text9 = configuration["MaxQueueLength"];
			if (text9 != null && !string.IsNullOrEmpty(text9))
			{
				instance.MaxQueueLength = ParseInt(text9, configuration.GetSection("MaxQueueLength").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.MaxQueueLength = instance.MaxQueueLength;
			}
		}

		public static void BindCore(IConfiguration configuration, ref JavaScriptEncoder instance, bool defaultValueIfNotFound, BinderOptions? binderOptions)
		{
			ValidateConfigurationKeys(typeof(JavaScriptEncoder), s_configKeys_JavaScriptEncoder, configuration, binderOptions);
			if (AsConfigWithChildren(configuration.GetSection("Default")) is IConfigurationSection configuration2)
			{
				JavaScriptEncoder instance2 = JavaScriptEncoder.Default;
				if (instance2 == null)
				{
					throw new InvalidOperationException("Cannot create instance of type 'System.Text.Encodings.Web.JavaScriptEncoder' because it is missing a public instance constructor.");
				}
				BindCore(configuration2, ref instance2, defaultValueIfNotFound: false, binderOptions);
			}
			if (AsConfigWithChildren(configuration.GetSection("UnsafeRelaxedJsonEscaping")) is IConfigurationSection configuration3)
			{
				JavaScriptEncoder instance3 = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
				if (instance3 == null)
				{
					throw new InvalidOperationException("Cannot create instance of type 'System.Text.Encodings.Web.JavaScriptEncoder' because it is missing a public instance constructor.");
				}
				BindCore(configuration3, ref instance3, defaultValueIfNotFound: false, binderOptions);
			}
		}

		public static void BindCore(IConfiguration configuration, ref JsonWriterOptions instance, bool defaultValueIfNotFound, BinderOptions? binderOptions)
		{
			ValidateConfigurationKeys(typeof(JsonWriterOptions), s_configKeys_JsonWriterOptions, configuration, binderOptions);
			if (AsConfigWithChildren(configuration.GetSection("Encoder")) is IConfigurationSection configuration2)
			{
				JavaScriptEncoder instance2 = instance.Encoder;
				if (instance2 == null)
				{
					throw new InvalidOperationException("Cannot create instance of type 'System.Text.Encodings.Web.JavaScriptEncoder' because it is missing a public instance constructor.");
				}
				BindCore(configuration2, ref instance2, defaultValueIfNotFound: false, binderOptions);
				instance.Encoder = instance2;
			}
			string text = configuration["Indented"];
			if (text != null && !string.IsNullOrEmpty(text))
			{
				instance.Indented = ParseBool(text, configuration.GetSection("Indented").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.Indented = instance.Indented;
			}
			string text2 = configuration["IndentCharacter"];
			if (text2 != null && !string.IsNullOrEmpty(text2))
			{
				instance.IndentCharacter = ParseChar(text2, configuration.GetSection("IndentCharacter").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.IndentCharacter = instance.IndentCharacter;
			}
			string text3 = configuration["IndentSize"];
			if (text3 != null && !string.IsNullOrEmpty(text3))
			{
				instance.IndentSize = ParseInt(text3, configuration.GetSection("IndentSize").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.IndentSize = instance.IndentSize;
			}
			string text4 = configuration["MaxDepth"];
			if (text4 != null && !string.IsNullOrEmpty(text4))
			{
				instance.MaxDepth = ParseInt(text4, configuration.GetSection("MaxDepth").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.MaxDepth = instance.MaxDepth;
			}
			string text5 = configuration["SkipValidation"];
			if (text5 != null && !string.IsNullOrEmpty(text5))
			{
				instance.SkipValidation = ParseBool(text5, configuration.GetSection("SkipValidation").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.SkipValidation = instance.SkipValidation;
			}
			string text6 = configuration["NewLine"];
			if (text6 != null)
			{
				instance.NewLine = text6;
			}
			else if (defaultValueIfNotFound)
			{
				string newLine = instance.NewLine;
				if (newLine != null)
				{
					instance.NewLine = newLine;
				}
			}
		}

		public static void BindCore(IConfiguration configuration, ref JsonConsoleFormatterOptions instance, bool defaultValueIfNotFound, BinderOptions? binderOptions)
		{
			ValidateConfigurationKeys(typeof(JsonConsoleFormatterOptions), s_configKeys_JsonConsoleFormatterOptions, configuration, binderOptions);
			if (AsConfigWithChildren(configuration.GetSection("JsonWriterOptions")) is IConfigurationSection configuration2)
			{
				_ = instance.JsonWriterOptions;
				JsonWriterOptions instance2 = default(JsonWriterOptions);
				BindCore(configuration2, ref instance2, defaultValueIfNotFound: false, binderOptions);
				instance.JsonWriterOptions = instance2;
			}
			else
			{
				instance.JsonWriterOptions = instance.JsonWriterOptions;
			}
			string text = configuration["IncludeScopes"];
			if (text != null && !string.IsNullOrEmpty(text))
			{
				instance.IncludeScopes = ParseBool(text, configuration.GetSection("IncludeScopes").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.IncludeScopes = instance.IncludeScopes;
			}
			string text2 = configuration["TimestampFormat"];
			if (text2 != null)
			{
				instance.TimestampFormat = text2;
			}
			else if (defaultValueIfNotFound)
			{
				string timestampFormat = instance.TimestampFormat;
				if (timestampFormat != null)
				{
					instance.TimestampFormat = timestampFormat;
				}
			}
			string text3 = configuration["UseUtcTimestamp"];
			if (text3 != null && !string.IsNullOrEmpty(text3))
			{
				instance.UseUtcTimestamp = ParseBool(text3, configuration.GetSection("UseUtcTimestamp").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.UseUtcTimestamp = instance.UseUtcTimestamp;
			}
		}

		public static void BindCore(IConfiguration configuration, ref SimpleConsoleFormatterOptions instance, bool defaultValueIfNotFound, BinderOptions? binderOptions)
		{
			ValidateConfigurationKeys(typeof(SimpleConsoleFormatterOptions), s_configKeys_SimpleConsoleFormatterOptions, configuration, binderOptions);
			string text = configuration["ColorBehavior"];
			if (text != null && !string.IsNullOrEmpty(text))
			{
				instance.ColorBehavior = ParseEnum<LoggerColorBehavior>(text, configuration.GetSection("ColorBehavior").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.ColorBehavior = instance.ColorBehavior;
			}
			string text2 = configuration["SingleLine"];
			if (text2 != null && !string.IsNullOrEmpty(text2))
			{
				instance.SingleLine = ParseBool(text2, configuration.GetSection("SingleLine").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.SingleLine = instance.SingleLine;
			}
			string text3 = configuration["IncludeScopes"];
			if (text3 != null && !string.IsNullOrEmpty(text3))
			{
				instance.IncludeScopes = ParseBool(text3, configuration.GetSection("IncludeScopes").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.IncludeScopes = instance.IncludeScopes;
			}
			string text4 = configuration["TimestampFormat"];
			if (text4 != null)
			{
				instance.TimestampFormat = text4;
			}
			else if (defaultValueIfNotFound)
			{
				string timestampFormat = instance.TimestampFormat;
				if (timestampFormat != null)
				{
					instance.TimestampFormat = timestampFormat;
				}
			}
			string text5 = configuration["UseUtcTimestamp"];
			if (text5 != null && !string.IsNullOrEmpty(text5))
			{
				instance.UseUtcTimestamp = ParseBool(text5, configuration.GetSection("UseUtcTimestamp").Path);
			}
			else if (defaultValueIfNotFound)
			{
				instance.UseUtcTimestamp = instance.UseUtcTimestamp;
			}
		}

		public static void ValidateConfigurationKeys(Type type, Lazy<HashSet<string>> keys, IConfiguration configuration, BinderOptions? binderOptions)
		{
			if (!(binderOptions?.ErrorOnUnknownConfiguration ?? false))
			{
				return;
			}
			List<string> list = null;
			foreach (IConfigurationSection child in configuration.GetChildren())
			{
				if (!keys.Value.Contains(child.Key))
				{
					(list ?? (list = new List<string>())).Add("'" + child.Key + "'");
				}
			}
			if (list != null)
			{
				throw new InvalidOperationException(string.Format("'ErrorOnUnknownConfiguration' was set on the provided BinderOptions, but the following properties were not found on the instance of {0}: {1}", type, string.Join(", ", list)));
			}
		}

		public static IConfiguration? AsConfigWithChildren(IConfiguration configuration)
		{
			using (IEnumerator<IConfigurationSection> enumerator = configuration.GetChildren().GetEnumerator())
			{
				if (enumerator.MoveNext())
				{
					_ = enumerator.Current;
					return configuration;
				}
			}
			return null;
		}

		public static T ParseEnum<T>(string value, string? path) where T : struct
		{
			try
			{
				return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
			}
			catch (Exception innerException)
			{
				throw new InvalidOperationException($"Failed to convert configuration value at '{path}' to type '{typeof(T)}'.", innerException);
			}
		}

		public static bool ParseBool(string value, string? path)
		{
			try
			{
				return bool.Parse(value);
			}
			catch (Exception innerException)
			{
				throw new InvalidOperationException($"Failed to convert configuration value at '{path}' to type '{typeof(bool)}'.", innerException);
			}
		}

		public static int ParseInt(string value, string? path)
		{
			try
			{
				return int.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture);
			}
			catch (Exception innerException)
			{
				throw new InvalidOperationException($"Failed to convert configuration value at '{path}' to type '{typeof(int)}'.", innerException);
			}
		}

		public static char ParseChar(string value, string? path)
		{
			try
			{
				return char.Parse(value);
			}
			catch (Exception innerException)
			{
				throw new InvalidOperationException($"Failed to convert configuration value at '{path}' to type '{typeof(char)}'.", innerException);
			}
		}
	}
}
namespace Microsoft.Extensions.Logging
{
	internal sealed class ConsoleFormatterConfigureOptions : IConfigureOptions<ConsoleFormatterOptions>
	{
		private readonly IConfiguration _configuration;

		[UnsupportedOSPlatform("browser")]
		public ConsoleFormatterConfigureOptions(ILoggerProviderConfiguration<ConsoleLoggerProvider> providerConfiguration)
		{
			_configuration = providerConfiguration.GetFormatterOptionsSection();
		}

		public void Configure(ConsoleFormatterOptions options)
		{
			options.Configure(_configuration);
		}
	}
	internal sealed class ConsoleLoggerConfigureOptions : IConfigureOptions<ConsoleLoggerOptions>
	{
		private readonly IConfiguration _configuration;

		[UnsupportedOSPlatform("browser")]
		public ConsoleLoggerConfigureOptions(ILoggerProviderConfiguration<ConsoleLoggerProvider> providerConfiguration)
		{
			_configuration = providerConfiguration.Configuration;
		}

		public void Configure(ConsoleLoggerOptions options)
		{
			_configuration.Bind_ConsoleLoggerOptions(options);
		}
	}
	[UnsupportedOSPlatform("browser")]
	public static class ConsoleLoggerExtensions
	{
		[Obsolete]
		private sealed class ConsoleLoggerSettingsAdapter : IConfigureOptions<ConsoleLoggerOptions>, IOptionsChangeTokenSource<ConsoleLoggerOptions>
		{
			private IConsoleLoggerSettings _settings;

			string IOptionsChangeTokenSource<ConsoleLoggerOptions>.Name => Microsoft.Extensions.Options.Options.DefaultName;

			private ConsoleLoggerSettingsAdapter(IConsoleLoggerSettings settings)
			{
				_settings = settings;
			}

			IChangeToken IOptionsChangeTokenSource<ConsoleLoggerOptions>.GetChangeToken()
			{
				return _settings.ChangeToken ?? NullChangeToken.Instance;
			}

			void IConfigureOptions<ConsoleLoggerOptions>.Configure(ConsoleLoggerOptions options)
			{
				options.IncludeScopes = _settings.IncludeScopes;
				if (_settings is ConfigurationConsoleLoggerSettings configurationConsoleLoggerSettings)
				{
					configurationConsoleLoggerSettings._configuration.Bind_ConsoleLoggerOptions(options);
				}
				else if (_settings is ConsoleLoggerSettings consoleLoggerSettings)
				{
					options.DisableColors = consoleLoggerSettings.DisableColors;
				}
			}

			internal static OptionsMonitor<ConsoleLoggerOptions> GetOptionsMonitor(IConsoleLoggerSettings settings)
			{
				ConsoleLoggerSettingsAdapter consoleLoggerSettingsAdapter = new ConsoleLoggerSettingsAdapter(settings);
				OptionsFactory<ConsoleLoggerOptions> factory = new OptionsFactory<ConsoleLoggerOptions>(new IConfigureOptions<ConsoleLoggerOptions>[1] { consoleLoggerSettingsAdapter }, Array.Empty<IPostConfigureOptions<ConsoleLoggerOptions>>());
				IOptionsChangeTokenSource<ConsoleLoggerOptions>[] sources = new IOptionsChangeTokenSource<ConsoleLoggerOptions>[1] { consoleLoggerSettingsAdapter };
				OptionsCache<ConsoleLoggerOptions> cache = new OptionsCache<ConsoleLoggerOptions>();
				return new OptionsMonitor<ConsoleLoggerOptions>(factory, sources, cache);
			}
		}

		private sealed class NullChangeToken : IChangeToken, IDisposable
		{
			internal static NullChangeToken Instance { get; } = new NullChangeToken();


			public bool HasChanged => false;

			public bool ActiveChangeCallbacks => false;

			private NullChangeToken()
			{
			}

			public IDisposable RegisterChangeCallback(Action<object> callback, object state)
			{
				return this;
			}

			public void Dispose()
			{
			}
		}

		internal const string RequiresDynamicCodeMessage = "Binding TOptions to configuration values may require generating dynamic code at runtime.";

		internal const string TrimmingRequiresUnreferencedCodeMessage = "TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.";

		public static ILoggingBuilder AddConsole(this ILoggingBuilder builder)
		{
			LoggingBuilderConfigurationExtensions.AddConfiguration(builder);
			builder.AddConsoleFormatter<JsonConsoleFormatter, JsonConsoleFormatterOptions, ConsoleFormatterConfigureOptions>();
			builder.AddConsoleFormatter<SystemdConsoleFormatter, ConsoleFormatterOptions, ConsoleFormatterConfigureOptions>();
			builder.AddConsoleFormatter<SimpleConsoleFormatter, SimpleConsoleFormatterOptions, ConsoleFormatterConfigureOptions>();
			builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, ConsoleLoggerProvider>());
			builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<ConsoleLoggerOptions>, ConsoleLoggerConfigureOptions>());
			builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IOptionsChangeTokenSource<ConsoleLoggerOptions>, LoggerProviderOptionsChangeTokenSource<ConsoleLoggerOptions, ConsoleLoggerProvider>>());
			return builder;
		}

		public static ILoggingBuilder AddConsole(this ILoggingBuilder builder, Action<ConsoleLoggerOptions> configure)
		{
			System.ThrowHelper.ThrowIfNull(configure, "configure");
			builder.AddConsole();
			builder.Services.Configure(configure);
			return builder;
		}

		public static ILoggingBuilder AddSimpleConsole(this ILoggingBuilder builder)
		{
			return builder.AddFormatterWithName("simple");
		}

		public static ILoggingBuilder AddSimpleConsole(this ILoggingBuilder builder, Action<SimpleConsoleFormatterOptions> configure)
		{
			return builder.AddConsoleWithFormatter("simple", configure);
		}

		public static ILoggingBuilder AddJsonConsole(this ILoggingBuilder builder)
		{
			return builder.AddFormatterWithName("json");
		}

		public static ILoggingBuilder AddJsonConsole(this ILoggingBuilder builder, Action<JsonConsoleFormatterOptions> configure)
		{
			return builder.AddConsoleWithFormatter("json", configure);
		}

		public static ILoggingBuilder AddSystemdConsole(this ILoggingBuilder builder, Action<ConsoleFormatterOptions> configure)
		{
			return builder.AddConsoleWithFormatter("systemd", configure);
		}

		public static ILoggingBuilder AddSystemdConsole(this ILoggingBuilder builder)
		{
			return builder.AddFormatterWithName("systemd");
		}

		internal static ILoggingBuilder AddConsoleWithFormatter<TOptions>(this ILoggingBuilder builder, string name, Action<TOptions> configure) where TOptions : ConsoleFormatterOptions
		{
			System.ThrowHelper.ThrowIfNull(configure, "configure");
			builder.AddFormatterWithName(name);
			builder.Services.Configure(configure);
			return builder;
		}

		private static ILoggingBuilder AddFormatterWithName(this ILoggingBuilder builder, string name)
		{
			return builder.AddConsole(delegate(ConsoleLoggerOptions options)
			{
				options.FormatterName = name;
			});
		}

		[RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static ILoggingBuilder AddConsoleFormatter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TFormatter, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this ILoggingBuilder builder) where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions
		{
			return builder.AddConsoleFormatter<TFormatter, TOptions, ConsoleLoggerFormatterConfigureOptions<TFormatter, TOptions>>();
		}

		[RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static ILoggingBuilder AddConsoleFormatter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TFormatter, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this ILoggingBuilder builder, Action<TOptions> configure) where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions
		{
			System.ThrowHelper.ThrowIfNull(configure, "configure");
			builder.AddConsoleFormatter<TFormatter, TOptions>();
			builder.Services.Configure(configure);
			return builder;
		}

		private static ILoggingBuilder AddConsoleFormatter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TFormatter, TOptions, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TConfigureOptions>(this ILoggingBuilder builder) where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions where TConfigureOptions : class, IConfigureOptions<TOptions>
		{
			LoggingBuilderConfigurationExtensions.AddConfiguration(builder);
			builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ConsoleFormatter, TFormatter>());
			builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<TOptions>, TConfigureOptions>());
			builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IOptionsChangeTokenSource<TOptions>, ConsoleLoggerFormatterOptionsChangeTokenSource<TFormatter, TOptions>>());
			return builder;
		}

		internal static IConfiguration GetFormatterOptionsSection(this ILoggerProviderConfiguration<ConsoleLoggerProvider> providerConfiguration)
		{
			return providerConfiguration.Configuration.GetSection("FormatterOptions");
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		[Obsolete("This method is retained only for compatibility. The recommended alternative is AddConsole(this ILoggingBuilder builder).", true)]
		public static ILoggerFactory AddConsole(this ILoggerFactory factory, IConfiguration configuration)
		{
			ConfigurationConsoleLoggerSettings settings = new ConfigurationConsoleLoggerSettings(configuration);
			return factory.AddConsole(settings);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		[Obsolete("This method is retained only for compatibility. The recommended alternative is AddConsole(this ILoggingBuilder builder).", true)]
		public static ILoggerFactory AddConsole(this ILoggerFactory factory, IConsoleLoggerSettings settings)
		{
			factory.AddProvider(new ConsoleLoggerProvider(ConsoleLoggerSettingsAdapter.GetOptionsMonitor(settings)));
			return factory;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		[Obsolete("This method is retained only for compatibility. The recommended alternative is AddConsole(this ILoggingBuilder builder).", true)]
		public static ILoggerFactory AddConsole(this ILoggerFactory factory, LogLevel minLevel, bool includeScopes)
		{
			factory.AddConsole((string n, LogLevel l) => l >= LogLevel.Information, includeScopes);
			return factory;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		[Obsolete("This method is retained only for compatibility. The recommended alternative is AddConsole(this ILoggingBuilder builder).", true)]
		public static ILoggerFactory AddConsole(this ILoggerFactory factory, LogLevel minLevel)
		{
			factory.AddConsole(minLevel, includeScopes: false);
			return factory;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		[Obsolete("This method is retained only for compatibility. The recommended alternative is AddConsole(this ILoggingBuilder builder).", true)]
		public static ILoggerFactory AddConsole(this ILoggerFactory factory, bool includeScopes)
		{
			factory.AddConsole((string n, LogLevel l) => l >= LogLevel.Information, includeScopes);
			return factory;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		[Obsolete("This method is retained only for compatibility. The recommended alternative is AddConsole(this ILoggingBuilder builder).", true)]
		public static ILoggerFactory AddConsole(this ILoggerFactory factory, Func<string, LogLevel, bool> filter, bool includeScopes)
		{
			factory.AddConsole(new ConsoleLoggerSettings
			{
				IncludeScopes = includeScopes
			});
			return factory;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		[Obsolete("This method is retained only for compatibility. The recommended alternative is AddConsole(this ILoggingBuilder builder).", true)]
		public static ILoggerFactory AddConsole(this ILoggerFactory factory, Func<string, LogLevel, bool> filter)
		{
			factory.AddConsole(filter, includeScopes: false);
			return factory;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		[Obsolete("This method is retained only for compatibility. The recommended alternative is AddConsole(this ILoggingBuilder builder).", true)]
		public static ILoggerFactory AddConsole(this ILoggerFactory factory)
		{
			return factory.AddConsole(includeScopes: false);
		}
	}
	[UnsupportedOSPlatform("browser")]
	internal sealed class ConsoleLoggerFormatterConfigureOptions<TFormatter, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions> : ConfigureFromConfigurationOptions<TOptions> where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions
	{
		[RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public ConsoleLoggerFormatterConfigureOptions(ILoggerProviderConfiguration<ConsoleLoggerProvider> providerConfiguration)
			: base(providerConfiguration.GetFormatterOptionsSection())
		{
		}
	}
	[UnsupportedOSPlatform("browser")]
	internal sealed class ConsoleLoggerFormatterOptionsChangeTokenSource<TFormatter, TOptions> : ConfigurationChangeTokenSource<TOptions> where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions
	{
		public ConsoleLoggerFormatterOptionsChangeTokenSource(ILoggerProviderConfiguration<ConsoleLoggerProvider> providerConfiguration)
			: base(providerConfiguration.GetFormatterOptionsSection())
		{
		}
	}
	internal sealed class NullExternalScopeProvider : IExternalScopeProvider
	{
		public static IExternalScopeProvider Instance { get; } = new Microsoft.Extensions.Logging.NullExternalScopeProvider();


		private NullExternalScopeProvider()
		{
		}

		void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state)
		{
		}

		IDisposable IExternalScopeProvider.Push(object state)
		{
			return Microsoft.Extensions.Logging.NullScope.Instance;
		}
	}
	internal sealed class NullScope : IDisposable
	{
		public static Microsoft.Extensions.Logging.NullScope Instance { get; } = new Microsoft.Extensions.Logging.NullScope();


		private NullScope()
		{
		}

		public void Dispose()
		{
		}
	}
}
namespace Microsoft.Extensions.Logging.Console
{
	internal sealed class AnsiLogConsole : IConsole
	{
		private readonly TextWriter _textWriter;

		public AnsiLogConsole(bool stdErr = false)
		{
			_textWriter = (stdErr ? System.Console.Error : System.Console.Out);
		}

		public void Write(string message)
		{
			_textWriter.Write(message);
		}
	}
	internal sealed class AnsiParser
	{
		private readonly Action<string, int, int, ConsoleColor?, ConsoleColor?> _onParseWrite;

		internal const string DefaultForegroundColor = "\u001b[39m\u001b[22m";

		internal const string DefaultBackgroundColor = "\u001b[49m";

		public AnsiParser(Action<string, int, int, ConsoleColor?, ConsoleColor?> onParseWrite)
		{
			System.ThrowHelper.ThrowIfNull(onParseWrite, "onParseWrite");
			_onParseWrite = onParseWrite;
		}

		public void Parse(string message)
		{
			int num = -1;
			int arg = 0;
			ConsoleColor? arg2 = null;
			ConsoleColor? arg3 = null;
			ReadOnlySpan<char> readOnlySpan = message.AsSpan();
			ConsoleColor? color = null;
			bool isBright = false;
			int num2;
			for (num2 = 0; num2 < readOnlySpan.Length; num2++)
			{
				if (readOnlySpan[num2] == '\u001b' && readOnlySpan.Length >= num2 + 4 && readOnlySpan[num2 + 1] == '[')
				{
					if (readOnlySpan[num2 + 3] == 'm')
					{
						if (IsDigit(readOnlySpan[num2 + 2]))
						{
							int num3 = readOnlySpan[num2 + 2] - 48;
							if (num != -1)
							{
								_onParseWrite(message, num, arg, arg3, arg2);
								num = -1;
								arg = 0;
							}
							if (num3 == 1)
							{
								isBright = true;
							}
							num2 += 3;
							continue;
						}
					}
					else if (readOnlySpan.Length >= num2 + 5 && readOnlySpan[num2 + 4] == 'm' && IsDigit(readOnlySpan[num2 + 2]) && IsDigit(readOnlySpan[num2 + 3]))
					{
						int num3 = (readOnlySpan[num2 + 2] - 48) * 10 + (readOnlySpan[num2 + 3] - 48);
						if (num != -1)
						{
							_onParseWrite(message, num, arg, arg3, arg2);
							num = -1;
							arg = 0;
						}
						if (TryGetForegroundColor(num3, isBright, out color))
						{
							arg2 = color;
							isBright = false;
						}
						else if (TryGetBackgroundColor(num3, out color))
						{
							arg3 = color;
						}
						num2 += 4;
						continue;
					}
				}
				if (num == -1)
				{
					num = num2;
				}
				int num4 = -1;
				if (num2 < message.Length - 1)
				{
					num4 = message.IndexOf('\u001b', num2 + 1);
				}
				if (num4 < 0)
				{
					arg = message.Length - num;
					break;
				}
				arg = num4 - num;
				num2 = num4 - 1;
			}
			if (num != -1)
			{
				_onParseWrite(message, num, arg, arg3, arg2);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static bool IsDigit(char c)
		{
			return (uint)(c - 48) <= 9u;
		}

		internal static string GetForegroundColorEscapeCode(ConsoleColor color)
		{
			return color switch
			{
				ConsoleColor.Black => "\u001b[30m", 
				ConsoleColor.DarkRed => "\u001b[31m", 
				ConsoleColor.DarkGreen => "\u001b[32m", 
				ConsoleColor.DarkYellow => "\u001b[33m", 
				ConsoleColor.DarkBlue => "\u001b[34m", 
				ConsoleColor.DarkMagenta => "\u001b[35m", 
				ConsoleColor.DarkCyan => "\u001b[36m", 
				ConsoleColor.Gray => "\u001b[37m", 
				ConsoleColor.Red => "\u001b[1m\u001b[31m", 
				ConsoleColor.Green => "\u001b[1m\u001b[32m", 
				ConsoleColor.Yellow => "\u001b[1m\u001b[33m", 
				ConsoleColor.Blue => "\u001b[1m\u001b[34m", 
				ConsoleColor.Magenta => "\u001b[1m\u001b[35m", 
				ConsoleColor.Cyan => "\u001b[1m\u001b[36m", 
				ConsoleColor.White => "\u001b[1m\u001b[37m", 
				_ => "\u001b[39m\u001b[22m", 
			};
		}

		internal static string GetBackgroundColorEscapeCode(ConsoleColor color)
		{
			return color switch
			{
				ConsoleColor.Black => "\u001b[40m", 
				ConsoleColor.DarkRed => "\u001b[41m", 
				ConsoleColor.DarkGreen => "\u001b[42m", 
				ConsoleColor.DarkYellow => "\u001b[43m", 
				ConsoleColor.DarkBlue => "\u001b[44m", 
				ConsoleColor.DarkMagenta => "\u001b[45m", 
				ConsoleColor.DarkCyan => "\u001b[46m", 
				ConsoleColor.Gray => "\u001b[47m", 
				_ => "\u001b[49m", 
			};
		}

		private static bool TryGetForegroundColor(int number, bool isBright, out ConsoleColor? color)
		{
			color = number switch
			{
				30 => ConsoleColor.Black, 
				31 => isBright ? ConsoleColor.Red : ConsoleColor.DarkRed, 
				32 => isBright ? ConsoleColor.Green : ConsoleColor.DarkGreen, 
				33 => isBright ? ConsoleColor.Yellow : ConsoleColor.DarkYellow, 
				34 => (!isBright) ? ConsoleColor.DarkBlue : ConsoleColor.Blue, 
				35 => isBright ? ConsoleColor.Magenta : ConsoleColor.DarkMagenta, 
				36 => isBright ? ConsoleColor.Cyan : ConsoleColor.DarkCyan, 
				37 => isBright ? ConsoleColor.White : ConsoleColor.Gray, 
				_ => null, 
			};
			if (!color.HasValue)
			{
				return number == 39;
			}
			return true;
		}

		private static bool TryGetBackgroundColor(int number, out ConsoleColor? color)
		{
			color = number switch
			{
				40 => ConsoleColor.Black, 
				41 => ConsoleColor.DarkRed, 
				42 => ConsoleColor.DarkGreen, 
				43 => ConsoleColor.DarkYellow, 
				44 => ConsoleColor.DarkBlue, 
				45 => ConsoleColor.DarkMagenta, 
				46 => ConsoleColor.DarkCyan, 
				47 => ConsoleColor.Gray, 
				_ => null, 
			};
			if (!color.HasValue)
			{
				return number == 49;
			}
			return true;
		}
	}
	[UnsupportedOSPlatform("android")]
	[UnsupportedOSPlatform("browser")]
	[UnsupportedOSPlatform("ios")]
	[UnsupportedOSPlatform("tvos")]
	internal sealed class AnsiParsingLogConsole : IConsole
	{
		private readonly TextWriter _textWriter;

		private readonly AnsiParser _parser;

		public AnsiParsingLogConsole(bool stdErr = false)
		{
			_textWriter = (stdErr ? System.Console.Error : System.Console.Out);
			_parser = new AnsiParser(WriteToConsole);
		}

		public void Write(string message)
		{
			_parser.Parse(message);
		}

		private static bool SetColor(ConsoleColor? background, ConsoleColor? foreground)
		{
			bool flag = SetBackgroundColor(background);
			return SetForegroundColor(foreground) || flag;
		}

		private static bool SetBackgroundColor(ConsoleColor? background)
		{
			if (background.HasValue)
			{
				System.Console.BackgroundColor = background.Value;
				return true;
			}
			return false;
		}

		private static bool SetForegroundColor(ConsoleColor? foreground)
		{
			if (foreground.HasValue)
			{
				System.Console.ForegroundColor = foreground.Value;
				return true;
			}
			return false;
		}

		private static void ResetColor()
		{
			System.Console.ResetColor();
		}

		private void WriteToConsole(string message, int startIndex, int length, ConsoleColor? background, ConsoleColor? foreground)
		{
			ReadOnlySpan<char> readOnlySpan = message.AsSpan(startIndex, length);
			bool num = SetColor(background, foreground);
			_textWriter.Write(readOnlySpan.ToString());
			if (num)
			{
				ResetColor();
			}
		}
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	[Obsolete("This type is retained only for compatibility. The recommended alternative is ConsoleLoggerOptions.")]
	public class ConfigurationConsoleLoggerSettings : IConsoleLoggerSettings
	{
		internal readonly IConfiguration _configuration;

		public IChangeToken? ChangeToken { get; private set; }

		public bool IncludeScopes
		{
			get
			{
				string text = _configuration["IncludeScopes"];
				if (string.IsNullOrEmpty(text))
				{
					return false;
				}
				if (bool.TryParse(text, out var result))
				{
					return result;
				}
				throw new InvalidOperationException("Configuration value '" + text + "' for setting 'IncludeScopes' is not supported.");
			}
		}

		public ConfigurationConsoleLoggerSettings(IConfiguration configuration)
		{
			_configuration = configuration;
			ChangeToken = configuration.GetReloadToken();
		}

		public IConsoleLoggerSettings Reload()
		{
			ChangeToken = null;
			return new ConfigurationConsoleLoggerSettings(_configuration);
		}

		public bool TryGetSwitch(string name, out LogLevel level)
		{
			IConfigurationSection section = _configuration.GetSection("LogLevel");
			if (section == null)
			{
				level = LogLevel.None;
				return false;
			}
			string text = section[name];
			if (string.IsNullOrEmpty(text))
			{
				level = LogLevel.None;
				return false;
			}
			if (Enum.TryParse<LogLevel>(text, ignoreCase: true, out level))
			{
				return true;
			}
			throw new InvalidOperationException("Configuration value '" + text + "' for category '" + name + "' is not supported.");
		}
	}
	public abstract class ConsoleFormatter
	{
		public string Name { get; }

		protected ConsoleFormatter(string name)
		{
			System.ThrowHelper.ThrowIfNull(name, "name");
			Name = name;
		}

		public abstract void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter);
	}
	public static class ConsoleFormatterNames
	{
		public const string Simple = "simple";

		public const string Json = "json";

		public const string Systemd = "systemd";
	}
	public class ConsoleFormatterOptions
	{
		public bool IncludeScopes { get; set; }

		[StringSyntax("DateTimeFormat")]
		public string? TimestampFormat { get; set; }

		public bool UseUtcTimestamp { get; set; }

		internal virtual void Configure(IConfiguration configuration)
		{
			configuration.Bind_ConsoleFormatterOptions(this);
		}
	}
	[UnsupportedOSPlatform("browser")]
	internal sealed class ConsoleLogger : ILogger, IBufferedLogger
	{
		private readonly string _name;

		private readonly ConsoleLoggerProcessor _queueProcessor;

		[ThreadStatic]
		private static StringWriter t_stringWriter;

		internal ConsoleFormatter Formatter { get; set; }

		internal IExternalScopeProvider? ScopeProvider { get; set; }

		internal ConsoleLoggerOptions Options { get; set; }

		internal ConsoleLogger(string name, ConsoleLoggerProcessor loggerProcessor, ConsoleFormatter formatter, IExternalScopeProvider? scopeProvider, ConsoleLoggerOptions options)
		{
			System.ThrowHelper.ThrowIfNull(name, "name");
			_name = name;
			_queueProcessor = loggerProcessor;
			Formatter = formatter;
			ScopeProvider = scopeProvider;
			Options = options;
		}

		public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
		{
			if (!IsEnabled(logLevel))
			{
				return;
			}
			System.ThrowHelper.ThrowIfNull(formatter, "formatter");
			if (t_stringWriter == null)
			{
				t_stringWriter = new StringWriter();
			}
			LogEntry<TState> logEntry = new LogEntry<TState>(logLevel, _name, eventId, state, exception, formatter);
			Formatter.Write(in logEntry, ScopeProvider, t_stringWriter);
			StringBuilder stringBuilder = t_stringWriter.GetStringBuilder();
			if (stringBuilder.Length != 0)
			{
				string message = stringBuilder.ToString();
				stringBuilder.Clear();
				if (stringBuilder.Capacity > 1024)
				{
					stringBuilder.Capacity = 1024;
				}
				_queueProcessor.EnqueueMessage(new LogMessageEntry(message, logLevel >= Options.LogToStandardErrorThreshold));
			}
		}

		public void LogRecords(IEnumerable<BufferedLogRecord> records)
		{
			System.ThrowHelper.ThrowIfNull(records, "records");
			StringWriter stringWriter = t_stringWriter ?? (t_stringWriter = new StringWriter());
			StringBuilder stringBuilder = stringWriter.GetStringBuilder();
			foreach (BufferedLogRecord record in records)
			{
				LogEntry<BufferedLogRecord> logEntry = new LogEntry<BufferedLogRecord>(record.LogLevel, _name, record.EventId, record, null, (BufferedLogRecord s, Exception _) => s.FormattedMessage ?? string.Empty);
				Formatter.Write(in logEntry, null, stringWriter);
				if (stringBuilder.Length != 0)
				{
					string message = stringBuilder.ToString();
					stringBuilder.Clear();
					_queueProcessor.EnqueueMessage(new LogMessageEntry(message, record.LogLevel >= Options.LogToStandardErrorThreshold));
				}
			}
			if (stringBuilder.Capacity > 1024)
			{
				stringBuilder.Capacity = 1024;
			}
		}

		public bool IsEnabled(LogLevel logLevel)
		{
			return logLevel != LogLevel.None;
		}

		public IDisposable BeginScope<TState>(TState state) where TState : notnull
		{
			return ScopeProvider?.Push(state) ?? Microsoft.Extensions.Logging.NullScope.Instance;
		}
	}
	[Obsolete("ConsoleLoggerFormat has been deprecated.")]
	public enum ConsoleLoggerFormat
	{
		Default,
		Systemd
	}
	public class ConsoleLoggerOptions
	{
		private ConsoleLoggerFormat _format;

		private ConsoleLoggerQueueFullMode _queueFullMode;

		internal const int DefaultMaxQueueLengthValue = 2500;

		private int _maxQueuedMessages = 2500;

		[Obsolete("ConsoleLoggerOptions.DisableColors has been deprecated. Use SimpleConsoleFormatterOptions.ColorBehavior instead.")]
		public bool DisableColors { get; set; }

		[Obsolete("ConsoleLoggerOptions.Format has been deprecated. Use ConsoleLoggerOptions.FormatterName instead.")]
		public ConsoleLoggerFormat Format
		{
			get
			{
				return _format;
			}
			set
			{
				if (value < ConsoleLoggerFormat.Default || value > ConsoleLoggerFormat.Systemd)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_format = value;
			}
		}

		public string? FormatterName { get; set; }

		[Obsolete("ConsoleLoggerOptions.IncludeScopes has been deprecated. Use ConsoleFormatterOptions.IncludeScopes instead.")]
		public bool IncludeScopes { get; set; }

		public LogLevel LogToStandardErrorThreshold { get; set; } = LogLevel.None;


		[Obsolete("ConsoleLoggerOptions.TimestampFormat has been deprecated. Use ConsoleFormatterOptions.TimestampFormat instead.")]
		public string? TimestampFormat { get; set; }

		[Obsolete("ConsoleLoggerOptions.UseUtcTimestamp has been deprecated. Use ConsoleFormatterOptions.UseUtcTimestamp instead.")]
		public bool UseUtcTimestamp { get; set; }

		public ConsoleLoggerQueueFullMode QueueFullMode
		{
			get
			{
				return _queueFullMode;
			}
			set
			{
				if (value != 0 && value != ConsoleLoggerQueueFullMode.DropWrite)
				{
					throw new ArgumentOutOfRangeException(System.SR.Format(System.SR.QueueModeNotSupported, "value"));
				}
				_queueFullMode = value;
			}
		}

		public int MaxQueueLength
		{
			get
			{
				return _maxQueuedMessages;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentOutOfRangeException(System.SR.Format(System.SR.MaxQueueLengthBadValue, "value"));
				}
				_maxQueuedMessages = value;
			}
		}
	}
	[UnsupportedOSPlatform("browser")]
	internal class ConsoleLoggerProcessor : IDisposable
	{
		private readonly Queue<LogMessageEntry> _messageQueue;

		private volatile int _messagesDropped;

		private bool _isAddingCompleted;

		private int _maxQueuedMessages = 2500;

		private ConsoleLoggerQueueFullMode _fullMode;

		private readonly Thread _outputThread;

		public int MaxQueueLength
		{
			get
			{
				return _maxQueuedMessages;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentOutOfRangeException(System.SR.Format(System.SR.MaxQueueLengthBadValue, "value"));
				}
				lock (_messageQueue)
				{
					_maxQueuedMessages = value;
					Monitor.PulseAll(_messageQueue);
				}
			}
		}

		public ConsoleLoggerQueueFullMode FullMode
		{
			get
			{
				return _fullMode;
			}
			set
			{
				if (value != 0 && value != ConsoleLoggerQueueFullMode.DropWrite)
				{
					throw new ArgumentOutOfRangeException(System.SR.Format(System.SR.QueueModeNotSupported, "value"));
				}
				lock (_messageQueue)
				{
					_fullMode = value;
					Monitor.PulseAll(_messageQueue);
				}
			}
		}

		public IConsole Console { get; }

		public IConsole ErrorConsole { get; }

		public ConsoleLoggerProcessor(IConsole console, IConsole errorConsole, ConsoleLoggerQueueFullMode fullMode, int maxQueueLength)
		{
			_messageQueue = new Queue<LogMessageEntry>();
			FullMode = fullMode;
			MaxQueueLength = maxQueueLength;
			Console = console;
			ErrorConsole = errorConsole;
			_outputThread = new Thread(ProcessLogQueue)
			{
				IsBackground = true,
				Name = "Console logger queue processing thread"
			};
			_outputThread.Start();
		}

		public virtual void EnqueueMessage(LogMessageEntry message)
		{
			if (!Enqueue(message))
			{
				WriteMessage(message);
			}
		}

		internal void WriteMessage(LogMessageEntry entry)
		{
			try
			{
				(entry.LogAsError ? ErrorConsole : Console).Write(entry.Message);
			}
			catch
			{
				CompleteAdding();
			}
		}

		private void ProcessLogQueue()
		{
			LogMessageEntry item;
			while (TryDequeue(out item))
			{
				WriteMessage(item);
			}
		}

		public bool Enqueue(LogMessageEntry item)
		{
			lock (_messageQueue)
			{
				while (_messageQueue.Count >= MaxQueueLength && !_isAddingCompleted)
				{
					if (FullMode == ConsoleLoggerQueueFullMode.DropWrite)
					{
						_messagesDropped++;
						return true;
					}
					Monitor.Wait(_messageQueue);
				}
				if (!_isAddingCompleted)
				{
					bool num = _messageQueue.Count == 0;
					if (_messagesDropped > 0)
					{
						_messageQueue.Enqueue(new LogMessageEntry(System.SR.Format(System.SR.WarningMessageOnDrop + Environment.NewLine, _messagesDropped), logAsError: true));
						_messagesDropped = 0;
					}
					_messageQueue.Enqueue(item);
					if (num)
					{
						Monitor.PulseAll(_messageQueue);
					}
					return true;
				}
			}
			return false;
		}

		public bool TryDequeue(out LogMessageEntry item)
		{
			lock (_messageQueue)
			{
				while (_messageQueue.Count == 0 && !_isAddingCompleted)
				{
					Monitor.Wait(_messageQueue);
				}
				if (_messageQueue.Count > 0)
				{
					item = _messageQueue.Dequeue();
					if (_messageQueue.Count == MaxQueueLength - 1)
					{
						Monitor.PulseAll(_messageQueue);
					}
					return true;
				}
				item = default(LogMessageEntry);
				return false;
			}
		}

		public void Dispose()
		{
			CompleteAdding();
			try
			{
				_outputThread.Join(1500);
			}
			catch (ThreadStateException)
			{
			}
		}

		private void CompleteAdding()
		{
			lock (_messageQueue)
			{
				_isAddingCompleted = true;
				Monitor.PulseAll(_messageQueue);
			}
		}
	}
	[UnsupportedOSPlatform("browser")]
	[ProviderAlias("Console")]
	public class ConsoleLoggerProvider : ILoggerProvider, IDisposable, ISupportExternalScope
	{
		private readonly IOptionsMonitor<ConsoleLoggerOptions> _options;

		private readonly ConcurrentDictionary<string, ConsoleLogger> _loggers;

		private ConcurrentDictionary<string, ConsoleFormatter> _formatters;

		private readonly ConsoleLoggerProcessor _messageQueue;

		private readonly IDisposable _optionsReloadToken;

		private IExternalScopeProvider _scopeProvider = Microsoft.Extensions.Logging.NullExternalScopeProvider.Instance;

		public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options)
			: this(options, Array.Empty<ConsoleFormatter>())
		{
		}

		public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options, IEnumerable<ConsoleFormatter>? formatters)
		{
			_options = options;
			_loggers = new ConcurrentDictionary<string, ConsoleLogger>();
			SetFormatters(formatters);
			IConsole console;
			IConsole errorConsole;
			if (DoesConsoleSupportAnsi())
			{
				console = new AnsiLogConsole();
				errorConsole = new AnsiLogConsole(stdErr: true);
			}
			else
			{
				console = new AnsiParsingLogConsole();
				errorConsole = new AnsiParsingLogConsole(stdErr: true);
			}
			_messageQueue = new ConsoleLoggerProcessor(console, errorConsole, options.CurrentValue.QueueFullMode, options.CurrentValue.MaxQueueLength);
			ReloadLoggerOptions(options.CurrentValue);
			_optionsReloadToken = _options.OnChange(ReloadLoggerOptions);
		}

		[UnsupportedOSPlatformGuard("windows")]
		private static bool DoesConsoleSupportAnsi()
		{
			string environmentVariable = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_CONSOLE_ALLOW_ANSI_COLOR_REDIRECTION");
			if (environmentVariable != null && (environmentVariable == "1" || environmentVariable.Equals("true", StringComparison.OrdinalIgnoreCase)))
			{
				return true;
			}
			if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				return true;
			}
			if (!global::Interop.Kernel32.GetConsoleMode(global::Interop.Kernel32.GetStdHandle(-11), out var mode))
			{
				return false;
			}
			return ((ulong)mode & 4uL) == 4;
		}

		[MemberNotNull("_formatters")]
		private void SetFormatters(IEnumerable<ConsoleFormatter> formatters = null)
		{
			ConcurrentDictionary<string, ConsoleFormatter> concurrentDictionary = new ConcurrentDictionary<string, ConsoleFormatter>(StringComparer.OrdinalIgnoreCase);
			bool flag = false;
			if (formatters != null)
			{
				foreach (ConsoleFormatter formatter in formatters)
				{
					concurrentDictionary.TryAdd(formatter.Name, formatter);
					flag = true;
				}
			}
			if (!flag)
			{
				concurrentDictionary.TryAdd("simple", new SimpleConsoleFormatter(new FormatterOptionsMonitor<SimpleConsoleFormatterOptions>(new SimpleConsoleFormatterOptions())));
				concurrentDictionary.TryAdd("systemd", new SystemdConsoleFormatter(new FormatterOptionsMonitor<ConsoleFormatterOptions>(new ConsoleFormatterOptions())));
				concurrentDictionary.TryAdd("json", new JsonConsoleFormatter(new FormatterOptionsMonitor<JsonConsoleFormatterOptions>(new JsonConsoleFormatterOptions())));
			}
			_formatters = concurrentDictionary;
		}

		private void ReloadLoggerOptions(ConsoleLoggerOptions options)
		{
			if (options.FormatterName == null || !_formatters.TryGetValue(options.FormatterName, out var value))
			{
				ConsoleFormatter consoleFormatter = ((options.Format != ConsoleLoggerFormat.Systemd) ? _formatters["simple"] : _formatters["systemd"]);
				value = consoleFormatter;
				if (options.FormatterName == null)
				{
					UpdateFormatterOptions(value, options);
				}
			}
			_messageQueue.FullMode = options.QueueFullMode;
			_messageQueue.MaxQueueLength = options.MaxQueueLength;
			foreach (KeyValuePair<string, ConsoleLogger> logger in _loggers)
			{
				logger.Value.Options = options;
				logger.Value.Formatter = value;
			}
		}

		public ILogger CreateLogger(string name)
		{
			if (_options.CurrentValue.FormatterName == null || !_formatters.TryGetValue(_options.CurrentValue.FormatterName, out var value))
			{
				ConsoleFormatter consoleFormatter = ((_options.CurrentValue.Format != ConsoleLoggerFormat.Systemd) ? _formatters["simple"] : _formatters["systemd"]);
				value = consoleFormatter;
				if (_options.CurrentValue.FormatterName == null)
				{
					UpdateFormatterOptions(value, _options.CurrentValue);
				}
			}
			if (!_loggers.TryGetValue(name, out var value2))
			{
				return _loggers.GetOrAdd(name, new ConsoleLogger(name, _messageQueue, value, _scopeProvider, _options.CurrentValue));
			}
			return value2;
		}

		private static void UpdateFormatterOptions(ConsoleFormatter formatter, ConsoleLoggerOptions deprecatedFromOptions)
		{
			if (formatter is SimpleConsoleFormatter simpleConsoleFormatter)
			{
				simpleConsoleFormatter.FormatterOptions = new SimpleConsoleFormatterOptions
				{
					ColorBehavior = (deprecatedFromOptions.DisableColors ? LoggerColorBehavior.Disabled : LoggerColorBehavior.Default),
					IncludeScopes = deprecatedFromOptions.IncludeScopes,
					TimestampFormat = deprecatedFromOptions.TimestampFormat,
					UseUtcTimestamp = deprecatedFromOptions.UseUtcTimestamp
				};
			}
			else if (formatter is SystemdConsoleFormatter systemdConsoleFormatter)
			{
				systemdConsoleFormatter.FormatterOptions = new ConsoleFormatterOptions
				{
					IncludeScopes = deprecatedFromOptions.IncludeScopes,
					TimestampFormat = deprecatedFromOptions.TimestampFormat,
					UseUtcTimestamp = deprecatedFromOptions.UseUtcTimestamp
				};
			}
		}

		public void Dispose()
		{
			_optionsReloadToken?.Dispose();
			_messageQueue.Dispose();
		}

		public void SetScopeProvider(IExternalScopeProvider scopeProvider)
		{
			_scopeProvider = scopeProvider;
			foreach (KeyValuePair<string, ConsoleLogger> logger in _loggers)
			{
				logger.Value.ScopeProvider = _scopeProvider;
			}
		}
	}
	public enum ConsoleLoggerQueueFullMode
	{
		Wait,
		DropWrite
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	[Obsolete("This type is retained only for compatibility. The recommended alternative is ConsoleLoggerOptions.", true)]
	public class ConsoleLoggerSettings : IConsoleLoggerSettings
	{
		public IChangeToken? ChangeToken { get; set; }

		public bool IncludeScopes { get; set; }

		public bool DisableColors { get; set; }

		public IDictionary<string, LogLevel> Switches { get; set; } = new Dictionary<string, LogLevel>();


		public IConsoleLoggerSettings Reload()
		{
			return this;
		}

		public bool TryGetSwitch(string name, out LogLevel level)
		{
			return Switches.TryGetValue(name, out level);
		}
	}
	internal sealed class FormatterOptionsMonitor<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptionsMonitor<TOptions> where TOptions : ConsoleFormatterOptions
	{
		private readonly TOptions _options;

		public TOptions CurrentValue => _options;

		public FormatterOptionsMonitor(TOptions options)
		{
			_options = options;
		}

		public TOptions Get(string? name)
		{
			return _options;
		}

		public IDisposable? OnChange(Action<TOptions, string> listener)
		{
			return null;
		}
	}
	internal interface IConsole
	{
		void Write(string message);
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	[Obsolete("This type is retained only for compatibility. The recommended alternative is ConsoleLoggerOptions.", true)]
	public interface IConsoleLoggerSettings
	{
		bool IncludeScopes { get; }

		IChangeToken? ChangeToken { get; }

		bool TryGetSwitch(string name, out LogLevel level);

		IConsoleLoggerSettings Reload();
	}
	internal sealed class JsonConsoleFormatter : ConsoleFormatter, IDisposable
	{
		private readonly IDisposable _optionsReloadToken;

		internal JsonConsoleFormatterOptions FormatterOptions { get; set; }

		public JsonConsoleFormatter(IOptionsMonitor<JsonConsoleFormatterOptions> options)
			: base("json")
		{
			ReloadLoggerOptions(options.CurrentValue);
			_optionsReloadToken = options.OnChange(ReloadLoggerOptions);
		}

		public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter)
		{
			object obj = logEntry.State;
			BufferedLogRecord val = (BufferedLogRecord)((obj is BufferedLogRecord) ? obj : null);
			if (val != null)
			{
				string message = val.FormattedMessage ?? string.Empty;
				WriteInternal(null, textWriter, message, val.LogLevel, logEntry.Category, val.EventId.Id, val.Exception, val.Attributes.Count > 0, null, val.Attributes, val.Timestamp);
				return;
			}
			string text = logEntry.Formatter(logEntry.State, logEntry.Exception);
			if (logEntry.Exception != null || text != null)
			{
				DateTimeOffset stamp = ((FormatterOptions.TimestampFormat == null) ? DateTimeOffset.MinValue : (FormatterOptions.UseUtcTimestamp ? DateTimeOffset.UtcNow : DateTimeOffset.Now));
				LogLevel logLevel = logEntry.LogLevel;
				string category = logEntry.Category;
				int id = logEntry.EventId.Id;
				string exception = logEntry.Exception?.ToString();
				bool hasState = logEntry.State != null;
				TState state = logEntry.State;
				WriteInternal(scopeProvider, textWriter, text, logLevel, category, id, exception, hasState, (state != null) ? state.ToString() : null, logEntry.State as IReadOnlyList<KeyValuePair<string, object>>, stamp);
			}
		}

		private unsafe void WriteInternal(IExternalScopeProvider scopeProvider, TextWriter textWriter, string message, LogLevel logLevel, string category, int eventId, string exception, bool hasState, string stateMessage, IReadOnlyList<KeyValuePair<string, object>> stateProperties, DateTimeOffset stamp)
		{
			using (System.Text.Json.PooledByteBufferWriter pooledByteBufferWriter = new System.Text.Json.PooledByteBufferWriter(1024))
			{
				using (Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(pooledByteBufferWriter, FormatterOptions.JsonWriterOptions))
				{
					utf8JsonWriter.WriteStartObject();
					string timestampFormat = FormatterOptions.TimestampFormat;
					if (timestampFormat != null)
					{
						utf8JsonWriter.WriteString("Timestamp", stamp.ToString(timestampFormat));
					}
					utf8JsonWriter.WriteNumber("EventId", eventId);
					utf8JsonWriter.WriteString("LogLevel", GetLogLevelString(logLevel));
					utf8JsonWriter.WriteString("Category", category);
					utf8JsonWriter.WriteString("Message", message);
					if (exception != null)
					{
						utf8JsonWriter.WriteString("Exception", exception);
					}
					if (hasState)
					{
						utf8JsonWriter.WriteStartObject("State");
						utf8JsonWriter.WriteString("Message", stateMessage);
						if (stateProperties != null)
						{
							foreach (KeyValuePair<string, object> stateProperty in stateProperties)
							{
								WriteItem(utf8JsonWriter, stateProperty);
							}
						}
						utf8JsonWriter.WriteEndObject();
					}
					WriteScopeInformation(utf8JsonWriter, scopeProvider);
					utf8JsonWriter.WriteEndObject();
					utf8JsonWriter.Flush();
				}
				ReadOnlySpan<byte> span = pooledByteBufferWriter.WrittenMemory.Span;
				char[] array = ArrayPool<char>.Shared.Rent(Encoding.UTF8.GetMaxCharCount(span.Length));
				try
				{
					int chars2;
					fixed (byte* bytes = span)
					{
						fixed (char* chars = array)
						{
							chars2 = Encoding.UTF8.GetChars(bytes, span.Length, chars, array.Length);
						}
					}
					textWriter.Write(array, 0, chars2);
				}
				finally
				{
					ArrayPool<char>.Shared.Return(array);
				}
			}
			textWriter.Write(Environment.NewLine);
		}

		private static string GetLogLevelString(LogLevel logLevel)
		{
			return logLevel switch
			{
				LogLevel.Trace => "Trace", 
				LogLevel.Debug => "Debug", 
				LogLevel.Information => "Information", 
				LogLevel.Warning => "Warning", 
				LogLevel.Error => "Error", 
				LogLevel.Critical => "Critical", 
				_ => throw new ArgumentOutOfRangeException("logLevel"), 
			};
		}

		private void WriteScopeInformation(Utf8JsonWriter writer, IExternalScopeProvider scopeProvider)
		{
			if (!FormatterOptions.IncludeScopes || scopeProvider == null)
			{
				return;
			}
			writer.WriteStartArray("Scopes");
			scopeProvider.ForEachScope(delegate(object scope, Utf8JsonWriter state)
			{
				if (scope is IEnumerable<KeyValuePair<string, object>> enumerable)
				{
					state.WriteStartObject();
					state.WriteString("Message", scope.ToString());
					foreach (KeyValuePair<string, object> item in enumerable)
					{
						WriteItem(state, item);
					}
					state.WriteEndObject();
				}
				else
				{
					state.WriteStringValue(ToInvariantString(scope));
				}
			}, writer);
			writer.WriteEndArray();
		}

		private static void WriteItem(Utf8JsonWriter writer, KeyValuePair<string, object> item)
		{
			string key = item.Key;
			object value = item.Value;
			if (!(value is bool value2))
			{
				if (!(value is byte value3))
				{
					if (!(value is sbyte value4))
					{
						if (!(value is char c))
						{
							if (!(value is decimal value5))
							{
								if (!(value is double value6))
								{
									if (!(value is float value7))
									{
										if (!(value is int value8))
										{
											if (!(value is uint value9))
											{
												if (!(value is long value10))
												{
													if (!(value is ulong value11))
													{
														if (!(value is short value12))
														{
															if (!(value is ushort value13))
															{
																if (value == null)
																{
																	writer.WriteNull(key);
																}
																else
																{
																	writer.WriteString(key, ToInvariantString(item.Value));
																}
															}
															else
															{
																writer.WriteNumber(key, value13);
															}
														}
														else
														{
															writer.WriteNumber(key, value12);
														}
													}
													else
													{
														writer.WriteNumber(key, value11);
													}
												}
												else
												{
													writer.WriteNumber(key, value10);
												}
											}
											else
											{
												writer.WriteNumber(key, value9);
											}
										}
										else
										{
											writer.WriteNumber(key, value8);
										}
									}
									else
									{
										writer.WriteNumber(key, value7);
									}
								}
								else
								{
									writer.WriteNumber(key, value6);
								}
							}
							else
							{
								writer.WriteNumber(key, value5);
							}
						}
						else
						{
							writer.WriteString(key, c.ToString());
						}
					}
					else
					{
						writer.WriteNumber(key, value4);
					}
				}
				else
				{
					writer.WriteNumber(key, value3);
				}
			}
			else
			{
				writer.WriteBoolean(key, value2);
			}
		}

		private static string ToInvariantString(object obj)
		{
			return Convert.ToString(obj, CultureInfo.InvariantCulture);
		}

		[MemberNotNull("FormatterOptions")]
		private void ReloadLoggerOptions(JsonConsoleFormatterOptions options)
		{
			FormatterOptions = options;
		}

		public void Dispose()
		{
			_optionsReloadToken?.Dispose();
		}
	}
	public class JsonConsoleFormatterOptions : ConsoleFormatterOptions
	{
		public JsonWriterOptions JsonWriterOptions { get; set; }

		internal override void Configure(IConfiguration configuration)
		{
			configuration.Bind_JsonConsoleFormatterOptions(this);
		}
	}
	public enum LoggerColorBehavior
	{
		Default,
		Enabled,
		Disabled
	}
	internal readonly struct LogMessageEntry
	{
		public readonly string Message;

		public readonly bool LogAsError;

		public LogMessageEntry(string message, bool logAsError = false)
		{
			Message = message;
			LogAsError = logAsError;
		}
	}
	internal sealed class SimpleConsoleFormatter : ConsoleFormatter, IDisposable
	{
		private readonly struct ConsoleColors
		{
			public ConsoleColor? Foreground { get; }

			public ConsoleColor? Background { get; }

			public ConsoleColors(ConsoleColor? foreground, ConsoleColor? background)
			{
				Foreground = foreground;
				Background = background;
			}
		}

		private const string LoglevelPadding = ": ";

		private static readonly string _messagePadding = new string(' ', GetLogLevelString(LogLevel.Information).Length + ": ".Length);

		private static readonly string _newLineWithMessagePadding = Environment.NewLine + _messagePadding;

		private readonly IDisposable _optionsReloadToken;

		private static bool IsAndroidOrAppleMobile => false;

		internal SimpleConsoleFormatterOptions FormatterOptions { get; set; }

		public SimpleConsoleFormatter(IOptionsMonitor<SimpleConsoleFormatterOptions> options)
			: base("simple")
		{
			ReloadLoggerOptions(options.CurrentValue);
			_optionsReloadToken = options.OnChange(ReloadLoggerOptions);
		}

		[MemberNotNull("FormatterOptions")]
		private void ReloadLoggerOptions(SimpleConsoleFormatterOptions options)
		{
			FormatterOptions = options;
		}

		public void Dispose()
		{
			_optionsReloadToken?.Dispose();
		}

		public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter)
		{
			object obj = logEntry.State;
			BufferedLogRecord val = (BufferedLogRecord)((obj is BufferedLogRecord) ? obj : null);
			if (val != null)
			{
				string message = val.FormattedMessage ?? string.Empty;
				WriteInternal(null, textWriter, message, val.LogLevel, val.EventId.Id, val.Exception, logEntry.Category, val.Timestamp);
				return;
			}
			string text = logEntry.Formatter(logEntry.State, logEntry.Exception);
			if (logEntry.Exception != null || text != null)
			{
				WriteInternal(scopeProvider, textWriter, text, logEntry.LogLevel, logEntry.EventId.Id, logEntry.Exception?.ToString(), logEntry.Category, GetCurrentDateTime());
			}
		}

		private void WriteInternal(IExternalScopeProvider scopeProvider, TextWriter textWriter, string message, LogLevel logLevel, int eventId, string exception, string category, DateTimeOffset stamp)
		{
			ConsoleColors logLevelConsoleColors = GetLogLevelConsoleColors(logLevel);
			string logLevelString = GetLogLevelString(logLevel);
			string text = null;
			string timestampFormat = FormatterOptions.TimestampFormat;
			if (timestampFormat != null)
			{
				text = stamp.ToString(timestampFormat);
			}
			if (text != null)
			{
				textWriter.Write(text);
			}
			if (logLevelString != null)
			{
				textWriter.WriteColoredMessage(logLevelString, logLevelConsoleColors.Background, logLevelConsoleColors.Foreground);
			}
			bool singleLine = FormatterOptions.SingleLine;
			textWriter.Write(": ");
			textWriter.Write(category);
			textWriter.Write('[');
			textWriter.Write(eventId.ToString());
			textWriter.Write(']');
			if (!singleLine)
			{
				textWriter.Write(Environment.NewLine);
			}
			WriteScopeInformation(textWriter, scopeProvider, singleLine);
			WriteMessage(textWriter, message, singleLine);
			if (exception != null)
			{
				WriteMessage(textWriter, exception, singleLine);
			}
			if (singleLine)
			{
				textWriter.Write(Environment.NewLine);
			}
		}

		private static void WriteMessage(TextWriter textWriter, string message, bool singleLine)
		{
			if (!string.IsNullOrEmpty(message))
			{
				if (singleLine)
				{
					textWriter.Write(' ');
					WriteReplacing(textWriter, Environment.NewLine, " ", message);
				}
				else
				{
					textWriter.Write(_messagePadding);
					WriteReplacing(textWriter, Environment.NewLine, _newLineWithMessagePadding, message);
					textWriter.Write(Environment.NewLine);
				}
			}
			static void WriteReplacing(TextWriter writer, string oldValue, string newValue, string message)
			{
				string value = message.Replace(oldValue, newValue);
				writer.Write(value);
			}
		}

		private DateTimeOffset GetCurrentDateTime()
		{
			if (FormatterOptions.TimestampFormat == null)
			{
				return DateTimeOffset.MinValue;
			}
			if (!FormatterOptions.UseUtcTimestamp)
			{
				return DateTimeOffset.Now;
			}
			return DateTimeOffset.UtcNow;
		}

		private static string GetLogLevelString(LogLevel logLevel)
		{
			return logLevel switch
			{
				LogLevel.Trace => "trce", 
				LogLevel.Debug => "dbug", 
				LogLevel.Information => "info", 
				LogLevel.Warning => "warn", 
				LogLevel.Error => "fail", 
				LogLevel.Critical => "crit", 
				_ => throw new ArgumentOutOfRangeException("logLevel"), 
			};
		}

		private ConsoleColors GetLogLevelConsoleColors(LogLevel logLevel)
		{
			if (FormatterOptions.ColorBehavior == LoggerColorBehavior.Disabled || (FormatterOptions.ColorBehavior == LoggerColorBehavior.Default && (!ConsoleUtils.EmitAnsiColorCodes || IsAndroidOrAppleMobile)))
			{
				return new ConsoleColors(null, null);
			}
			return logLevel switch
			{
				LogLevel.Trace => new ConsoleColors(ConsoleColor.Gray, ConsoleColor.Black), 
				LogLevel.Debug => new ConsoleColors(ConsoleColor.Gray, ConsoleColor.Black), 
				LogLevel.Information => new ConsoleColors(ConsoleColor.DarkGreen, ConsoleColor.Black), 
				LogLevel.Warning => new ConsoleColors(ConsoleColor.Yellow, ConsoleColor.Black), 
				LogLevel.Error => new ConsoleColors(ConsoleColor.Black, ConsoleColor.DarkRed), 
				LogLevel.Critical => new ConsoleColors(ConsoleColor.White, ConsoleColor.DarkRed), 
				_ => new ConsoleColors(null, null), 
			};
		}

		private void WriteScopeInformation(TextWriter textWriter, IExternalScopeProvider scopeProvider, bool singleLine)
		{
			if (!FormatterOptions.IncludeScopes || scopeProvider == null)
			{
				return;
			}
			bool paddingNeeded = !singleLine;
			scopeProvider.ForEachScope(delegate(obj

Microsoft.Extensions.Logging.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
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.Text;
using System.Threading;
using FxResources.Microsoft.Extensions.Logging;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging")]
[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("Logging infrastructure default implementation for Microsoft.Extensions.Logging.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Logging")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[assembly: TypeForwardedTo(typeof(ILoggingBuilder))]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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.Microsoft.Extensions.Logging
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string InvalidActivityTrackingOptions => GetResourceString("InvalidActivityTrackingOptions");

		internal static string MoreThanOneWildcard => GetResourceString("MoreThanOneWildcard");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection
{
	public static class LoggingServiceCollectionExtensions
	{
		public static IServiceCollection AddLogging(this IServiceCollection services)
		{
			return services.AddLogging(delegate
			{
			});
		}

		public static IServiceCollection AddLogging(this IServiceCollection services, Action<ILoggingBuilder> configure)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			services.AddOptions();
			services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());
			services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));
			services.TryAddEnumerable(ServiceDescriptor.Singleton((IConfigureOptions<LoggerFilterOptions>)new DefaultLoggerLevelConfigureOptions(LogLevel.Information)));
			configure((ILoggingBuilder)(object)new LoggingBuilder(services));
			return services;
		}
	}
}
namespace Microsoft.Extensions.Logging
{
	[Flags]
	public enum ActivityTrackingOptions
	{
		None = 0,
		SpanId = 1,
		TraceId = 2,
		ParentId = 4,
		TraceState = 8,
		TraceFlags = 0x10,
		Tags = 0x20,
		Baggage = 0x40
	}
	internal sealed class DefaultLoggerLevelConfigureOptions : ConfigureOptions<LoggerFilterOptions>
	{
		public DefaultLoggerLevelConfigureOptions(LogLevel level)
			: base((Action<LoggerFilterOptions>)delegate(LoggerFilterOptions options)
			{
				options.MinLevel = level;
			})
		{
		}
	}
	public static class FilterLoggingBuilderExtensions
	{
		public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, Func<string?, string?, LogLevel, bool> filter)
		{
			Func<string, string, LogLevel, bool> filter2 = filter;
			return builder.ConfigureFilter(delegate(LoggerFilterOptions options)
			{
				options.AddFilter(filter2);
			});
		}

		public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, Func<string?, LogLevel, bool> categoryLevelFilter)
		{
			Func<string, LogLevel, bool> categoryLevelFilter2 = categoryLevelFilter;
			return builder.ConfigureFilter(delegate(LoggerFilterOptions options)
			{
				options.AddFilter(categoryLevelFilter2);
			});
		}

		public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, Func<string?, LogLevel, bool> categoryLevelFilter) where T : ILoggerProvider
		{
			Func<string, LogLevel, bool> categoryLevelFilter2 = categoryLevelFilter;
			return builder.ConfigureFilter(delegate(LoggerFilterOptions options)
			{
				options.AddFilter<T>(categoryLevelFilter2);
			});
		}

		public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, Func<LogLevel, bool> levelFilter)
		{
			Func<LogLevel, bool> levelFilter2 = levelFilter;
			return builder.ConfigureFilter(delegate(LoggerFilterOptions options)
			{
				options.AddFilter(levelFilter2);
			});
		}

		public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider
		{
			Func<LogLevel, bool> levelFilter2 = levelFilter;
			return builder.ConfigureFilter(delegate(LoggerFilterOptions options)
			{
				options.AddFilter<T>(levelFilter2);
			});
		}

		public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, string? category, LogLevel level)
		{
			string category2 = category;
			return builder.ConfigureFilter(delegate(LoggerFilterOptions options)
			{
				options.AddFilter(category2, level);
			});
		}

		public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, string? category, LogLevel level) where T : ILoggerProvider
		{
			string category2 = category;
			return builder.ConfigureFilter(delegate(LoggerFilterOptions options)
			{
				options.AddFilter<T>(category2, level);
			});
		}

		public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, string? category, Func<LogLevel, bool> levelFilter)
		{
			string category2 = category;
			Func<LogLevel, bool> levelFilter2 = levelFilter;
			return builder.ConfigureFilter(delegate(LoggerFilterOptions options)
			{
				options.AddFilter(category2, levelFilter2);
			});
		}

		public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, string? category, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider
		{
			string category2 = category;
			Func<LogLevel, bool> levelFilter2 = levelFilter;
			return builder.ConfigureFilter(delegate(LoggerFilterOptions options)
			{
				options.AddFilter<T>(category2, levelFilter2);
			});
		}

		public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, Func<string?, string?, LogLevel, bool> filter)
		{
			return AddRule(builder, null, null, null, filter);
		}

		public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, Func<string?, LogLevel, bool> categoryLevelFilter)
		{
			Func<string, LogLevel, bool> categoryLevelFilter2 = categoryLevelFilter;
			return AddRule(builder, null, null, null, (string type, string name, LogLevel level) => categoryLevelFilter2(name, level));
		}

		public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, Func<string?, LogLevel, bool> categoryLevelFilter) where T : ILoggerProvider
		{
			Func<string, LogLevel, bool> categoryLevelFilter2 = categoryLevelFilter;
			return AddRule(builder, typeof(T).FullName, null, null, (string type, string name, LogLevel level) => categoryLevelFilter2(name, level));
		}

		public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, Func<LogLevel, bool> levelFilter)
		{
			Func<LogLevel, bool> levelFilter2 = levelFilter;
			return AddRule(builder, null, null, null, (string type, string name, LogLevel level) => levelFilter2(level));
		}

		public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider
		{
			Func<LogLevel, bool> levelFilter2 = levelFilter;
			return AddRule(builder, typeof(T).FullName, null, null, (string type, string name, LogLevel level) => levelFilter2(level));
		}

		public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, string? category, LogLevel level)
		{
			return AddRule(builder, null, category, level);
		}

		public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, string? category, LogLevel level) where T : ILoggerProvider
		{
			return AddRule(builder, typeof(T).FullName, category, level);
		}

		public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, string? category, Func<LogLevel, bool> levelFilter)
		{
			Func<LogLevel, bool> levelFilter2 = levelFilter;
			return AddRule(builder, null, category, null, (string type, string name, LogLevel level) => levelFilter2(level));
		}

		public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, string? category, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider
		{
			Func<LogLevel, bool> levelFilter2 = levelFilter;
			return AddRule(builder, typeof(T).FullName, category, null, (string type, string name, LogLevel level) => levelFilter2(level));
		}

		private static ILoggingBuilder ConfigureFilter(this ILoggingBuilder builder, Action<LoggerFilterOptions> configureOptions)
		{
			builder.Services.Configure(configureOptions);
			return builder;
		}

		private static LoggerFilterOptions AddRule(LoggerFilterOptions options, string type = null, string category = null, LogLevel? level = null, Func<string, string, LogLevel, bool> filter = null)
		{
			options.Rules.Add(new LoggerFilterRule(type, category, level, filter));
			return options;
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	[DebuggerTypeProxy(typeof(LoggerDebugView))]
	internal sealed class Logger : ILogger
	{
		private sealed class LoggerDebugView
		{
			[CompilerGenerated]
			private Logger <logger>P;

			public string Name => <logger>P._categoryName;

			public List<LoggerProviderDebugView> Providers
			{
				get
				{
					List<LoggerProviderDebugView> list = new List<LoggerProviderDebugView>();
					for (int i = 0; i < <logger>P.Loggers.Length; i++)
					{
						LoggerInformation loggerInformation = <logger>P.Loggers[i];
						string providerName = ProviderAliasUtilities.GetAlias(loggerInformation.ProviderType) ?? loggerInformation.ProviderType.Name;
						MessageLogger? messageLogger = FirstOrNull(<logger>P.MessageLoggers, loggerInformation.Logger);
						list.Add(new LoggerProviderDebugView(providerName, messageLogger));
					}
					return list;
					static MessageLogger? FirstOrNull(MessageLogger[] messageLoggers, ILogger logger)
					{
						if (messageLoggers == null || messageLoggers.Length == 0)
						{
							return null;
						}
						for (int j = 0; j < messageLoggers.Length; j++)
						{
							MessageLogger value = messageLoggers[j];
							if (value.Logger == logger)
							{
								return value;
							}
						}
						return null;
					}
				}
			}

			public List<object> Scopes
			{
				get
				{
					IExternalScopeProvider externalScopeProvider = <logger>P.ScopeLoggers?.FirstOrDefault().ExternalScopeProvider;
					if (externalScopeProvider == null)
					{
						return null;
					}
					List<object> list = new List<object>();
					externalScopeProvider.ForEachScope(delegate(object scope, List<object> scopes)
					{
						scopes.Add(scope);
					}, list);
					return list;
				}
			}

			public LogLevel? MinLevel => DebuggerDisplayFormatting.CalculateEnabledLogLevel(<logger>P);

			public bool Enabled => DebuggerDisplayFormatting.CalculateEnabledLogLevel(<logger>P).HasValue;

			public LoggerDebugView(Logger logger)
			{
				<logger>P = logger;
				base..ctor();
			}
		}

		[DebuggerDisplay("{DebuggerToString(),nq}")]
		private sealed class LoggerProviderDebugView
		{
			[CompilerGenerated]
			private string <providerName>P;

			[CompilerGenerated]
			private MessageLogger? <messageLogger>P;

			public string Name => <providerName>P;

			public LogLevel LogLevel => CalculateEnabledLogLevel(<messageLogger>P).GetValueOrDefault(LogLevel.None);

			public LoggerProviderDebugView(string providerName, MessageLogger? messageLogger)
			{
				<providerName>P = providerName;
				<messageLogger>P = messageLogger;
				base..ctor();
			}

			private static LogLevel? CalculateEnabledLogLevel(MessageLogger? logger)
			{
				if (!logger.HasValue)
				{
					return null;
				}
				object obj = global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6;
				if (obj == null)
				{
					obj = new int[6] { 5, 4, 3, 2, 1, 0 };
					global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6 = (int[])obj;
				}
				ReadOnlySpan<LogLevel> readOnlySpan = new ReadOnlySpan<LogLevel>((LogLevel[]?)obj);
				LogLevel? result = null;
				ReadOnlySpan<LogLevel> readOnlySpan2 = readOnlySpan;
				for (int i = 0; i < readOnlySpan2.Length; i++)
				{
					LogLevel logLevel = readOnlySpan2[i];
					if (!logger.Value.IsEnabled(logLevel))
					{
						break;
					}
					result = logLevel;
				}
				return result;
			}

			private string DebuggerToString()
			{
				return $"Name = \"{<providerName>P}\", LogLevel = {LogLevel}";
			}
		}

		private sealed class Scope : IDisposable
		{
			private bool _isDisposed;

			private IDisposable _disposable0;

			private IDisposable _disposable1;

			private readonly IDisposable[] _disposable;

			public Scope(int count)
			{
				if (count > 2)
				{
					_disposable = new IDisposable[count - 2];
				}
			}

			public void SetDisposable(int index, IDisposable disposable)
			{
				switch (index)
				{
				case 0:
					_disposable0 = disposable;
					break;
				case 1:
					_disposable1 = disposable;
					break;
				default:
					_disposable[index - 2] = disposable;
					break;
				}
			}

			public void Dispose()
			{
				if (_isDisposed)
				{
					return;
				}
				_disposable0?.Dispose();
				_disposable1?.Dispose();
				if (_disposable != null)
				{
					int num = _disposable.Length;
					for (int i = 0; i != num; i++)
					{
						_disposable[i]?.Dispose();
					}
				}
				_isDisposed = true;
			}
		}

		private readonly string _categoryName;

		public LoggerInformation[] Loggers { get; set; }

		public MessageLogger[] MessageLoggers { get; set; }

		public ScopeLogger[] ScopeLoggers { get; set; }

		public Logger(string categoryName, LoggerInformation[] loggers)
		{
			_categoryName = categoryName;
			Loggers = loggers;
		}

		public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
		{
			MessageLogger[] messageLoggers = MessageLoggers;
			if (messageLoggers == null)
			{
				return;
			}
			List<Exception> exceptions2 = null;
			for (int i = 0; i < messageLoggers.Length; i++)
			{
				ref MessageLogger reference = ref messageLoggers[i];
				if (reference.IsEnabled(logLevel))
				{
					LoggerLog(logLevel, eventId, reference.Logger, exception, formatter, ref exceptions2, in state);
				}
			}
			if (exceptions2 != null && exceptions2.Count > 0)
			{
				ThrowLoggingError(exceptions2);
			}
			static void LoggerLog(LogLevel logLevel, EventId eventId, ILogger logger, Exception exception, Func<TState, Exception, string> formatter, ref List<Exception> exceptions, in TState state)
			{
				try
				{
					logger.Log(logLevel, eventId, state, exception, formatter);
				}
				catch (Exception item)
				{
					if (exceptions == null)
					{
						exceptions = new List<Exception>();
					}
					exceptions.Add(item);
				}
			}
		}

		public bool IsEnabled(LogLevel logLevel)
		{
			MessageLogger[] messageLoggers = MessageLoggers;
			if (messageLoggers == null)
			{
				return false;
			}
			List<Exception> exceptions2 = null;
			int i;
			for (i = 0; i < messageLoggers.Length; i++)
			{
				ref MessageLogger reference = ref messageLoggers[i];
				if (reference.IsEnabled(logLevel) && LoggerIsEnabled(logLevel, reference.Logger, ref exceptions2))
				{
					break;
				}
			}
			if (exceptions2 != null && exceptions2.Count > 0)
			{
				ThrowLoggingError(exceptions2);
			}
			return i < messageLoggers.Length;
			static bool LoggerIsEnabled(LogLevel logLevel, ILogger logger, ref List<Exception> exceptions)
			{
				try
				{
					if (logger.IsEnabled(logLevel))
					{
						return true;
					}
				}
				catch (Exception item)
				{
					if (exceptions == null)
					{
						exceptions = new List<Exception>();
					}
					exceptions.Add(item);
				}
				return false;
			}
		}

		public IDisposable BeginScope<TState>(TState state)
		{
			ScopeLogger[] scopeLoggers = ScopeLoggers;
			if (scopeLoggers == null)
			{
				return Microsoft.Extensions.Logging.NullScope.Instance;
			}
			if (scopeLoggers.Length == 1)
			{
				return scopeLoggers[0].CreateScope(state);
			}
			Scope scope = new Scope(scopeLoggers.Length);
			List<Exception> list = null;
			for (int i = 0; i < scopeLoggers.Length; i++)
			{
				ref ScopeLogger reference = ref scopeLoggers[i];
				try
				{
					scope.SetDisposable(i, reference.CreateScope(state));
				}
				catch (Exception item)
				{
					if (list == null)
					{
						list = new List<Exception>();
					}
					list.Add(item);
				}
			}
			if (list != null && list.Count > 0)
			{
				ThrowLoggingError(list);
			}
			return scope;
		}

		private static void ThrowLoggingError(List<Exception> exceptions)
		{
			throw new AggregateException("An error occurred while writing to logger(s).", exceptions);
		}

		internal string DebuggerToString()
		{
			return DebuggerDisplayFormatting.DebuggerToString(_categoryName, this);
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	[DebuggerTypeProxy(typeof(LoggerFactoryDebugView))]
	public class LoggerFactory : ILoggerFactory, IDisposable
	{
		private struct ProviderRegistration
		{
			public ILoggerProvider Provider;

			public bool ShouldDispose;
		}

		private sealed class DisposingLoggerFactory : ILoggerFactory, IDisposable
		{
			private readonly ILoggerFactory _loggerFactory;

			private readonly ServiceProvider _serviceProvider;

			public DisposingLoggerFactory(ILoggerFactory loggerFactory, ServiceProvider serviceProvider)
			{
				_loggerFactory = loggerFactory;
				_serviceProvider = serviceProvider;
			}

			public void Dispose()
			{
				_serviceProvider.Dispose();
			}

			public ILogger CreateLogger(string categoryName)
			{
				return _loggerFactory.CreateLogger(categoryName);
			}

			public void AddProvider(ILoggerProvider provider)
			{
				_loggerFactory.AddProvider(provider);
			}
		}

		private sealed class LoggerFactoryDebugView
		{
			[CompilerGenerated]
			private LoggerFactory <loggerFactory>P;

			public List<ILoggerProvider> Providers => <loggerFactory>P._providerRegistrations.Select((ProviderRegistration r) => r.Provider).ToList();

			public bool Disposed => <loggerFactory>P._disposed;

			public LoggerFilterOptions FilterOptions => <loggerFactory>P._filterOptions;

			public LoggerFactoryDebugView(LoggerFactory loggerFactory)
			{
				<loggerFactory>P = loggerFactory;
				base..ctor();
			}
		}

		private readonly ConcurrentDictionary<string, Logger> _loggers = new ConcurrentDictionary<string, Logger>(StringComparer.Ordinal);

		private readonly List<ProviderRegistration> _providerRegistrations = new List<ProviderRegistration>();

		private readonly object _sync = new object();

		private volatile bool _disposed;

		private readonly IDisposable _changeTokenRegistration;

		private LoggerFilterOptions _filterOptions;

		private IExternalScopeProvider _scopeProvider;

		private readonly LoggerFactoryOptions _factoryOptions;

		public LoggerFactory()
			: this(Array.Empty<ILoggerProvider>())
		{
		}

		public LoggerFactory(IEnumerable<ILoggerProvider> providers)
			: this(providers, new StaticFilterOptionsMonitor(new LoggerFilterOptions()))
		{
		}

		public LoggerFactory(IEnumerable<ILoggerProvider> providers, LoggerFilterOptions filterOptions)
			: this(providers, new StaticFilterOptionsMonitor(filterOptions))
		{
		}

		public LoggerFactory(IEnumerable<ILoggerProvider> providers, IOptionsMonitor<LoggerFilterOptions> filterOption)
			: this(providers, filterOption, null)
		{
		}

		public LoggerFactory(IEnumerable<ILoggerProvider> providers, IOptionsMonitor<LoggerFilterOptions> filterOption, IOptions<LoggerFactoryOptions>? options)
			: this(providers, filterOption, options, null)
		{
		}

		public LoggerFactory(IEnumerable<ILoggerProvider> providers, IOptionsMonitor<LoggerFilterOptions> filterOption, IOptions<LoggerFactoryOptions>? options = null, IExternalScopeProvider? scopeProvider = null)
		{
			_scopeProvider = scopeProvider;
			_factoryOptions = ((options == null || options.Value == null) ? new LoggerFactoryOptions() : options.Value);
			if (((uint)_factoryOptions.ActivityTrackingOptions & 0xFFFFFF80u) != 0)
			{
				throw new ArgumentException(System.SR.Format(System.SR.InvalidActivityTrackingOptions, _factoryOptions.ActivityTrackingOptions), "options");
			}
			foreach (ILoggerProvider provider in providers)
			{
				AddProviderRegistration(provider, dispose: false);
			}
			_changeTokenRegistration = filterOption.OnChange(RefreshFilters);
			RefreshFilters(filterOption.CurrentValue);
		}

		public static ILoggerFactory Create(Action<ILoggingBuilder> configure)
		{
			ServiceCollection services = new ServiceCollection();
			services.AddLogging(configure);
			ServiceProvider serviceProvider = services.BuildServiceProvider();
			return new DisposingLoggerFactory(ServiceProviderServiceExtensions.GetRequiredService<ILoggerFactory>(serviceProvider), serviceProvider);
		}

		[MemberNotNull("_filterOptions")]
		private void RefreshFilters(LoggerFilterOptions filterOptions)
		{
			lock (_sync)
			{
				_filterOptions = filterOptions;
				foreach (KeyValuePair<string, Logger> logger2 in _loggers)
				{
					Logger value = logger2.Value;
					(value.MessageLoggers, value.ScopeLoggers) = ApplyFilters(value.Loggers);
				}
			}
		}

		public ILogger CreateLogger(string categoryName)
		{
			if (CheckDisposed())
			{
				throw new ObjectDisposedException("LoggerFactory");
			}
			if (!_loggers.TryGetValue(categoryName, out var value))
			{
				lock (_sync)
				{
					if (!_loggers.TryGetValue(categoryName, out value))
					{
						value = new Logger(categoryName, CreateLoggers(categoryName));
						(value.MessageLoggers, value.ScopeLoggers) = ApplyFilters(value.Loggers);
						_loggers[categoryName] = value;
					}
				}
			}
			return value;
		}

		public void AddProvider(ILoggerProvider provider)
		{
			if (CheckDisposed())
			{
				throw new ObjectDisposedException("LoggerFactory");
			}
			System.ThrowHelper.ThrowIfNull(provider, "provider");
			lock (_sync)
			{
				AddProviderRegistration(provider, dispose: true);
				foreach (KeyValuePair<string, Logger> logger2 in _loggers)
				{
					Logger value = logger2.Value;
					LoggerInformation[] array = value.Loggers;
					int num = array.Length;
					Array.Resize(ref array, array.Length + 1);
					array[num] = new LoggerInformation(provider, logger2.Key);
					value.Loggers = array;
					(value.MessageLoggers, value.ScopeLoggers) = ApplyFilters(value.Loggers);
				}
			}
		}

		private void AddProviderRegistration(ILoggerProvider provider, bool dispose)
		{
			_providerRegistrations.Add(new ProviderRegistration
			{
				Provider = provider,
				ShouldDispose = dispose
			});
			if (provider is ISupportExternalScope supportExternalScope)
			{
				if (_scopeProvider == null)
				{
					_scopeProvider = new LoggerFactoryScopeProvider(_factoryOptions.ActivityTrackingOptions);
				}
				supportExternalScope.SetScopeProvider(_scopeProvider);
			}
		}

		private LoggerInformation[] CreateLoggers(string categoryName)
		{
			LoggerInformation[] array = new LoggerInformation[_providerRegistrations.Count];
			for (int i = 0; i < _providerRegistrations.Count; i++)
			{
				array[i] = new LoggerInformation(_providerRegistrations[i].Provider, categoryName);
			}
			return array;
		}

		private (MessageLogger[] MessageLoggers, ScopeLogger[] ScopeLoggers) ApplyFilters(LoggerInformation[] loggers)
		{
			List<MessageLogger> list = new List<MessageLogger>();
			List<ScopeLogger> list2 = (_filterOptions.CaptureScopes ? new List<ScopeLogger>() : null);
			for (int i = 0; i < loggers.Length; i++)
			{
				LoggerInformation loggerInformation = loggers[i];
				LoggerRuleSelector.Select(_filterOptions, loggerInformation.ProviderType, loggerInformation.Category, out var minLevel, out var filter);
				if (!minLevel.HasValue || minLevel.GetValueOrDefault() <= LogLevel.Critical)
				{
					list.Add(new MessageLogger(loggerInformation.Logger, loggerInformation.Category, loggerInformation.ProviderType.FullName, minLevel, filter));
					if (!loggerInformation.ExternalScope)
					{
						list2?.Add(new ScopeLogger(loggerInformation.Logger, null));
					}
				}
			}
			if (_scopeProvider != null)
			{
				list2?.Add(new ScopeLogger(null, _scopeProvider));
			}
			return (list.ToArray(), list2?.ToArray());
		}

		protected virtual bool CheckDisposed()
		{
			return _disposed;
		}

		public void Dispose()
		{
			if (_disposed)
			{
				return;
			}
			_disposed = true;
			_changeTokenRegistration?.Dispose();
			foreach (ProviderRegistration providerRegistration in _providerRegistrations)
			{
				try
				{
					if (providerRegistration.ShouldDispose)
					{
						providerRegistration.Provider.Dispose();
					}
				}
				catch
				{
				}
			}
		}

		private string DebuggerToString()
		{
			return $"Providers = {_providerRegistrations.Count}, {_filterOptions.DebuggerToString()}";
		}
	}
	[DebuggerDisplay("ActivityTrackingOptions = {ActivityTrackingOptions}")]
	public class LoggerFactoryOptions
	{
		public ActivityTrackingOptions ActivityTrackingOptions { get; set; }
	}
	internal sealed class LoggerFactoryScopeProvider : IExternalScopeProvider
	{
		private sealed class Scope : IDisposable
		{
			private readonly LoggerFactoryScopeProvider _provider;

			private bool _isDisposed;

			public Scope Parent { get; }

			public object State { get; }

			internal Scope(LoggerFactoryScopeProvider provider, object state, Scope parent)
			{
				_provider = provider;
				State = state;
				Parent = parent;
			}

			public override string ToString()
			{
				return State?.ToString();
			}

			public void Dispose()
			{
				if (!_isDisposed)
				{
					_provider._currentScope.Value = Parent;
					_isDisposed = true;
				}
			}
		}

		private sealed class ActivityLogScope : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			private string _cachedToString;

			private const int MaxItems = 5;

			private readonly KeyValuePair<string, object>[] _items = new KeyValuePair<string, object>[5];

			public int Count { get; }

			public KeyValuePair<string, object> this[int index]
			{
				get
				{
					if (index >= Count)
					{
						throw new ArgumentOutOfRangeException("index");
					}
					return _items[index];
				}
			}

			public ActivityLogScope(Activity activity, ActivityTrackingOptions activityTrackingOption)
			{
				int num = 0;
				if ((activityTrackingOption & ActivityTrackingOptions.SpanId) != 0)
				{
					_items[num++] = new KeyValuePair<string, object>("SpanId", activity.GetSpanId());
				}
				if ((activityTrackingOption & ActivityTrackingOptions.TraceId) != 0)
				{
					_items[num++] = new KeyValuePair<string, object>("TraceId", activity.GetTraceId());
				}
				if ((activityTrackingOption & ActivityTrackingOptions.ParentId) != 0)
				{
					_items[num++] = new KeyValuePair<string, object>("ParentId", activity.GetParentId());
				}
				if ((activityTrackingOption & ActivityTrackingOptions.TraceState) != 0)
				{
					_items[num++] = new KeyValuePair<string, object>("TraceState", activity.TraceStateString);
				}
				if ((activityTrackingOption & ActivityTrackingOptions.TraceFlags) != 0)
				{
					_items[num++] = new KeyValuePair<string, object>("TraceFlags", activity.ActivityTraceFlags);
				}
				Count = num;
			}

			public override string ToString()
			{
				if (_cachedToString == null)
				{
					StringBuilder stringBuilder = new StringBuilder();
					stringBuilder.Append(_items[0].Key);
					stringBuilder.Append(':');
					stringBuilder.Append(_items[0].Value);
					for (int i = 1; i < Count; i++)
					{
						stringBuilder.Append(", ");
						stringBuilder.Append(_items[i].Key);
						stringBuilder.Append(':');
						stringBuilder.Append(_items[i].Value);
					}
					_cachedToString = stringBuilder.ToString();
				}
				return _cachedToString;
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				int i = 0;
				while (i < Count)
				{
					yield return this[i];
					int num = i + 1;
					i = num;
				}
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private sealed class ActivityBaggageLogScopeWrapper : IEnumerable<KeyValuePair<string, object>>, IEnumerable
		{
			private struct BaggageEnumerator : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable
			{
				private readonly IEnumerator<KeyValuePair<string, string>> _enumerator;

				public KeyValuePair<string, object> Current => new KeyValuePair<string, object>(_enumerator.Current.Key, _enumerator.Current.Value);

				object IEnumerator.Current => Current;

				public BaggageEnumerator(IEnumerator<KeyValuePair<string, string>> enumerator)
				{
					_enumerator = enumerator;
				}

				public void Dispose()
				{
					_enumerator.Dispose();
				}

				public bool MoveNext()
				{
					return _enumerator.MoveNext();
				}

				public void Reset()
				{
					_enumerator.Reset();
				}
			}

			private readonly IEnumerable<KeyValuePair<string, string>> _items;

			private StringBuilder _stringBuilder;

			public ActivityBaggageLogScopeWrapper(IEnumerable<KeyValuePair<string, string>> items)
			{
				_items = items;
			}

			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				return new BaggageEnumerator(_items.GetEnumerator());
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return new BaggageEnumerator(_items.GetEnumerator());
			}

			public override string ToString()
			{
				lock (this)
				{
					IEnumerator<KeyValuePair<string, string>> enumerator = _items.GetEnumerator();
					if (!enumerator.MoveNext())
					{
						return string.Empty;
					}
					if (_stringBuilder == null)
					{
						_stringBuilder = new StringBuilder();
					}
					_stringBuilder.Append(enumerator.Current.Key);
					_stringBuilder.Append(':');
					_stringBuilder.Append(enumerator.Current.Value);
					while (enumerator.MoveNext())
					{
						_stringBuilder.Append(", ");
						_stringBuilder.Append(enumerator.Current.Key);
						_stringBuilder.Append(':');
						_stringBuilder.Append(enumerator.Current.Value);
					}
					string result = _stringBuilder.ToString();
					_stringBuilder.Clear();
					return result;
				}
			}
		}

		private readonly AsyncLocal<Scope> _currentScope = new AsyncLocal<Scope>();

		private readonly ActivityTrackingOptions _activityTrackingOption;

		public LoggerFactoryScopeProvider(ActivityTrackingOptions activityTrackingOption)
		{
			_activityTrackingOption = activityTrackingOption;
		}

		public void ForEachScope<TState>(Action<object, TState> callback, TState state)
		{
			if (_activityTrackingOption != 0)
			{
				Activity current2 = Activity.Current;
				if (current2 != null)
				{
					ActivityLogScope activityLogScope = current2.GetCustomProperty("__ActivityLogScope__") as ActivityLogScope;
					if (activityLogScope == null)
					{
						activityLogScope = new ActivityLogScope(current2, _activityTrackingOption);
						current2.SetCustomProperty("__ActivityLogScope__", activityLogScope);
					}
					callback(activityLogScope, state);
					if ((_activityTrackingOption & ActivityTrackingOptions.Tags) != 0 && current2.TagObjects.GetEnumerator().MoveNext())
					{
						callback(current2.TagObjects, state);
					}
					if ((_activityTrackingOption & ActivityTrackingOptions.Baggage) != 0)
					{
						IEnumerable<KeyValuePair<string, string>> baggage = current2.Baggage;
						if (baggage.GetEnumerator().MoveNext())
						{
							ActivityBaggageLogScopeWrapper orCreateActivityBaggageLogScopeWrapper = GetOrCreateActivityBaggageLogScopeWrapper(current2, baggage);
							callback(orCreateActivityBaggageLogScopeWrapper, state);
						}
					}
				}
			}
			Report(_currentScope.Value);
			void Report(Scope current)
			{
				if (current != null)
				{
					Report(current.Parent);
					callback(current.State, state);
				}
			}
		}

		private static ActivityBaggageLogScopeWrapper GetOrCreateActivityBaggageLogScopeWrapper(Activity activity, IEnumerable<KeyValuePair<string, string>> items)
		{
			ActivityBaggageLogScopeWrapper activityBaggageLogScopeWrapper = activity.GetCustomProperty("__ActivityBaggageItemsLogScope__") as ActivityBaggageLogScopeWrapper;
			if (activityBaggageLogScopeWrapper == null)
			{
				activityBaggageLogScopeWrapper = new ActivityBaggageLogScopeWrapper(items);
				activity.SetCustomProperty("__ActivityBaggageItemsLogScope__", activityBaggageLogScopeWrapper);
			}
			return activityBaggageLogScopeWrapper;
		}

		public IDisposable Push(object state)
		{
			Scope value = _currentScope.Value;
			Scope scope = new Scope(this, state, value);
			_currentScope.Value = scope;
			return scope;
		}
	}
	internal static class ActivityExtensions
	{
		public static string GetSpanId(this Activity activity)
		{
			return (string)((activity.IdFormat switch
			{
				ActivityIdFormat.Hierarchical => activity.Id, 
				ActivityIdFormat.W3C => activity.SpanId.ToHexString(), 
				_ => null, 
			}) ?? string.Empty);
		}

		public static string GetTraceId(this Activity activity)
		{
			return (string)((activity.IdFormat switch
			{
				ActivityIdFormat.Hierarchical => activity.RootId, 
				ActivityIdFormat.W3C => activity.TraceId.ToHexString(), 
				_ => null, 
			}) ?? string.Empty);
		}

		public static string GetParentId(this Activity activity)
		{
			return (string)((activity.IdFormat switch
			{
				ActivityIdFormat.Hierarchical => activity.ParentId, 
				ActivityIdFormat.W3C => activity.ParentSpanId.ToHexString(), 
				_ => null, 
			}) ?? string.Empty);
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	public class LoggerFilterOptions
	{
		public bool CaptureScopes { get; set; } = true;


		public LogLevel MinLevel { get; set; }

		public IList<LoggerFilterRule> Rules => RulesInternal;

		internal List<LoggerFilterRule> RulesInternal { get; } = new List<LoggerFilterRule>();


		internal string DebuggerToString()
		{
			string text = ((MinLevel == LogLevel.None) ? "Enabled = false" : $"MinLevel = {MinLevel}");
			if (Rules.Count > 0)
			{
				text += $", Rules = {Rules.Count}";
			}
			return text;
		}
	}
	public class LoggerFilterRule
	{
		public string? ProviderName { get; }

		public string? CategoryName { get; }

		public LogLevel? LogLevel { get; }

		public Func<string?, string?, LogLevel, bool>? Filter { get; }

		public LoggerFilterRule(string? providerName, string? categoryName, LogLevel? logLevel, Func<string?, string?, LogLevel, bool>? filter)
		{
			ProviderName = providerName;
			CategoryName = categoryName;
			LogLevel = logLevel;
			Filter = filter;
		}

		public override string ToString()
		{
			return string.Format("{0}: '{1}', {2}: '{3}', {4}: '{5}', {6}: '{7}'", "ProviderName", ProviderName, "CategoryName", CategoryName, "LogLevel", LogLevel, "Filter", Filter);
		}
	}
	internal readonly struct MessageLogger
	{
		public ILogger Logger { get; }

		public string Category { get; }

		private string ProviderTypeFullName { get; }

		public LogLevel? MinLevel { get; }

		public Func<string, string, LogLevel, bool> Filter { get; }

		public MessageLogger(ILogger logger, string category, string providerTypeFullName, LogLevel? minLevel, Func<string, string, LogLevel, bool> filter)
		{
			Logger = logger;
			Category = category;
			ProviderTypeFullName = providerTypeFullName;
			MinLevel = minLevel;
			Filter = filter;
		}

		public bool IsEnabled(LogLevel level)
		{
			if (MinLevel.HasValue && level < MinLevel)
			{
				return false;
			}
			if (Filter != null)
			{
				return Filter(ProviderTypeFullName, Category, level);
			}
			return true;
		}
	}
	internal readonly struct ScopeLogger
	{
		public ILogger Logger { get; }

		public IExternalScopeProvider ExternalScopeProvider { get; }

		public ScopeLogger(ILogger logger, IExternalScopeProvider externalScopeProvider)
		{
			Logger = logger;
			ExternalScopeProvider = externalScopeProvider;
		}

		public IDisposable CreateScope<TState>(TState state)
		{
			if (ExternalScopeProvider != null)
			{
				return ExternalScopeProvider.Push(state);
			}
			return Logger.BeginScope(state);
		}
	}
	internal readonly struct LoggerInformation
	{
		public ILogger Logger { get; }

		public string Category { get; }

		public Type ProviderType { get; }

		public bool ExternalScope { get; }

		public LoggerInformation(ILoggerProvider provider, string category)
		{
			this = default(LoggerInformation);
			ProviderType = provider.GetType();
			Logger = provider.CreateLogger(category);
			Category = category;
			ExternalScope = provider is ISupportExternalScope;
		}
	}
	internal static class LoggerRuleSelector
	{
		public static void Select(LoggerFilterOptions options, Type providerType, string category, out LogLevel? minLevel, out Func<string, string, LogLevel, bool> filter)
		{
			filter = null;
			minLevel = options.MinLevel;
			string alias = ProviderAliasUtilities.GetAlias(providerType);
			LoggerFilterRule loggerFilterRule = null;
			foreach (LoggerFilterRule item in options.RulesInternal)
			{
				if (IsBetter(item, loggerFilterRule, providerType.FullName, category) || (!string.IsNullOrEmpty(alias) && IsBetter(item, loggerFilterRule, alias, category)))
				{
					loggerFilterRule = item;
				}
			}
			if (loggerFilterRule != null)
			{
				filter = loggerFilterRule.Filter;
				minLevel = loggerFilterRule.LogLevel;
			}
		}

		private static bool IsBetter(LoggerFilterRule rule, LoggerFilterRule current, string logger, string category)
		{
			if (rule.ProviderName != null && rule.ProviderName != logger)
			{
				return false;
			}
			string categoryName = rule.CategoryName;
			if (categoryName != null)
			{
				int num = categoryName.IndexOf('*');
				if (num != -1 && categoryName.IndexOf('*', num + 1) != -1)
				{
					throw new InvalidOperationException(System.SR.MoreThanOneWildcard);
				}
				ReadOnlySpan<char> value;
				ReadOnlySpan<char> value2;
				if (num == -1)
				{
					value = categoryName.AsSpan();
					value2 = default(ReadOnlySpan<char>);
				}
				else
				{
					value = categoryName.AsSpan(0, num);
					value2 = categoryName.AsSpan(num + 1);
				}
				if (!category.AsSpan().StartsWith(value, StringComparison.OrdinalIgnoreCase) || !category.AsSpan().EndsWith(value2, StringComparison.OrdinalIgnoreCase))
				{
					return false;
				}
			}
			if (current != null && current.ProviderName != null)
			{
				if (rule.ProviderName == null)
				{
					return false;
				}
			}
			else if (rule.ProviderName != null)
			{
				return true;
			}
			if (current != null && current.CategoryName != null)
			{
				if (rule.CategoryName == null)
				{
					return false;
				}
				if (current.CategoryName.Length > rule.CategoryName.Length)
				{
					return false;
				}
			}
			return true;
		}
	}
	internal sealed class LoggingBuilder : ILoggingBuilder
	{
		public IServiceCollection Services { get; }

		public LoggingBuilder(IServiceCollection services)
		{
			Services = services;
		}
	}
	public static class LoggingBuilderExtensions
	{
		public static ILoggingBuilder SetMinimumLevel(this ILoggingBuilder builder, LogLevel level)
		{
			builder.Services.Add(ServiceDescriptor.Singleton((IConfigureOptions<LoggerFilterOptions>)new DefaultLoggerLevelConfigureOptions(level)));
			return builder;
		}

		public static ILoggingBuilder AddProvider(this ILoggingBuilder builder, ILoggerProvider provider)
		{
			builder.Services.AddSingleton(provider);
			return builder;
		}

		public static ILoggingBuilder ClearProviders(this ILoggingBuilder builder)
		{
			builder.Services.RemoveAll<ILoggerProvider>();
			return builder;
		}

		public static ILoggingBuilder Configure(this ILoggingBuilder builder, Action<LoggerFactoryOptions> action)
		{
			builder.Services.Configure(action);
			return builder;
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
	public class ProviderAliasAttribute : Attribute
	{
		public string Alias { get; }

		public ProviderAliasAttribute(string alias)
		{
			Alias = alias;
		}
	}
	internal sealed class StaticFilterOptionsMonitor : IOptionsMonitor<LoggerFilterOptions>
	{
		public LoggerFilterOptions CurrentValue { get; }

		public StaticFilterOptionsMonitor(LoggerFilterOptions currentValue)
		{
			CurrentValue = currentValue ?? throw new ArgumentNullException("currentValue");
		}

		public IDisposable OnChange(Action<LoggerFilterOptions, string> listener)
		{
			return null;
		}

		public LoggerFilterOptions Get(string name)
		{
			return CurrentValue;
		}
	}
	internal static class ProviderAliasUtilities
	{
		private const string AliasAttributeTypeFullName = "Microsoft.Extensions.Logging.ProviderAliasAttribute";

		internal static string GetAlias(Type providerType)
		{
			IList<CustomAttributeData> customAttributes = CustomAttributeData.GetCustomAttributes(providerType);
			for (int i = 0; i < customAttributes.Count; i++)
			{
				CustomAttributeData customAttributeData = customAttributes[i];
				if (customAttributeData.AttributeType.FullName == "Microsoft.Extensions.Logging.ProviderAliasAttribute" && customAttributeData.ConstructorArguments.Count > 0)
				{
					return customAttributeData.ConstructorArguments[0].Value?.ToString();
				}
			}
			return null;
		}
	}
	internal sealed class NullExternalScopeProvider : IExternalScopeProvider
	{
		public static IExternalScopeProvider Instance { get; } = new Microsoft.Extensions.Logging.NullExternalScopeProvider();


		private NullExternalScopeProvider()
		{
		}

		void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state)
		{
		}

		IDisposable IExternalScopeProvider.Push(object state)
		{
			return Microsoft.Extensions.Logging.NullScope.Instance;
		}
	}
	internal sealed class NullScope : IDisposable
	{
		public static Microsoft.Extensions.Logging.NullScope Instance { get; } = new Microsoft.Extensions.Logging.NullScope();


		private NullScope()
		{
		}

		public void Dispose()
		{
		}
	}
	internal static class DebuggerDisplayFormatting
	{
		internal static string DebuggerToString(string name, ILogger logger)
		{
			LogLevel? logLevel = CalculateEnabledLogLevel(logger);
			string text = "Name = \"" + name + "\"";
			if (logLevel.HasValue)
			{
				return text + $", MinLevel = {logLevel}";
			}
			return text + ", Enabled = false";
		}

		internal static LogLevel? CalculateEnabledLogLevel(ILogger logger)
		{
			object obj = global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6;
			if (obj == null)
			{
				obj = new int[6] { 5, 4, 3, 2, 1, 0 };
				global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6 = (int[])obj;
			}
			ReadOnlySpan<LogLevel> readOnlySpan = new ReadOnlySpan<LogLevel>((LogLevel[]?)obj);
			LogLevel? result = null;
			ReadOnlySpan<LogLevel> readOnlySpan2 = readOnlySpan;
			for (int i = 0; i < readOnlySpan2.Length; i++)
			{
				LogLevel logLevel = readOnlySpan2[i];
				if (!logger.IsEnabled(logLevel))
				{
					break;
				}
				result = logLevel;
			}
			return result;
		}
	}
}

Microsoft.Extensions.Options.ConfigurationExtensions.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Options.ConfigurationExtensions")]
[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("Provides additional configuration specific functionality related to Options.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Options.ConfigurationExtensions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | 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,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string Scope { get; set; }

		public string Target { get; set; }

		public string MessageId { get; set; }

		public string Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection
{
	public static class OptionsBuilderConfigurationExtensions
	{
		internal const string RequiresDynamicCodeMessage = "Binding strongly typed objects to configuration values may require generating dynamic code at runtime.";

		internal const string TrimmingRequiredUnreferencedCodeMessage = "TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.";

		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static OptionsBuilder<TOptions> Bind<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder, IConfiguration config) where TOptions : class
		{
			return optionsBuilder.Bind(config, delegate
			{
			});
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static OptionsBuilder<TOptions> Bind<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder, IConfiguration config, Action<BinderOptions>? configureBinder) where TOptions : class
		{
			System.ThrowHelper.ThrowIfNull(optionsBuilder, "optionsBuilder");
			optionsBuilder.Services.Configure<TOptions>(optionsBuilder.Name, config, configureBinder);
			return optionsBuilder;
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static OptionsBuilder<TOptions> BindConfiguration<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder, string configSectionPath, Action<BinderOptions>? configureBinder = null) where TOptions : class
		{
			string configSectionPath2 = configSectionPath;
			Action<BinderOptions> configureBinder2 = configureBinder;
			OptionsBuilder<TOptions> optionsBuilder2 = optionsBuilder;
			System.ThrowHelper.ThrowIfNull(optionsBuilder2, "optionsBuilder");
			System.ThrowHelper.ThrowIfNull(configSectionPath2, "configSectionPath");
			optionsBuilder2.Configure(delegate(TOptions opts, IConfiguration config)
			{
				IConfiguration configuration;
				if (!string.Equals("", configSectionPath2, StringComparison.OrdinalIgnoreCase))
				{
					IConfiguration section = config.GetSection(configSectionPath2);
					configuration = section;
				}
				else
				{
					configuration = config;
				}
				configuration.Bind(opts, configureBinder2);
			});
			optionsBuilder2.Services.AddSingleton<IOptionsChangeTokenSource<TOptions>, ConfigurationChangeTokenSource<TOptions>>((IServiceProvider sp) => new ConfigurationChangeTokenSource<TOptions>(optionsBuilder2.Name, sp.GetRequiredService<IConfiguration>()));
			return optionsBuilder2;
		}
	}
	public static class OptionsConfigurationServiceCollectionExtensions
	{
		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, IConfiguration config) where TOptions : class
		{
			return services.Configure<TOptions>(Microsoft.Extensions.Options.Options.DefaultName, config);
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, string? name, IConfiguration config) where TOptions : class
		{
			return services.Configure<TOptions>(name, config, delegate
			{
			});
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, IConfiguration config, Action<BinderOptions>? configureBinder) where TOptions : class
		{
			return services.Configure<TOptions>(Microsoft.Extensions.Options.Options.DefaultName, config, configureBinder);
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, string? name, IConfiguration config, Action<BinderOptions>? configureBinder) where TOptions : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(config, "config");
			services.AddOptions();
			services.AddSingleton((IOptionsChangeTokenSource<TOptions>)new ConfigurationChangeTokenSource<TOptions>(name, config));
			return services.AddSingleton((IConfigureOptions<TOptions>)new NamedConfigureFromConfigurationOptions<TOptions>(name, config, configureBinder));
		}
	}
}
namespace Microsoft.Extensions.Options
{
	public class ConfigurationChangeTokenSource<TOptions> : IOptionsChangeTokenSource<TOptions>
	{
		private readonly IConfiguration _config;

		public string Name { get; }

		public ConfigurationChangeTokenSource(IConfiguration config)
			: this(Options.DefaultName, config)
		{
		}

		public ConfigurationChangeTokenSource(string? name, IConfiguration config)
		{
			System.ThrowHelper.ThrowIfNull(config, "config");
			_config = config;
			Name = name ?? Options.DefaultName;
		}

		public IChangeToken GetChangeToken()
		{
			return _config.GetReloadToken();
		}
	}
	public class ConfigureFromConfigurationOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions> : ConfigureOptions<TOptions> where TOptions : class
	{
		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public ConfigureFromConfigurationOptions(IConfiguration config)
		{
			IConfiguration config2 = config;
			base..ctor((Action<TOptions>)delegate(TOptions options)
			{
				config2.Bind(options);
			});
			System.ThrowHelper.ThrowIfNull(config2, "config");
		}
	}
	public class NamedConfigureFromConfigurationOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions> : ConfigureNamedOptions<TOptions> where TOptions : class
	{
		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public NamedConfigureFromConfigurationOptions(string? name, IConfiguration config)
			: this(name, config, (Action<BinderOptions>?)delegate
			{
			})
		{
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")]
		[RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
		public NamedConfigureFromConfigurationOptions(string? name, IConfiguration config, Action<BinderOptions>? configureBinder)
		{
			IConfiguration config2 = config;
			Action<BinderOptions> configureBinder2 = configureBinder;
			base..ctor(name, (Action<TOptions>)delegate(TOptions options)
			{
				config2.Bind(options, configureBinder2);
			});
			System.ThrowHelper.ThrowIfNull(config2, "config");
		}
	}
}

Microsoft.Extensions.Options.dll

Decompiled a month ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using FxResources.Microsoft.Extensions.Options;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Extensions.Options.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Options")]
[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("Provides a strongly typed way of specifying and accessing settings using dependency injection.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Options")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.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]
	[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.Microsoft.Extensions.Options
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Error_CannotActivateAbstractOrInterface => GetResourceString("Error_CannotActivateAbstractOrInterface");

		internal static string Error_FailedBinding => GetResourceString("Error_FailedBinding");

		internal static string Error_FailedToActivate => GetResourceString("Error_FailedToActivate");

		internal static string Error_MissingParameterlessConstructor => GetResourceString("Error_MissingParameterlessConstructor");

		internal static string Error_NoConfigurationServices => GetResourceString("Error_NoConfigurationServices");

		internal static string Error_NoConfigurationServicesAndAction => GetResourceString("Error_NoConfigurationServicesAndAction");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | 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,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection
{
	[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2091:UnrecognizedReflectionPattern", Justification = "Workaround for https://github.com/mono/linker/issues/1416. Outer method has been annotated with DynamicallyAccessedMembers.")]
	public static class OptionsBuilderExtensions
	{
		public static OptionsBuilder<TOptions> ValidateOnStart<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class
		{
			OptionsBuilder<TOptions> optionsBuilder2 = optionsBuilder;
			System.ThrowHelper.ThrowIfNull(optionsBuilder2, "optionsBuilder");
			optionsBuilder2.Services.TryAddTransient<IStartupValidator, StartupValidator>();
			optionsBuilder2.Services.AddOptions<StartupValidatorOptions>().Configure(delegate(StartupValidatorOptions vo, IOptionsMonitor<TOptions> options)
			{
				vo._validators[(typeof(TOptions), optionsBuilder2.Name)] = delegate
				{
					options.Get(optionsBuilder2.Name);
				};
			});
			return optionsBuilder2;
		}
	}
	public static class OptionsServiceCollectionExtensions
	{
		public static IServiceCollection AddOptions(this IServiceCollection services)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(UnnamedOptionsManager<>)));
			services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>)));
			services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>)));
			services.TryAdd(ServiceDescriptor.Transient(typeof(IOptionsFactory<>), typeof(OptionsFactory<>)));
			services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitorCache<>), typeof(OptionsCache<>)));
			return services;
		}

		public static OptionsBuilder<TOptions> AddOptionsWithValidateOnStart<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions>(this IServiceCollection services, string? name = null) where TOptions : class
		{
			return new OptionsBuilder<TOptions>(services, name ?? Microsoft.Extensions.Options.Options.DefaultName).ValidateOnStart();
		}

		public static OptionsBuilder<TOptions> AddOptionsWithValidateOnStart<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TValidateOptions>(this IServiceCollection services, string? name = null) where TOptions : class where TValidateOptions : class, IValidateOptions<TOptions>
		{
			services.AddOptions().TryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<TOptions>, TValidateOptions>());
			return new OptionsBuilder<TOptions>(services, name ?? Microsoft.Extensions.Options.Options.DefaultName).ValidateOnStart();
		}

		public static IServiceCollection Configure<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class
		{
			return services.Configure(Microsoft.Extensions.Options.Options.DefaultName, configureOptions);
		}

		public static IServiceCollection Configure<TOptions>(this IServiceCollection services, string? name, Action<TOptions> configureOptions) where TOptions : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(configureOptions, "configureOptions");
			services.AddOptions();
			services.AddSingleton((IConfigureOptions<TOptions>)new ConfigureNamedOptions<TOptions>(name, configureOptions));
			return services;
		}

		public static IServiceCollection ConfigureAll<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class
		{
			return services.Configure(null, configureOptions);
		}

		public static IServiceCollection PostConfigure<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class
		{
			return services.PostConfigure(Microsoft.Extensions.Options.Options.DefaultName, configureOptions);
		}

		public static IServiceCollection PostConfigure<TOptions>(this IServiceCollection services, string? name, Action<TOptions> configureOptions) where TOptions : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			System.ThrowHelper.ThrowIfNull(configureOptions, "configureOptions");
			services.AddOptions();
			services.AddSingleton((IPostConfigureOptions<TOptions>)new PostConfigureOptions<TOptions>(name, configureOptions));
			return services;
		}

		public static IServiceCollection PostConfigureAll<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class
		{
			return services.PostConfigure(null, configureOptions);
		}

		public static IServiceCollection ConfigureOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TConfigureOptions>(this IServiceCollection services) where TConfigureOptions : class
		{
			return services.ConfigureOptions(typeof(TConfigureOptions));
		}

		private static IEnumerable<Type> FindConfigurationServices(Type type)
		{
			Type[] array = GetInterfacesOnType(type);
			foreach (Type type2 in array)
			{
				if (type2.IsGenericType)
				{
					Type genericTypeDefinition = type2.GetGenericTypeDefinition();
					if (genericTypeDefinition == typeof(IConfigureOptions<>) || genericTypeDefinition == typeof(IPostConfigureOptions<>) || genericTypeDefinition == typeof(IValidateOptions<>))
					{
						yield return type2;
					}
				}
			}
			[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This method only looks for interfaces referenced in its code. The trimmer will keep the interface and thus all of its implementations in that case. The call to GetInterfaces may return less results in trimmed apps, but it will include the interfaces this method looks for if they should be there.")]
			static Type[] GetInterfacesOnType(Type t)
			{
				return t.GetInterfaces();
			}
		}

		private static void ThrowNoConfigServices(Type type)
		{
			throw new InvalidOperationException((type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Action<>)) ? System.SR.Error_NoConfigurationServicesAndAction : System.SR.Error_NoConfigurationServices);
		}

		public static IServiceCollection ConfigureOptions(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type configureType)
		{
			services.AddOptions();
			bool flag = false;
			foreach (Type item in FindConfigurationServices(configureType))
			{
				services.AddTransient(item, configureType);
				flag = true;
			}
			if (!flag)
			{
				ThrowNoConfigServices(configureType);
			}
			return services;
		}

		public static IServiceCollection ConfigureOptions(this IServiceCollection services, object configureInstance)
		{
			services.AddOptions();
			Type type = configureInstance.GetType();
			bool flag = false;
			foreach (Type item in FindConfigurationServices(type))
			{
				services.AddSingleton(item, configureInstance);
				flag = true;
			}
			if (!flag)
			{
				ThrowNoConfigServices(type);
			}
			return services;
		}

		public static OptionsBuilder<TOptions> AddOptions<TOptions>(this IServiceCollection services) where TOptions : class
		{
			return services.AddOptions<TOptions>(Microsoft.Extensions.Options.Options.DefaultName);
		}

		public static OptionsBuilder<TOptions> AddOptions<TOptions>(this IServiceCollection services, string? name) where TOptions : class
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			services.AddOptions();
			return new OptionsBuilder<TOptions>(services, name);
		}
	}
}
namespace Microsoft.Extensions.Options
{
	public class ConfigureNamedOptions<TOptions> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class
	{
		public string? Name { get; }

		public Action<TOptions>? Action { get; }

		public ConfigureNamedOptions(string? name, Action<TOptions>? action)
		{
			Name = name;
			Action = action;
		}

		public virtual void Configure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options);
			}
		}

		public void Configure(TOptions options)
		{
			Configure(Options.DefaultName, options);
		}
	}
	public class ConfigureNamedOptions<TOptions, TDep> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep>? Action { get; }

		public TDep Dependency { get; }

		public ConfigureNamedOptions(string? name, TDep dependency, Action<TOptions, TDep>? action)
		{
			Name = name;
			Action = action;
			Dependency = dependency;
		}

		public virtual void Configure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency);
			}
		}

		public void Configure(TOptions options)
		{
			Configure(Options.DefaultName, options);
		}
	}
	public class ConfigureNamedOptions<TOptions, TDep1, TDep2> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep1, TDep2>? Action { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public ConfigureNamedOptions(string? name, TDep1 dependency, TDep2 dependency2, Action<TOptions, TDep1, TDep2>? action)
		{
			Name = name;
			Action = action;
			Dependency1 = dependency;
			Dependency2 = dependency2;
		}

		public virtual void Configure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency1, Dependency2);
			}
		}

		public void Configure(TOptions options)
		{
			Configure(Options.DefaultName, options);
		}
	}
	public class ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep1, TDep2, TDep3>? Action { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public TDep3 Dependency3 { get; }

		public ConfigureNamedOptions(string? name, TDep1 dependency, TDep2 dependency2, TDep3 dependency3, Action<TOptions, TDep1, TDep2, TDep3>? action)
		{
			Name = name;
			Action = action;
			Dependency1 = dependency;
			Dependency2 = dependency2;
			Dependency3 = dependency3;
		}

		public virtual void Configure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency1, Dependency2, Dependency3);
			}
		}

		public void Configure(TOptions options)
		{
			Configure(Options.DefaultName, options);
		}
	}
	public class ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep1, TDep2, TDep3, TDep4>? Action { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public TDep3 Dependency3 { get; }

		public TDep4 Dependency4 { get; }

		public ConfigureNamedOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Action<TOptions, TDep1, TDep2, TDep3, TDep4>? action)
		{
			Name = name;
			Action = action;
			Dependency1 = dependency1;
			Dependency2 = dependency2;
			Dependency3 = dependency3;
			Dependency4 = dependency4;
		}

		public virtual void Configure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4);
			}
		}

		public void Configure(TOptions options)
		{
			Configure(Options.DefaultName, options);
		}
	}
	public class ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>? Action { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public TDep3 Dependency3 { get; }

		public TDep4 Dependency4 { get; }

		public TDep5 Dependency5 { get; }

		public ConfigureNamedOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, TDep5 dependency5, Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>? action)
		{
			Name = name;
			Action = action;
			Dependency1 = dependency1;
			Dependency2 = dependency2;
			Dependency3 = dependency3;
			Dependency4 = dependency4;
			Dependency5 = dependency5;
		}

		public virtual void Configure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4, Dependency5);
			}
		}

		public void Configure(TOptions options)
		{
			Configure(Options.DefaultName, options);
		}
	}
	public class ConfigureOptions<TOptions> : IConfigureOptions<TOptions> where TOptions : class
	{
		public Action<TOptions>? Action { get; }

		public ConfigureOptions(Action<TOptions>? action)
		{
			Action = action;
		}

		public virtual void Configure(TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			Action?.Invoke(options);
		}
	}
	public interface IConfigureNamedOptions<in TOptions> : IConfigureOptions<TOptions> where TOptions : class
	{
		void Configure(string? name, TOptions options);
	}
	public interface IConfigureOptions<in TOptions> where TOptions : class
	{
		void Configure(TOptions options);
	}
	public interface IOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] out TOptions> where TOptions : class
	{
		TOptions Value { get; }
	}
	public interface IOptionsChangeTokenSource<out TOptions>
	{
		string? Name { get; }

		IChangeToken GetChangeToken();
	}
	public interface IOptionsFactory<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> where TOptions : class
	{
		TOptions Create(string name);
	}
	public interface IOptionsMonitor<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] out TOptions>
	{
		TOptions CurrentValue { get; }

		TOptions Get(string? name);

		IDisposable? OnChange(Action<TOptions, string?> listener);
	}
	public interface IOptionsMonitorCache<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> where TOptions : class
	{
		TOptions GetOrAdd(string? name, Func<TOptions> createOptions);

		bool TryAdd(string? name, TOptions options);

		bool TryRemove(string? name);

		void Clear();
	}
	public interface IOptionsSnapshot<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] out TOptions> : IOptions<TOptions> where TOptions : class
	{
		TOptions Get(string? name);
	}
	public interface IPostConfigureOptions<in TOptions> where TOptions : class
	{
		void PostConfigure(string? name, TOptions options);
	}
	public interface IStartupValidator
	{
		void Validate();
	}
	public interface IValidateOptions<TOptions> where TOptions : class
	{
		ValidateOptionsResult Validate(string? name, TOptions options);
	}
	public static class Options
	{
		internal const DynamicallyAccessedMemberTypes DynamicallyAccessedMembers = DynamicallyAccessedMemberTypes.PublicParameterlessConstructor;

		public static readonly string DefaultName = string.Empty;

		public static IOptions<TOptions> Create<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions>(TOptions options) where TOptions : class
		{
			return new OptionsWrapper<TOptions>(options);
		}
	}
	public class OptionsBuilder<TOptions> where TOptions : class
	{
		private const string DefaultValidationFailureMessage = "A validation error has occurred.";

		public string Name { get; }

		public IServiceCollection Services { get; }

		public OptionsBuilder(IServiceCollection services, string? name)
		{
			System.ThrowHelper.ThrowIfNull(services, "services");
			Services = services;
			Name = name ?? Options.DefaultName;
		}

		public virtual OptionsBuilder<TOptions> Configure(Action<TOptions> configureOptions)
		{
			System.ThrowHelper.ThrowIfNull(configureOptions, "configureOptions");
			Services.AddSingleton((IConfigureOptions<TOptions>)new ConfigureNamedOptions<TOptions>(Name, configureOptions));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Configure<TDep>(Action<TOptions, TDep> configureOptions) where TDep : class
		{
			Action<TOptions, TDep> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep>(Name, sp.GetRequiredService<TDep>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2>(Action<TOptions, TDep1, TDep2> configureOptions) where TDep1 : class where TDep2 : class
		{
			Action<TOptions, TDep1, TDep2> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2, TDep3>(Action<TOptions, TDep1, TDep2, TDep3> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class
		{
			Action<TOptions, TDep1, TDep2, TDep3> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2, TDep3, TDep4>(Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class
		{
			Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2, TDep3, TDep4, TDep5>(Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class
		{
			Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), sp.GetRequiredService<TDep5>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> PostConfigure(Action<TOptions> configureOptions)
		{
			System.ThrowHelper.ThrowIfNull(configureOptions, "configureOptions");
			Services.AddSingleton((IPostConfigureOptions<TOptions>)new PostConfigureOptions<TOptions>(Name, configureOptions));
			return this;
		}

		public virtual OptionsBuilder<TOptions> PostConfigure<TDep>(Action<TOptions, TDep> configureOptions) where TDep : class
		{
			Action<TOptions, TDep> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep>(Name, sp.GetRequiredService<TDep>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2>(Action<TOptions, TDep1, TDep2> configureOptions) where TDep1 : class where TDep2 : class
		{
			Action<TOptions, TDep1, TDep2> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3>(Action<TOptions, TDep1, TDep2, TDep3> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class
		{
			Action<TOptions, TDep1, TDep2, TDep3> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3, TDep4>(Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class
		{
			Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3, TDep4, TDep5>(Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class
		{
			Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions2 = configureOptions;
			System.ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions");
			Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), sp.GetRequiredService<TDep5>(), configureOptions2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Validate(Func<TOptions, bool> validation)
		{
			return Validate(validation, "A validation error has occurred.");
		}

		public virtual OptionsBuilder<TOptions> Validate(Func<TOptions, bool> validation, string failureMessage)
		{
			System.ThrowHelper.ThrowIfNull(validation, "validation");
			Services.AddSingleton((IValidateOptions<TOptions>)new ValidateOptions<TOptions>(Name, validation, failureMessage));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep>(Func<TOptions, TDep, bool> validation) where TDep : notnull
		{
			return Validate(validation, "A validation error has occurred.");
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep>(Func<TOptions, TDep, bool> validation, string failureMessage) where TDep : notnull
		{
			Func<TOptions, TDep, bool> validation2 = validation;
			string failureMessage2 = failureMessage;
			System.ThrowHelper.ThrowIfNull(validation2, "validation");
			Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep>(Name, sp.GetRequiredService<TDep>(), validation2, failureMessage2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2>(Func<TOptions, TDep1, TDep2, bool> validation) where TDep1 : notnull where TDep2 : notnull
		{
			return Validate(validation, "A validation error has occurred.");
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2>(Func<TOptions, TDep1, TDep2, bool> validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull
		{
			Func<TOptions, TDep1, TDep2, bool> validation2 = validation;
			string failureMessage2 = failureMessage;
			System.ThrowHelper.ThrowIfNull(validation2, "validation");
			Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), validation2, failureMessage2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3>(Func<TOptions, TDep1, TDep2, TDep3, bool> validation) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull
		{
			return Validate(validation, "A validation error has occurred.");
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3>(Func<TOptions, TDep1, TDep2, TDep3, bool> validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull
		{
			Func<TOptions, TDep1, TDep2, TDep3, bool> validation2 = validation;
			string failureMessage2 = failureMessage;
			System.ThrowHelper.ThrowIfNull(validation2, "validation");
			Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2, TDep3>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), validation2, failureMessage2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull
		{
			return Validate(validation, "A validation error has occurred.");
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull
		{
			Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation2 = validation;
			string failureMessage2 = failureMessage;
			System.ThrowHelper.ThrowIfNull(validation2, "validation");
			Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), validation2, failureMessage2)));
			return this;
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4, TDep5>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> validation) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull where TDep5 : notnull
		{
			return Validate(validation, "A validation error has occurred.");
		}

		public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4, TDep5>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull where TDep5 : notnull
		{
			Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> validation2 = validation;
			string failureMessage2 = failureMessage;
			System.ThrowHelper.ThrowIfNull(validation2, "validation");
			Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), sp.GetRequiredService<TDep5>(), validation2, failureMessage2)));
			return this;
		}
	}
	public class OptionsCache<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptionsMonitorCache<TOptions> where TOptions : class
	{
		private readonly ConcurrentDictionary<string, Lazy<TOptions>> _cache = new ConcurrentDictionary<string, Lazy<TOptions>>(1, 31, StringComparer.Ordinal);

		public void Clear()
		{
			_cache.Clear();
		}

		public virtual TOptions GetOrAdd(string? name, Func<TOptions> createOptions)
		{
			System.ThrowHelper.ThrowIfNull(createOptions, "createOptions");
			if (name == null)
			{
				name = Options.DefaultName;
			}
			return _cache.GetOrAdd(name, (string name, Func<TOptions> createOptions) => new Lazy<TOptions>(createOptions), createOptions).Value;
		}

		internal TOptions GetOrAdd<TArg>(string? name, Func<string, TArg, TOptions> createOptions, TArg factoryArgument)
		{
			if (GetType() != typeof(OptionsCache<TOptions>))
			{
				string localName = name;
				Func<string, TArg, TOptions> localCreateOptions = createOptions;
				TArg localFactoryArgument = factoryArgument;
				return GetOrAdd(name, () => localCreateOptions(localName ?? Options.DefaultName, localFactoryArgument));
			}
			return _cache.GetOrAdd(name ?? Options.DefaultName, (string name, (Func<string, TArg, TOptions> createOptions, TArg factoryArgument) arg) => new Lazy<TOptions>(() => arg.createOptions(name, arg.factoryArgument)), (createOptions, factoryArgument)).Value;
		}

		internal bool TryGetValue(string? name, [MaybeNullWhen(false)] out TOptions options)
		{
			if (_cache.TryGetValue(name ?? Options.DefaultName, out var value))
			{
				options = value.Value;
				return true;
			}
			options = null;
			return false;
		}

		public virtual bool TryAdd(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			return _cache.TryAdd(name ?? Options.DefaultName, new Lazy<TOptions>(options));
		}

		public virtual bool TryRemove(string? name)
		{
			Lazy<TOptions> value;
			return _cache.TryRemove(name ?? Options.DefaultName, out value);
		}
	}
	public class OptionsFactory<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptionsFactory<TOptions> where TOptions : class
	{
		private readonly IConfigureOptions<TOptions>[] _setups;

		private readonly IPostConfigureOptions<TOptions>[] _postConfigures;

		private readonly IValidateOptions<TOptions>[] _validations;

		public OptionsFactory(IEnumerable<IConfigureOptions<TOptions>> setups, IEnumerable<IPostConfigureOptions<TOptions>> postConfigures)
			: this(setups, postConfigures, (IEnumerable<IValidateOptions<TOptions>>)Array.Empty<IValidateOptions<TOptions>>())
		{
		}

		public OptionsFactory(IEnumerable<IConfigureOptions<TOptions>> setups, IEnumerable<IPostConfigureOptions<TOptions>> postConfigures, IEnumerable<IValidateOptions<TOptions>> validations)
		{
			_setups = (setups as IConfigureOptions<TOptions>[]) ?? new List<IConfigureOptions<TOptions>>(setups).ToArray();
			_postConfigures = (postConfigures as IPostConfigureOptions<TOptions>[]) ?? new List<IPostConfigureOptions<TOptions>>(postConfigures).ToArray();
			_validations = (validations as IValidateOptions<TOptions>[]) ?? new List<IValidateOptions<TOptions>>(validations).ToArray();
		}

		public TOptions Create(string name)
		{
			TOptions val = CreateInstance(name);
			IConfigureOptions<TOptions>[] setups = _setups;
			foreach (IConfigureOptions<TOptions> configureOptions in setups)
			{
				if (configureOptions is IConfigureNamedOptions<TOptions> configureNamedOptions)
				{
					configureNamedOptions.Configure(name, val);
				}
				else if (name == Options.DefaultName)
				{
					configureOptions.Configure(val);
				}
			}
			IPostConfigureOptions<TOptions>[] postConfigures = _postConfigures;
			for (int i = 0; i < postConfigures.Length; i++)
			{
				postConfigures[i].PostConfigure(name, val);
			}
			if (_validations.Length != 0)
			{
				List<string> list = new List<string>();
				IValidateOptions<TOptions>[] validations = _validations;
				for (int i = 0; i < validations.Length; i++)
				{
					ValidateOptionsResult validateOptionsResult = validations[i].Validate(name, val);
					if (validateOptionsResult != null && validateOptionsResult.Failed)
					{
						list.AddRange(validateOptionsResult.Failures);
					}
				}
				if (list.Count > 0)
				{
					throw new OptionsValidationException(name, typeof(TOptions), list);
				}
			}
			return val;
		}

		protected virtual TOptions CreateInstance(string name)
		{
			return Activator.CreateInstance<TOptions>();
		}
	}
	public class OptionsManager<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptions<TOptions>, IOptionsSnapshot<TOptions> where TOptions : class
	{
		private readonly IOptionsFactory<TOptions> _factory;

		private readonly OptionsCache<TOptions> _cache = new OptionsCache<TOptions>();

		public TOptions Value => Get(Options.DefaultName);

		public OptionsManager(IOptionsFactory<TOptions> factory)
		{
			_factory = factory;
		}

		public virtual TOptions Get(string? name)
		{
			if (name == null)
			{
				name = Options.DefaultName;
			}
			if (!_cache.TryGetValue(name, out var options))
			{
				IOptionsFactory<TOptions> localFactory = _factory;
				string localName = name;
				return _cache.GetOrAdd(name, () => localFactory.Create(localName));
			}
			return options;
		}
	}
	public class OptionsMonitor<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptionsMonitor<TOptions>, IDisposable where TOptions : class
	{
		internal sealed class ChangeTrackerDisposable : IDisposable
		{
			private readonly Action<TOptions, string> _listener;

			private readonly OptionsMonitor<TOptions> _monitor;

			public ChangeTrackerDisposable(OptionsMonitor<TOptions> monitor, Action<TOptions, string> listener)
			{
				_listener = listener;
				_monitor = monitor;
			}

			public void OnChange(TOptions options, string name)
			{
				_listener(options, name);
			}

			public void Dispose()
			{
				_monitor._onChange -= OnChange;
			}
		}

		private readonly IOptionsMonitorCache<TOptions> _cache;

		private readonly IOptionsFactory<TOptions> _factory;

		private readonly List<IDisposable> _registrations = new List<IDisposable>();

		public TOptions CurrentValue => Get(Options.DefaultName);

		internal event Action<TOptions, string>? _onChange;

		public OptionsMonitor(IOptionsFactory<TOptions> factory, IEnumerable<IOptionsChangeTokenSource<TOptions>> sources, IOptionsMonitorCache<TOptions> cache)
		{
			_factory = factory;
			_cache = cache;
			if (sources is IOptionsChangeTokenSource<TOptions>[] array)
			{
				IOptionsChangeTokenSource<TOptions>[] array2 = array;
				foreach (IOptionsChangeTokenSource<TOptions> source2 in array2)
				{
					RegisterSource(source2);
					void RegisterSource(IOptionsChangeTokenSource<TOptions> source)
					{
						IDisposable item = ChangeToken.OnChange(source.GetChangeToken, InvokeChanged, source.Name);
						_registrations.Add(item);
					}
				}
				return;
			}
			foreach (IOptionsChangeTokenSource<TOptions> source3 in sources)
			{
				RegisterSource(source3);
			}
		}

		private void InvokeChanged(string name)
		{
			if (name == null)
			{
				name = Options.DefaultName;
			}
			_cache.TryRemove(name);
			TOptions arg = Get(name);
			this._onChange?.Invoke(arg, name);
		}

		public virtual TOptions Get(string? name)
		{
			if (!(_cache is OptionsCache<TOptions> optionsCache))
			{
				string localName = name ?? Options.DefaultName;
				IOptionsFactory<TOptions> localFactory = _factory;
				return _cache.GetOrAdd(localName, () => localFactory.Create(localName));
			}
			return optionsCache.GetOrAdd(name, (string name, IOptionsFactory<TOptions> factory) => factory.Create(name), _factory);
		}

		public IDisposable OnChange(Action<TOptions, string> listener)
		{
			ChangeTrackerDisposable changeTrackerDisposable = new ChangeTrackerDisposable(this, listener);
			_onChange += changeTrackerDisposable.OnChange;
			return changeTrackerDisposable;
		}

		public void Dispose()
		{
			foreach (IDisposable registration in _registrations)
			{
				registration.Dispose();
			}
			_registrations.Clear();
		}
	}
	public static class OptionsMonitorExtensions
	{
		public static IDisposable? OnChange<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions>(this IOptionsMonitor<TOptions> monitor, Action<TOptions> listener)
		{
			Action<TOptions> listener2 = listener;
			return monitor.OnChange(delegate(TOptions o, string _)
			{
				listener2(o);
			});
		}
	}
	public class OptionsValidationException : Exception
	{
		public string OptionsName { get; }

		public Type OptionsType { get; }

		public IEnumerable<string> Failures { get; }

		public override string Message => string.Join("; ", Failures);

		public OptionsValidationException(string optionsName, Type optionsType, IEnumerable<string>? failureMessages)
		{
			System.ThrowHelper.ThrowIfNull(optionsName, "optionsName");
			System.ThrowHelper.ThrowIfNull(optionsType, "optionsType");
			Failures = failureMessages ?? new List<string>();
			OptionsType = optionsType;
			OptionsName = optionsName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
	public sealed class OptionsValidatorAttribute : Attribute
	{
	}
	public class OptionsWrapper<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptions<TOptions> where TOptions : class
	{
		public TOptions Value { get; }

		public OptionsWrapper(TOptions options)
		{
			Value = options;
		}
	}
	public class PostConfigureOptions<TOptions> : IPostConfigureOptions<TOptions> where TOptions : class
	{
		public string? Name { get; }

		public Action<TOptions>? Action { get; }

		public PostConfigureOptions(string? name, Action<TOptions>? action)
		{
			Name = name;
			Action = action;
		}

		public virtual void PostConfigure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options);
			}
		}
	}
	public class PostConfigureOptions<TOptions, TDep> : IPostConfigureOptions<TOptions> where TOptions : class where TDep : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep>? Action { get; }

		public TDep Dependency { get; }

		public PostConfigureOptions(string? name, TDep dependency, Action<TOptions, TDep>? action)
		{
			Name = name;
			Action = action;
			Dependency = dependency;
		}

		public virtual void PostConfigure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency);
			}
		}

		public void PostConfigure(TOptions options)
		{
			PostConfigure(Options.DefaultName, options);
		}
	}
	public class PostConfigureOptions<TOptions, TDep1, TDep2> : IPostConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep1, TDep2>? Action { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public PostConfigureOptions(string? name, TDep1 dependency, TDep2 dependency2, Action<TOptions, TDep1, TDep2>? action)
		{
			Name = name;
			Action = action;
			Dependency1 = dependency;
			Dependency2 = dependency2;
		}

		public virtual void PostConfigure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency1, Dependency2);
			}
		}

		public void PostConfigure(TOptions options)
		{
			PostConfigure(Options.DefaultName, options);
		}
	}
	public class PostConfigureOptions<TOptions, TDep1, TDep2, TDep3> : IPostConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep1, TDep2, TDep3>? Action { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public TDep3 Dependency3 { get; }

		public PostConfigureOptions(string? name, TDep1 dependency, TDep2 dependency2, TDep3 dependency3, Action<TOptions, TDep1, TDep2, TDep3>? action)
		{
			Name = name;
			Action = action;
			Dependency1 = dependency;
			Dependency2 = dependency2;
			Dependency3 = dependency3;
		}

		public virtual void PostConfigure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency1, Dependency2, Dependency3);
			}
		}

		public void PostConfigure(TOptions options)
		{
			PostConfigure(Options.DefaultName, options);
		}
	}
	public class PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4> : IPostConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep1, TDep2, TDep3, TDep4>? Action { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public TDep3 Dependency3 { get; }

		public TDep4 Dependency4 { get; }

		public PostConfigureOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Action<TOptions, TDep1, TDep2, TDep3, TDep4>? action)
		{
			Name = name;
			Action = action;
			Dependency1 = dependency1;
			Dependency2 = dependency2;
			Dependency3 = dependency3;
			Dependency4 = dependency4;
		}

		public virtual void PostConfigure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4);
			}
		}

		public void PostConfigure(TOptions options)
		{
			PostConfigure(Options.DefaultName, options);
		}
	}
	public class PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> : IPostConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class
	{
		public string? Name { get; }

		public Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>? Action { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public TDep3 Dependency3 { get; }

		public TDep4 Dependency4 { get; }

		public TDep5 Dependency5 { get; }

		public PostConfigureOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, TDep5 dependency5, Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>? action)
		{
			Name = name;
			Action = action;
			Dependency1 = dependency1;
			Dependency2 = dependency2;
			Dependency3 = dependency3;
			Dependency4 = dependency4;
			Dependency5 = dependency5;
		}

		public virtual void PostConfigure(string? name, TOptions options)
		{
			System.ThrowHelper.ThrowIfNull(options, "options");
			if (Name == null || name == Name)
			{
				Action?.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4, Dependency5);
			}
		}

		public void PostConfigure(TOptions options)
		{
			PostConfigure(Options.DefaultName, options);
		}
	}
	internal sealed class StartupValidatorOptions
	{
		public Dictionary<(Type, string), Action> _validators { get; } = new Dictionary<(Type, string), Action>();

	}
	internal sealed class UnnamedOptionsManager<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptions<TOptions> where TOptions : class
	{
		private readonly IOptionsFactory<TOptions> _factory;

		private object _syncObj;

		private volatile TOptions _value;

		public TOptions Value
		{
			get
			{
				TOptions value = _value;
				if (value != null)
				{
					return value;
				}
				lock (_syncObj ?? Interlocked.CompareExchange(ref _syncObj, new object(), null) ?? _syncObj)
				{
					return _value ?? (_value = _factory.Create(Options.DefaultName));
				}
			}
		}

		public UnnamedOptionsManager(IOptionsFactory<TOptions> factory)
		{
			_factory = factory;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
	public sealed class ValidateEnumeratedItemsAttribute : Attribute
	{
		public Type? Validator { get; }

		public ValidateEnumeratedItemsAttribute()
		{
		}

		public ValidateEnumeratedItemsAttribute(Type validator)
		{
			Validator = validator;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
	public sealed class ValidateObjectMembersAttribute : Attribute
	{
		public Type? Validator { get; }

		public ValidateObjectMembersAttribute()
		{
		}

		public ValidateObjectMembersAttribute(Type validator)
		{
			Validator = validator;
		}
	}
	internal sealed class StartupValidator : IStartupValidator
	{
		private readonly StartupValidatorOptions _validatorOptions;

		public StartupValidator(IOptions<StartupValidatorOptions> validators)
		{
			_validatorOptions = validators.Value;
		}

		public void Validate()
		{
			List<Exception> list = null;
			foreach (Action value in _validatorOptions._validators.Values)
			{
				try
				{
					value();
				}
				catch (OptionsValidationException item)
				{
					if (list == null)
					{
						list = new List<Exception>();
					}
					list.Add(item);
				}
			}
			if (list != null)
			{
				if (list.Count == 1)
				{
					ExceptionDispatchInfo.Capture(list[0]).Throw();
				}
				if (list.Count > 1)
				{
					throw new AggregateException(list);
				}
			}
		}
	}
	public class ValidateOptions<TOptions> : IValidateOptions<TOptions> where TOptions : class
	{
		public string? Name { get; }

		public Func<TOptions, bool> Validation { get; }

		public string FailureMessage { get; }

		public ValidateOptions(string? name, Func<TOptions, bool> validation, string failureMessage)
		{
			System.ThrowHelper.ThrowIfNull(validation, "validation");
			Name = name;
			Validation = validation;
			FailureMessage = failureMessage;
		}

		public ValidateOptionsResult Validate(string? name, TOptions options)
		{
			if (Name == null || name == Name)
			{
				if (Validation(options))
				{
					return ValidateOptionsResult.Success;
				}
				return ValidateOptionsResult.Fail(FailureMessage);
			}
			return ValidateOptionsResult.Skip;
		}
	}
	public class ValidateOptions<TOptions, TDep> : IValidateOptions<TOptions> where TOptions : class
	{
		public string? Name { get; }

		public Func<TOptions, TDep, bool> Validation { get; }

		public string FailureMessage { get; }

		public TDep Dependency { get; }

		public ValidateOptions(string? name, TDep dependency, Func<TOptions, TDep, bool> validation, string failureMessage)
		{
			System.ThrowHelper.ThrowIfNull(validation, "validation");
			Name = name;
			Validation = validation;
			FailureMessage = failureMessage;
			Dependency = dependency;
		}

		public ValidateOptionsResult Validate(string? name, TOptions options)
		{
			if (Name == null || name == Name)
			{
				if (Validation(options, Dependency))
				{
					return ValidateOptionsResult.Success;
				}
				return ValidateOptionsResult.Fail(FailureMessage);
			}
			return ValidateOptionsResult.Skip;
		}
	}
	public class ValidateOptions<TOptions, TDep1, TDep2> : IValidateOptions<TOptions> where TOptions : class
	{
		public string? Name { get; }

		public Func<TOptions, TDep1, TDep2, bool> Validation { get; }

		public string FailureMessage { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, Func<TOptions, TDep1, TDep2, bool> validation, string failureMessage)
		{
			System.ThrowHelper.ThrowIfNull(validation, "validation");
			Name = name;
			Validation = validation;
			FailureMessage = failureMessage;
			Dependency1 = dependency1;
			Dependency2 = dependency2;
		}

		public ValidateOptionsResult Validate(string? name, TOptions options)
		{
			if (Name == null || name == Name)
			{
				if (Validation(options, Dependency1, Dependency2))
				{
					return ValidateOptionsResult.Success;
				}
				return ValidateOptionsResult.Fail(FailureMessage);
			}
			return ValidateOptionsResult.Skip;
		}
	}
	public class ValidateOptions<TOptions, TDep1, TDep2, TDep3> : IValidateOptions<TOptions> where TOptions : class
	{
		public string? Name { get; }

		public Func<TOptions, TDep1, TDep2, TDep3, bool> Validation { get; }

		public string FailureMessage { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public TDep3 Dependency3 { get; }

		public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, Func<TOptions, TDep1, TDep2, TDep3, bool> validation, string failureMessage)
		{
			System.ThrowHelper.ThrowIfNull(validation, "validation");
			Name = name;
			Validation = validation;
			FailureMessage = failureMessage;
			Dependency1 = dependency1;
			Dependency2 = dependency2;
			Dependency3 = dependency3;
		}

		public ValidateOptionsResult Validate(string? name, TOptions options)
		{
			if (Name == null || name == Name)
			{
				if (Validation(options, Dependency1, Dependency2, Dependency3))
				{
					return ValidateOptionsResult.Success;
				}
				return ValidateOptionsResult.Fail(FailureMessage);
			}
			return ValidateOptionsResult.Skip;
		}
	}
	public class ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4> : IValidateOptions<TOptions> where TOptions : class
	{
		public string? Name { get; }

		public Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> Validation { get; }

		public string FailureMessage { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public TDep3 Dependency3 { get; }

		public TDep4 Dependency4 { get; }

		public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation, string failureMessage)
		{
			System.ThrowHelper.ThrowIfNull(validation, "validation");
			Name = name;
			Validation = validation;
			FailureMessage = failureMessage;
			Dependency1 = dependency1;
			Dependency2 = dependency2;
			Dependency3 = dependency3;
			Dependency4 = dependency4;
		}

		public ValidateOptionsResult Validate(string? name, TOptions options)
		{
			if (Name == null || name == Name)
			{
				if (Validation(options, Dependency1, Dependency2, Dependency3, Dependency4))
				{
					return ValidateOptionsResult.Success;
				}
				return ValidateOptionsResult.Fail(FailureMessage);
			}
			return ValidateOptionsResult.Skip;
		}
	}
	public class ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> : IValidateOptions<TOptions> where TOptions : class
	{
		public string? Name { get; }

		public Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> Validation { get; }

		public string FailureMessage { get; }

		public TDep1 Dependency1 { get; }

		public TDep2 Dependency2 { get; }

		public TDep3 Dependency3 { get; }

		public TDep4 Dependency4 { get; }

		public TDep5 Dependency5 { get; }

		public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, TDep5 dependency5, Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> validation, string failureMessage)
		{
			System.ThrowHelper.ThrowIfNull(validation, "validation");
			Name = name;
			Validation = validation;
			FailureMessage = failureMessage;
			Dependency1 = dependency1;
			Dependency2 = dependency2;
			Dependency3 = dependency3;
			Dependency4 = dependency4;
			Dependency5 = dependency5;
		}

		public ValidateOptionsResult Validate(string? name, TOptions options)
		{
			if (Name == null || name == Name)
			{
				if (Validation(options, Dependency1, Dependency2, Dependency3, Dependency4, Dependency5))
				{
					return ValidateOptionsResult.Success;
				}
				return ValidateOptionsResult.Fail(FailureMessage);
			}
			return ValidateOptionsResult.Skip;
		}
	}
	public class ValidateOptionsResult
	{
		public static readonly ValidateOptionsResult Skip = new ValidateOptionsResult
		{
			Skipped = true
		};

		public static readonly ValidateOptionsResult Success = new ValidateOptionsResult
		{
			Succeeded = true
		};

		public bool Succeeded { get; protected set; }

		public bool Skipped { get; protected set; }

		[MemberNotNullWhen(true, "Failures")]
		[MemberNotNullWhen(true, "FailureMessage")]
		public bool Failed
		{
			[MemberNotNullWhen(true, "Failures")]
			[MemberNotNullWhen(true, "FailureMessage")]
			get;
			[MemberNotNullWhen(true, "Failures")]
			[MemberNotNullWhen(true, "FailureMessage")]
			protected set;
		}

		public string? FailureMessage { get; protected set; }

		public IEnumerable<string>? Failures { get; protected set; }

		public static ValidateOptionsResult Fail(string failureMessage)
		{
			ValidateOptionsResult validateOptionsResult = new ValidateOptionsResult();
			validateOptionsResult.Failed = true;
			validateOptionsResult.FailureMessage = failureMessage;
			validateOptionsResult.Failures = new string[1] { failureMessage };
			return validateOptionsResult;
		}

		public static ValidateOptionsResult Fail(IEnumerable<string> failures)
		{
			return new ValidateOptionsResult
			{
				Failed = true,
				FailureMessage = string.Join("; ", failures),
				Failures = failures
			};
		}
	}
	[DebuggerDisplay("{ErrorsCount} errors")]
	public class ValidateOptionsResultBuilder
	{
		private const string MemberSeparatorString = ", ";

		private List<string> _errors;

		private int ErrorsCount
		{
			get
			{
				if (_errors != null)
				{
					return _errors.Count;
				}
				return 0;
			}
		}

		private List<string> Errors => _errors ?? (_errors = new List<string>());

		public void AddError(string error, string? propertyName = null)
		{
			System.ThrowHelper.ThrowIfNull(error, "error");
			Errors.Add((propertyName == null) ? error : ("Property " + propertyName + ": " + error));
		}

		public void AddResult(ValidationResult? result)
		{
			if (result?.ErrorMessage != null)
			{
				string text = string.Join(", ", result.MemberNames);
				Errors.Add((text.Length != 0) ? (text + ": " + result.ErrorMessage) : result.ErrorMessage);
			}
		}

		public void AddResults(IEnumerable<ValidationResult?>? results)
		{
			if (results == null)
			{
				return;
			}
			foreach (ValidationResult result in results)
			{
				AddResult(result);
			}
		}

		public void AddResult(ValidateOptionsResult result)
		{
			System.ThrowHelper.ThrowIfNull(result, "result");
			if (!result.Failed)
			{
				return;
			}
			if (result.Failures == null)
			{
				Errors.Add(result.FailureMessage);
				return;
			}
			foreach (string failure in result.Failures)
			{
				if (failure != null)
				{
					Errors.Add(failure);
				}
			}
		}

		public ValidateOptionsResult Build()
		{
			List<string> errors = _errors;
			if (errors != null && errors.Count > 0)
			{
				return ValidateOptionsResult.Fail(_errors);
			}
			return ValidateOptionsResult.Success;
		}

		public void Clear()
		{
			_errors?.Clear();
		}
	}
}

Microsoft.Extensions.Primitives.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using FxResources.Microsoft.Extensions.Primitives;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Primitives")]
[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("Primitives shared by framework extensions. Commonly used types include:\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Primitives.IChangeToken\r\nMicrosoft.Extensions.Primitives.StringValues\r\nMicrosoft.Extensions.Primitives.StringSegment")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Primitives")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
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]
	internal sealed class IsByRefLikeAttribute : 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.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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.Microsoft.Extensions.Primitives
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Argument_InvalidOffsetLength => GetResourceString("Argument_InvalidOffsetLength");

		internal static string Argument_InvalidOffsetLengthStringSegment => GetResourceString("Argument_InvalidOffsetLengthStringSegment");

		internal static string Capacity_CannotChangeAfterWriteStarted => GetResourceString("Capacity_CannotChangeAfterWriteStarted");

		internal static string Capacity_NotEnough => GetResourceString("Capacity_NotEnough");

		internal static string Capacity_NotUsedEntirely => GetResourceString("Capacity_NotUsedEntirely");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.Text
{
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public unsafe void Append(char* value, int length)
		{
			if (_pos > _chars.Length - length)
			{
				Grow(length);
			}
			Span<char> span = _chars.Slice(_pos, length);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = *(value++);
			}
			_pos += length;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
}
namespace System.Numerics.Hashing
{
	internal static class HashHelpers
	{
		public static int Combine(int h1, int h2)
		{
			return (((h1 << 5) | (h1 >>> 27)) + h1) ^ h2;
		}
	}
}
namespace Microsoft.Extensions.FileProviders
{
	internal sealed class EmptyDisposable : IDisposable
	{
		public static EmptyDisposable Instance { get; } = new EmptyDisposable();


		private EmptyDisposable()
		{
		}

		public void Dispose()
		{
		}
	}
}
namespace Microsoft.Extensions.Internal
{
	internal static class ChangeCallbackRegistrar
	{
		internal static IDisposable UnsafeRegisterChangeCallback<T>(Action<object> callback, object state, CancellationToken token, Action<T> onFailure, T onFailureState)
		{
			bool flag = false;
			if (!ExecutionContext.IsFlowSuppressed())
			{
				ExecutionContext.SuppressFlow();
				flag = true;
			}
			try
			{
				return token.Register(callback, state);
			}
			catch (ObjectDisposedException)
			{
				onFailure(onFailureState);
			}
			finally
			{
				if (flag)
				{
					ExecutionContext.RestoreFlow();
				}
			}
			return EmptyDisposable.Instance;
		}
	}
}
namespace Microsoft.Extensions.Primitives
{
	[DebuggerDisplay("HasChanged = {HasChanged}")]
	public class CancellationChangeToken : IChangeToken
	{
		public bool ActiveChangeCallbacks { get; private set; } = true;


		public bool HasChanged => Token.IsCancellationRequested;

		private CancellationToken Token { get; }

		public CancellationChangeToken(CancellationToken cancellationToken)
		{
			Token = cancellationToken;
		}

		public IDisposable RegisterChangeCallback(Action<object?> callback, object? state)
		{
			return ChangeCallbackRegistrar.UnsafeRegisterChangeCallback(callback, state, Token, delegate(CancellationChangeToken s)
			{
				s.ActiveChangeCallbacks = false;
			}, this);
		}
	}
	public static class ChangeToken
	{
		private sealed class ChangeTokenRegistration<TState> : IDisposable
		{
			private sealed class NoopDisposable : IDisposable
			{
				public void Dispose()
				{
				}
			}

			private readonly Func<IChangeToken> _changeTokenProducer;

			private readonly Action<TState> _changeTokenConsumer;

			private readonly TState _state;

			private IDisposable _disposable;

			private static readonly NoopDisposable _disposedSentinel = new NoopDisposable();

			public ChangeTokenRegistration(Func<IChangeToken> changeTokenProducer, Action<TState> changeTokenConsumer, TState state)
			{
				_changeTokenProducer = changeTokenProducer;
				_changeTokenConsumer = changeTokenConsumer;
				_state = state;
				IChangeToken token = changeTokenProducer();
				RegisterChangeTokenCallback(token);
			}

			private void OnChangeTokenFired()
			{
				IChangeToken token = _changeTokenProducer();
				try
				{
					_changeTokenConsumer(_state);
				}
				finally
				{
					RegisterChangeTokenCallback(token);
				}
			}

			private void RegisterChangeTokenCallback(IChangeToken token)
			{
				if (token != null)
				{
					IDisposable disposable = token.RegisterChangeCallback(delegate(object s)
					{
						((ChangeTokenRegistration<TState>)s).OnChangeTokenFired();
					}, this);
					if (token.HasChanged && token.ActiveChangeCallbacks)
					{
						disposable?.Dispose();
					}
					else
					{
						SetDisposable(disposable);
					}
				}
			}

			private void SetDisposable(IDisposable disposable)
			{
				IDisposable disposable2 = Volatile.Read(ref _disposable);
				if (disposable2 == _disposedSentinel)
				{
					disposable.Dispose();
					return;
				}
				IDisposable disposable3 = Interlocked.CompareExchange(ref _disposable, disposable, disposable2);
				if (disposable3 == _disposedSentinel)
				{
					disposable.Dispose();
				}
				else if (disposable3 != disposable2)
				{
					throw new InvalidOperationException("Somebody else set the _disposable field");
				}
			}

			public void Dispose()
			{
				Interlocked.Exchange(ref _disposable, _disposedSentinel)?.Dispose();
			}
		}

		public static IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Action changeTokenConsumer)
		{
			if (changeTokenProducer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer);
			}
			if (changeTokenConsumer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer);
			}
			return new ChangeTokenRegistration<Action>(changeTokenProducer, delegate(Action callback)
			{
				callback();
			}, changeTokenConsumer);
		}

		public static IDisposable OnChange<TState>(Func<IChangeToken?> changeTokenProducer, Action<TState> changeTokenConsumer, TState state)
		{
			if (changeTokenProducer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer);
			}
			if (changeTokenConsumer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer);
			}
			return new ChangeTokenRegistration<TState>(changeTokenProducer, changeTokenConsumer, state);
		}
	}
	[DebuggerDisplay("HasChanged = {HasChanged}")]
	public class CompositeChangeToken : IChangeToken
	{
		private static readonly Action<object> _onChangeDelegate = OnChange;

		private readonly object _callbackLock = new object();

		private CancellationTokenSource _cancellationTokenSource;

		private List<IDisposable> _disposables;

		[MemberNotNullWhen(true, "_cancellationTokenSource")]
		[MemberNotNullWhen(true, "_disposables")]
		private bool RegisteredCallbackProxy
		{
			[MemberNotNullWhen(true, "_cancellationTokenSource")]
			[MemberNotNullWhen(true, "_disposables")]
			get;
			[MemberNotNullWhen(true, "_cancellationTokenSource")]
			[MemberNotNullWhen(true, "_disposables")]
			set;
		}

		public IReadOnlyList<IChangeToken> ChangeTokens { get; }

		public bool HasChanged
		{
			get
			{
				if (_cancellationTokenSource != null && _cancellationTokenSource.Token.IsCancellationRequested)
				{
					return true;
				}
				for (int i = 0; i < ChangeTokens.Count; i++)
				{
					if (ChangeTokens[i].HasChanged)
					{
						OnChange(this);
						return true;
					}
				}
				return false;
			}
		}

		public bool ActiveChangeCallbacks { get; }

		public CompositeChangeToken(IReadOnlyList<IChangeToken> changeTokens)
		{
			if (changeTokens == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokens);
			}
			ChangeTokens = changeTokens;
			for (int i = 0; i < ChangeTokens.Count; i++)
			{
				if (ChangeTokens[i].ActiveChangeCallbacks)
				{
					ActiveChangeCallbacks = true;
					break;
				}
			}
		}

		public IDisposable RegisterChangeCallback(Action<object?> callback, object? state)
		{
			EnsureCallbacksInitialized();
			return _cancellationTokenSource.Token.Register(callback, state);
		}

		[MemberNotNull("_cancellationTokenSource")]
		[MemberNotNull("_disposables")]
		private void EnsureCallbacksInitialized()
		{
			if (RegisteredCallbackProxy)
			{
				return;
			}
			lock (_callbackLock)
			{
				if (RegisteredCallbackProxy)
				{
					return;
				}
				_cancellationTokenSource = new CancellationTokenSource();
				_disposables = new List<IDisposable>();
				for (int i = 0; i < ChangeTokens.Count; i++)
				{
					if (ChangeTokens[i].ActiveChangeCallbacks)
					{
						IDisposable disposable = ChangeTokens[i].RegisterChangeCallback(_onChangeDelegate, this);
						if (_cancellationTokenSource.IsCancellationRequested)
						{
							disposable.Dispose();
							break;
						}
						_disposables.Add(disposable);
					}
				}
				RegisteredCallbackProxy = true;
			}
		}

		private static void OnChange(object state)
		{
			CompositeChangeToken compositeChangeToken = (CompositeChangeToken)state;
			if (compositeChangeToken._cancellationTokenSource == null)
			{
				return;
			}
			lock (compositeChangeToken._callbackLock)
			{
				if (compositeChangeToken._cancellationTokenSource.IsCancellationRequested)
				{
					return;
				}
				try
				{
					compositeChangeToken._cancellationTokenSource.Cancel();
				}
				catch
				{
				}
			}
			List<IDisposable> disposables = compositeChangeToken._disposables;
			for (int i = 0; i < disposables.Count; i++)
			{
				disposables[i].Dispose();
			}
		}
	}
	public static class Extensions
	{
		public static StringBuilder Append(this StringBuilder builder, StringSegment segment)
		{
			return builder.Append(segment.Buffer, segment.Offset, segment.Length);
		}
	}
	public interface IChangeToken
	{
		bool HasChanged { get; }

		bool ActiveChangeCallbacks { get; }

		IDisposable RegisterChangeCallback(Action<object?> callback, object? state);
	}
	[DebuggerDisplay("Value = {_value}")]
	[EditorBrowsable(EditorBrowsableState.Never)]
	[Obsolete("This type is retained only for compatibility. The recommended alternative is string.Create<TState> (int length, TState state, System.Buffers.SpanAction<char,TState> action).", true)]
	public struct InplaceStringBuilder
	{
		private int _offset;

		private int _capacity;

		private string _value;

		public int Capacity
		{
			get
			{
				return _capacity;
			}
			set
			{
				if (value < 0)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
				}
				if (_offset > 0)
				{
					ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_CannotChangeAfterWriteStarted);
				}
				_capacity = value;
			}
		}

		public InplaceStringBuilder(int capacity)
		{
			this = default(InplaceStringBuilder);
			if (capacity < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
			}
			_capacity = capacity;
		}

		public void Append(string? value)
		{
			if (value == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
			}
			Append(value, 0, value.Length);
		}

		public void Append(StringSegment segment)
		{
			Append(segment.Buffer, segment.Offset, segment.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Append(string? value, int offset, int count)
		{
			EnsureValueIsInitialized();
			if (value == null || offset < 0 || value.Length - offset < count || Capacity - _offset < count)
			{
				ThrowValidationError(value, offset, count);
			}
			fixed (char* ptr = _value)
			{
				fixed (char* ptr2 = value)
				{
					Unsafe.CopyBlockUnaligned(ptr + _offset, ptr2 + offset, (uint)(count * 2));
					_offset += count;
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Append(char c)
		{
			EnsureValueIsInitialized();
			if (_offset >= Capacity)
			{
				ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_NotEnough, 1, Capacity - _offset);
			}
			fixed (char* ptr = _value)
			{
				ptr[_offset++] = c;
			}
		}

		public override string? ToString()
		{
			if (Capacity != _offset)
			{
				ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_NotUsedEntirely, Capacity, _offset);
			}
			return _value;
		}

		private void EnsureValueIsInitialized()
		{
			if (_value == null)
			{
				_value = new string('\0', _capacity);
			}
		}

		private void ThrowValidationError(string value, int offset, int count)
		{
			if (value == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
			}
			if (offset < 0 || value.Length - offset < count)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset);
			}
			if (Capacity - _offset < count)
			{
				ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_NotEnough, value.Length, Capacity - _offset);
			}
		}
	}
	[DebuggerDisplay("{Value}")]
	public readonly struct StringSegment : IEquatable<StringSegment>, IEquatable<string?>
	{
		public static readonly StringSegment Empty = string.Empty;

		public string? Buffer { get; }

		public int Offset { get; }

		public int Length { get; }

		public string? Value
		{
			get
			{
				if (!HasValue)
				{
					return null;
				}
				return Buffer.Substring(Offset, Length);
			}
		}

		[MemberNotNullWhen(true, "Buffer")]
		[MemberNotNullWhen(true, "Value")]
		public bool HasValue
		{
			[MemberNotNullWhen(true, "Buffer")]
			[MemberNotNullWhen(true, "Value")]
			get
			{
				return Buffer != null;
			}
		}

		public char this[int index]
		{
			get
			{
				if ((uint)index >= (uint)Length)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
				}
				return Buffer[Offset + index];
			}
		}

		public StringSegment(string? buffer)
		{
			Buffer = buffer;
			Offset = 0;
			Length = buffer?.Length ?? 0;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public StringSegment(string buffer, int offset, int length)
		{
			if (buffer == null || (uint)offset > (uint)buffer.Length || (uint)length > (uint)(buffer.Length - offset))
			{
				ThrowInvalidArguments(buffer, offset, length);
			}
			Buffer = buffer;
			Offset = offset;
			Length = length;
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return Buffer.AsSpan(Offset, Length);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			if (!HasValue || start < 0)
			{
				ThrowInvalidArguments(start, Length - start, ExceptionArgument.start);
			}
			return Buffer.AsSpan(Offset + start, Length - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			if (!HasValue || start < 0 || length < 0 || (uint)(start + length) > (uint)Length)
			{
				ThrowInvalidArguments(start, length, ExceptionArgument.start);
			}
			return Buffer.AsSpan(Offset + start, length);
		}

		public ReadOnlyMemory<char> AsMemory()
		{
			return Buffer.AsMemory(Offset, Length);
		}

		public static int Compare(StringSegment a, StringSegment b, StringComparison comparisonType)
		{
			if (a.HasValue && b.HasValue)
			{
				return a.AsSpan().CompareTo(b.AsSpan(), comparisonType);
			}
			CheckStringComparison(comparisonType);
			if (a.HasValue)
			{
				return 1;
			}
			if (!b.HasValue)
			{
				return 0;
			}
			return -1;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is StringSegment other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(StringSegment other)
		{
			return Equals(other, StringComparison.Ordinal);
		}

		public bool Equals(StringSegment other, StringComparison comparisonType)
		{
			if (HasValue && other.HasValue)
			{
				return MemoryExtensions.Equals(AsSpan(), other.AsSpan(), comparisonType);
			}
			CheckStringComparison(comparisonType);
			if (!HasValue)
			{
				return !other.HasValue;
			}
			return false;
		}

		public static bool Equals(StringSegment a, StringSegment b, StringComparison comparisonType)
		{
			return a.Equals(b, comparisonType);
		}

		public bool Equals(string? text)
		{
			return Equals(text, StringComparison.Ordinal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool Equals(string? text, StringComparison comparisonType)
		{
			if (!HasValue || text == null)
			{
				CheckStringComparison(comparisonType);
				return text == Buffer;
			}
			return MemoryExtensions.Equals(AsSpan(), text.AsSpan(), comparisonType);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override int GetHashCode()
		{
			return Value?.GetHashCode() ?? 0;
		}

		public static bool operator ==(StringSegment left, StringSegment right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(StringSegment left, StringSegment right)
		{
			return !left.Equals(right);
		}

		public static implicit operator StringSegment(string? value)
		{
			return new StringSegment(value);
		}

		public static implicit operator ReadOnlySpan<char>(StringSegment segment)
		{
			return segment.AsSpan();
		}

		public static implicit operator ReadOnlyMemory<char>(StringSegment segment)
		{
			return segment.AsMemory();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool StartsWith(string text, StringComparison comparisonType)
		{
			if (text == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
			}
			if (!HasValue)
			{
				CheckStringComparison(comparisonType);
				return false;
			}
			return AsSpan().StartsWith(text.AsSpan(), comparisonType);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool EndsWith(string text, StringComparison comparisonType)
		{
			if (text == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
			}
			if (!HasValue)
			{
				CheckStringComparison(comparisonType);
				return false;
			}
			return AsSpan().EndsWith(text.AsSpan(), comparisonType);
		}

		public string Substring(int offset)
		{
			return Substring(offset, Length - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public string Substring(int offset, int length)
		{
			if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length)
			{
				ThrowInvalidArguments(offset, length, ExceptionArgument.offset);
			}
			return Buffer.Substring(Offset + offset, length);
		}

		public StringSegment Subsegment(int offset)
		{
			return Subsegment(offset, Length - offset);
		}

		public StringSegment Subsegment(int offset, int length)
		{
			if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length)
			{
				ThrowInvalidArguments(offset, length, ExceptionArgument.offset);
			}
			return new StringSegment(Buffer, Offset + offset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public int IndexOf(char c, int start, int count)
		{
			int num = -1;
			if (HasValue)
			{
				if ((uint)start > (uint)Length)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
				}
				if ((uint)count > (uint)(Length - start))
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count);
				}
				num = AsSpan(start, count).IndexOf(c);
				if (num >= 0)
				{
					num += start;
				}
			}
			return num;
		}

		public int IndexOf(char c, int start)
		{
			return IndexOf(c, start, Length - start);
		}

		public int IndexOf(char c)
		{
			return IndexOf(c, 0, Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public int IndexOfAny(char[] anyOf, int startIndex, int count)
		{
			int num = -1;
			if (HasValue)
			{
				if ((uint)startIndex > (uint)Length)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
				}
				if ((uint)count > (uint)(Length - startIndex))
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count);
				}
				num = Buffer.IndexOfAny(anyOf, Offset + startIndex, count);
				if (num != -1)
				{
					num -= Offset;
				}
			}
			return num;
		}

		public int IndexOfAny(char[] anyOf, int startIndex)
		{
			return IndexOfAny(anyOf, startIndex, Length - startIndex);
		}

		public int IndexOfAny(char[] anyOf)
		{
			return IndexOfAny(anyOf, 0, Length);
		}

		public int LastIndexOf(char value)
		{
			return AsSpan().LastIndexOf(value);
		}

		public StringSegment Trim()
		{
			return TrimStart().TrimEnd();
		}

		public StringSegment TrimStart()
		{
			ReadOnlySpan<char> readOnlySpan = AsSpan();
			int i;
			for (i = 0; i < readOnlySpan.Length && char.IsWhiteSpace(readOnlySpan[i]); i++)
			{
			}
			return Subsegment(i);
		}

		public StringSegment TrimEnd()
		{
			ReadOnlySpan<char> readOnlySpan = AsSpan();
			int num = readOnlySpan.Length - 1;
			while (num >= 0 && char.IsWhiteSpace(readOnlySpan[num]))
			{
				num--;
			}
			return Subsegment(0, num + 1);
		}

		public StringTokenizer Split(char[] chars)
		{
			return new StringTokenizer(this, chars);
		}

		public static bool IsNullOrEmpty(StringSegment value)
		{
			bool result = false;
			if (!value.HasValue || value.Length == 0)
			{
				result = true;
			}
			return result;
		}

		public override string ToString()
		{
			return Value ?? string.Empty;
		}

		private static void CheckStringComparison(StringComparison comparisonType)
		{
			if ((uint)comparisonType > 5u)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.comparisonType);
			}
		}

		[DoesNotReturn]
		private static void ThrowInvalidArguments(string buffer, int offset, int length)
		{
			throw GetInvalidArgumentsException();
			Exception GetInvalidArgumentsException()
			{
				if (buffer == null)
				{
					return ThrowHelper.GetArgumentNullException(ExceptionArgument.buffer);
				}
				if (offset < 0)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.offset);
				}
				if (length < 0)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length);
				}
				return ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLength);
			}
		}

		[DoesNotReturn]
		private void ThrowInvalidArguments(int offset, int length, ExceptionArgument offsetOrStart)
		{
			throw GetInvalidArgumentsException(HasValue);
			Exception GetInvalidArgumentsException(bool hasValue)
			{
				if (!hasValue)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart);
				}
				if (offset < 0)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart);
				}
				if (length < 0)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length);
				}
				return ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLengthStringSegment);
			}
		}
	}
	public class StringSegmentComparer : IComparer<StringSegment>, IEqualityComparer<StringSegment>
	{
		public static StringSegmentComparer Ordinal { get; } = new StringSegmentComparer(StringComparison.Ordinal, StringComparer.Ordinal);


		public static StringSegmentComparer OrdinalIgnoreCase { get; } = new StringSegmentComparer(StringComparison.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase);


		private StringComparison Comparison { get; }

		private StringComparer Comparer { get; }

		private StringSegmentComparer(StringComparison comparison, StringComparer comparer)
		{
			Comparison = comparison;
			Comparer = comparer;
		}

		public int Compare(StringSegment x, StringSegment y)
		{
			return StringSegment.Compare(x, y, Comparison);
		}

		public bool Equals(StringSegment x, StringSegment y)
		{
			return StringSegment.Equals(x, y, Comparison);
		}

		public int GetHashCode(StringSegment obj)
		{
			if (!obj.HasValue)
			{
				return 0;
			}
			return Comparer.GetHashCode(obj.Value);
		}
	}
	public readonly struct StringTokenizer : IEnumerable<StringSegment>, IEnumerable
	{
		public struct Enumerator : IEnumerator<StringSegment>, IEnumerator, IDisposable
		{
			private readonly StringSegment _value;

			private readonly char[] _separators;

			private int _index;

			public StringSegment Current { get; private set; }

			object IEnumerator.Current => Current;

			internal Enumerator(in StringSegment value, char[] separators)
			{
				_value = value;
				_separators = separators;
				Current = default(StringSegment);
				_index = 0;
			}

			public Enumerator(ref StringTokenizer tokenizer)
			{
				_value = tokenizer._value;
				_separators = tokenizer._separators;
				Current = default(StringSegment);
				_index = 0;
			}

			public void Dispose()
			{
			}

			public bool MoveNext()
			{
				if (!_value.HasValue || _index > _value.Length)
				{
					Current = default(StringSegment);
					return false;
				}
				int num = _value.IndexOfAny(_separators, _index);
				if (num == -1)
				{
					num = _value.Length;
				}
				Current = _value.Subsegment(_index, num - _index);
				_index = num + 1;
				return true;
			}

			public void Reset()
			{
				Current = default(StringSegment);
				_index = 0;
			}
		}

		private readonly StringSegment _value;

		private readonly char[] _separators;

		public StringTokenizer(string value, char[] separators)
		{
			if (value == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
			}
			if (separators == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators);
			}
			_value = value;
			_separators = separators;
		}

		public StringTokenizer(StringSegment value, char[] separators)
		{
			if (!value.HasValue)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
			}
			if (separators == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators);
			}
			_value = value;
			_separators = separators;
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(in _value, _separators);
		}

		IEnumerator<StringSegment> IEnumerable<StringSegment>.GetEnumerator()
		{
			return GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	[DebuggerDisplay("{ToString()}")]
	[DebuggerTypeProxy(typeof(StringValuesDebugView))]
	public readonly struct StringValues : IList<string?>, ICollection<string?>, IEnumerable<string?>, IEnumerable, IReadOnlyList<string?>, IReadOnlyCollection<string?>, IEquatable<StringValues>, IEquatable<string?>, IEquatable<string?[]?>
	{
		public struct Enumerator : IEnumerator<string?>, IEnumerator, IDisposable
		{
			private readonly string[] _values;

			private int _index;

			private string _current;

			public string? Current => _current;

			object? IEnumerator.Current => _current;

			internal Enumerator(object value)
			{
				if (value is string current)
				{
					_values = null;
					_current = current;
				}
				else
				{
					_current = null;
					_values = Unsafe.As<string[]>(value);
				}
				_index = 0;
			}

			public Enumerator(ref StringValues values)
				: this(values._values)
			{
			}

			public bool MoveNext()
			{
				int index = _index;
				if (index < 0)
				{
					return false;
				}
				string[] values = _values;
				if (values != null)
				{
					if ((uint)index < (uint)values.Length)
					{
						_index = index + 1;
						_current = values[index];
						return true;
					}
					_index = -1;
					return false;
				}
				_index = -1;
				return _current != null;
			}

			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			public void Dispose()
			{
			}
		}

		private sealed class StringValuesDebugView
		{
			[CompilerGenerated]
			private StringValues <values>P;

			[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
			public string[] Items => <values>P.ToArray();

			public StringValuesDebugView(StringValues values)
			{
				<values>P = values;
				base..ctor();
			}
		}

		public static readonly StringValues Empty = new StringValues(Array.Empty<string>());

		private readonly object _values;

		public int Count
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object values = _values;
				if (values == null)
				{
					return 0;
				}
				if (values is string)
				{
					return 1;
				}
				return Unsafe.As<string[]>(values).Length;
			}
		}

		bool ICollection<string>.IsReadOnly => true;

		string? IList<string>.this[int index]
		{
			get
			{
				return this[index];
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public string? this[int index]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object values = _values;
				if (values is string result)
				{
					if (index == 0)
					{
						return result;
					}
				}
				else if (values != null)
				{
					return Unsafe.As<string[]>(values)[index];
				}
				return OutOfBounds();
			}
		}

		public StringValues(string? value)
		{
			_values = value;
		}

		public StringValues(string?[]? values)
		{
			_values = values;
		}

		public static implicit operator StringValues(string? value)
		{
			return new StringValues(value);
		}

		public static implicit operator StringValues(string?[]? values)
		{
			return new StringValues(values);
		}

		public static implicit operator string?(StringValues values)
		{
			return values.GetStringValue();
		}

		public static implicit operator string?[]?(StringValues value)
		{
			return value.GetArrayValue();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static string OutOfBounds()
		{
			return Array.Empty<string>()[0];
		}

		public override string ToString()
		{
			return GetStringValue() ?? string.Empty;
		}

		private string GetStringValue()
		{
			object values2 = _values;
			if (values2 is string result)
			{
				return result;
			}
			return GetStringValueFromArray(values2);
			static string GetJoinedStringValueFromArray(string[] values)
			{
				int num = 0;
				foreach (string text in values)
				{
					if (text != null && text.Length > 0)
					{
						if (num > 0)
						{
							num++;
						}
						num += text.Length;
					}
				}
				System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(num);
				bool flag = false;
				foreach (string text2 in values)
				{
					if (text2 != null && text2.Length > 0)
					{
						if (flag)
						{
							valueStringBuilder.Append(',');
						}
						valueStringBuilder.Append(text2);
						flag = true;
					}
				}
				return valueStringBuilder.ToString();
			}
			static string GetStringValueFromArray(object value)
			{
				if (value == null)
				{
					return null;
				}
				string[] array = Unsafe.As<string[]>(value);
				return array.Length switch
				{
					0 => null, 
					1 => array[0], 
					_ => GetJoinedStringValueFromArray(array), 
				};
			}
		}

		public string?[] ToArray()
		{
			return GetArrayValue() ?? Array.Empty<string>();
		}

		private string[] GetArrayValue()
		{
			object values = _values;
			if (values is string[] result)
			{
				return result;
			}
			if (values != null)
			{
				return new string[1] { Unsafe.As<string>(values) };
			}
			return null;
		}

		int IList<string>.IndexOf(string item)
		{
			return IndexOf(item);
		}

		private int IndexOf(string item)
		{
			object values = _values;
			if (values is string[] array)
			{
				for (int i = 0; i < array.Length; i++)
				{
					if (string.Equals(array[i], item, StringComparison.Ordinal))
					{
						return i;
					}
				}
				return -1;
			}
			if (values != null)
			{
				if (!string.Equals(Unsafe.As<string>(values), item, StringComparison.Ordinal))
				{
					return -1;
				}
				return 0;
			}
			return -1;
		}

		bool ICollection<string>.Contains(string item)
		{
			return IndexOf(item) >= 0;
		}

		void ICollection<string>.CopyTo(string[] array, int arrayIndex)
		{
			CopyTo(array, arrayIndex);
		}

		private void CopyTo(string[] array, int arrayIndex)
		{
			object values = _values;
			if (values is string[] array2)
			{
				Array.Copy(array2, 0, array, arrayIndex, array2.Length);
			}
			else if (values != null)
			{
				if (array == null)
				{
					ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
				}
				if (arrayIndex < 0)
				{
					throw new ArgumentOutOfRangeException("arrayIndex");
				}
				if (array.Length - arrayIndex < 1)
				{
					throw new ArgumentException("'array' is not long enough to copy all the items in the collection. Check 'arrayIndex' and 'array' length.");
				}
				array[arrayIndex] = Unsafe.As<string>(values);
			}
		}

		void ICollection<string>.Add(string item)
		{
			throw new NotSupportedException();
		}

		void IList<string>.Insert(int index, string item)
		{
			throw new NotSupportedException();
		}

		bool ICollection<string>.Remove(string item)
		{
			throw new NotSupportedException();
		}

		void IList<string>.RemoveAt(int index)
		{
			throw new NotSupportedException();
		}

		void ICollection<string>.Clear()
		{
			throw new NotSupportedException();
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(_values);
		}

		IEnumerator<string> IEnumerable<string>.GetEnumerator()
		{
			return GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public static bool IsNullOrEmpty(StringValues value)
		{
			object values = value._values;
			if (values == null)
			{
				return true;
			}
			if (values is string[] array)
			{
				return array.Length switch
				{
					0 => true, 
					1 => string.IsNullOrEmpty(array[0]), 
					_ => false, 
				};
			}
			return string.IsNullOrEmpty(Unsafe.As<string>(values));
		}

		public static StringValues Concat(StringValues values1, StringValues values2)
		{
			int count = values1.Count;
			int count2 = values2.Count;
			if (count == 0)
			{
				return values2;
			}
			if (count2 == 0)
			{
				return values1;
			}
			string[] array = new string[count + count2];
			values1.CopyTo(array, 0);
			values2.CopyTo(array, count);
			return new StringValues(array);
		}

		public static StringValues Concat(in StringValues values, string? value)
		{
			if (value == null)
			{
				return values;
			}
			int count = values.Count;
			if (count == 0)
			{
				return new StringValues(value);
			}
			string[] array = new string[count + 1];
			values.CopyTo(array, 0);
			array[count] = value;
			return new StringValues(array);
		}

		public static StringValues Concat(string? value, in StringValues values)
		{
			if (value == null)
			{
				return values;
			}
			int count = values.Count;
			if (count == 0)
			{
				return new StringValues(value);
			}
			string[] array = new string[count + 1];
			array[0] = value;
			values.CopyTo(array, 1);
			return new StringValues(array);
		}

		public static bool Equals(StringValues left, StringValues right)
		{
			int count = left.Count;
			if (count != right.Count)
			{
				return false;
			}
			for (int i = 0; i < count; i++)
			{
				if (left[i] != right[i])
				{
					return false;
				}
			}
			return true;
		}

		public static bool operator ==(StringValues left, StringValues right)
		{
			return Equals(left, right);
		}

		public static bool operator !=(StringValues left, StringValues right)
		{
			return !Equals(left, right);
		}

		public bool Equals(StringValues other)
		{
			return Equals(this, other);
		}

		public static bool Equals(string? left, StringValues right)
		{
			return Equals(new StringValues(left), right);
		}

		public static bool Equals(StringValues left, string? right)
		{
			return Equals(left, new StringValues(right));
		}

		public bool Equals(string? other)
		{
			return Equals(this, new StringValues(other));
		}

		public static bool Equals(string?[]? left, StringValues right)
		{
			return Equals(new StringValues(left), right);
		}

		public static bool Equals(StringValues left, string?[]? right)
		{
			return Equals(left, new StringValues(right));
		}

		public bool Equals(string?[]? other)
		{
			return Equals(this, new StringValues(other));
		}

		public static bool operator ==(StringValues left, string? right)
		{
			return Equals(left, new StringValues(right));
		}

		public static bool operator !=(StringValues left, string? right)
		{
			return !Equals(left, new StringValues(right));
		}

		public static bool operator ==(string? left, StringValues right)
		{
			return Equals(new StringValues(left), right);
		}

		public static bool operator !=(string? left, StringValues right)
		{
			return !Equals(new StringValues(left), right);
		}

		public static bool operator ==(StringValues left, string?[]? right)
		{
			return Equals(left, new StringValues(right));
		}

		public static bool operator !=(StringValues left, string?[]? right)
		{
			return !Equals(left, new StringValues(right));
		}

		public static bool operator ==(string?[]? left, StringValues right)
		{
			return Equals(new StringValues(left), right);
		}

		public static bool operator !=(string?[]? left, StringValues right)
		{
			return !Equals(new StringValues(left), right);
		}

		public static bool operator ==(StringValues left, object? right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(StringValues left, object? right)
		{
			return !left.Equals(right);
		}

		public static bool operator ==(object? left, StringValues right)
		{
			return right.Equals(left);
		}

		public static bool operator !=(object? left, StringValues right)
		{
			return !right.Equals(left);
		}

		public override bool Equals(object? obj)
		{
			if (obj == null)
			{
				return Equals(this, Empty);
			}
			if (obj is string right)
			{
				return Equals(this, right);
			}
			if (obj is string[] right2)
			{
				return Equals(this, right2);
			}
			if (obj is StringValues right3)
			{
				return Equals(this, right3);
			}
			return false;
		}

		public override int GetHashCode()
		{
			object values = _values;
			if (values is string[] array)
			{
				if (Count == 1)
				{
					return Unsafe.As<string>(this[0])?.GetHashCode() ?? Count.GetHashCode();
				}
				int num = 0;
				for (int i = 0; i < array.Length; i++)
				{
					num = HashHelpers.Combine(num, array[i]?.GetHashCode() ?? 0);
				}
				return num;
			}
			return Unsafe.As<string>(values)?.GetHashCode() ?? Count.GetHashCode();
		}
	}
	internal static class ThrowHelper
	{
		[DoesNotReturn]
		internal static void ThrowArgumentNullException(ExceptionArgument argument)
		{
			throw new ArgumentNullException(GetArgumentName(argument));
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)
		{
			throw new ArgumentOutOfRangeException(GetArgumentName(argument));
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException(ExceptionResource resource)
		{
			throw new ArgumentException(GetResourceText(resource));
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException(ExceptionResource resource)
		{
			throw new InvalidOperationException(GetResourceText(resource));
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException(ExceptionResource resource, params object[] args)
		{
			throw new InvalidOperationException(string.Format(GetResourceText(resource), args));
		}

		internal static ArgumentNullException GetArgumentNullException(ExceptionArgument argument)
		{
			return new ArgumentNullException(GetArgumentName(argument));
		}

		internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument)
		{
			return new ArgumentOutOfRangeException(GetArgumentName(argument));
		}

		internal static ArgumentException GetArgumentException(ExceptionResource resource)
		{
			return new ArgumentException(GetResourceText(resource));
		}

		private static string GetResourceText(ExceptionResource resource)
		{
			return resource switch
			{
				ExceptionResource.Argument_InvalidOffsetLength => System.SR.Argument_InvalidOffsetLength, 
				ExceptionResource.Argument_InvalidOffsetLengthStringSegment => System.SR.Argument_InvalidOffsetLengthStringSegment, 
				ExceptionResource.Capacity_CannotChangeAfterWriteStarted => System.SR.Capacity_CannotChangeAfterWriteStarted, 
				ExceptionResource.Capacity_NotEnough => System.SR.Capacity_NotEnough, 
				ExceptionResource.Capacity_NotUsedEntirely => System.SR.Capacity_NotUsedEntirely, 
				_ => "", 
			};
		}

		private static string GetArgumentName(ExceptionArgument argument)
		{
			return argument.ToString();
		}
	}
	internal enum ExceptionArgument
	{
		buffer,
		offset,
		length,
		text,
		start,
		count,
		index,
		value,
		capacity,
		separators,
		comparisonType,
		changeTokens,
		changeTokenProducer,
		changeTokenConsumer,
		array
	}
	internal enum ExceptionResource
	{
		Argument_InvalidOffsetLength,
		Argument_InvalidOffsetLengthStringSegment,
		Capacity_CannotChangeAfterWriteStarted,
		Capacity_NotEnough,
		Capacity_NotUsedEntirely
	}
}

System.Buffers.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using FxResources.System.Buffers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Buffers")]
[assembly: AssemblyDescription("System.Buffers")]
[assembly: AssemblyDefaultAlias("System.Buffers")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.28619.01")]
[assembly: AssemblyInformationalVersion("4.6.28619.01 @BuiltBy: dlab14-DDVSOWINAGE069 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/7601f4f6225089ffb291dc7d58293c7bbf5c5d4f")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.3.0")]
[module: UnverifiableCode]
namespace FxResources.System.Buffers
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType));

		internal static Type ResourceType { get; } = typeof(SR);


		internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool", null);

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool UsingResourceKeys()
		{
			return false;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal))
			{
				return defaultString;
			}
			return text;
		}

		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(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);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.All)]
	internal class __BlockReflectionAttribute : Attribute
	{
	}
}
namespace System.Buffers
{
	public abstract class ArrayPool<T>
	{
		private static ArrayPool<T> s_sharedInstance;

		public static ArrayPool<T> Shared
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static ArrayPool<T> EnsureSharedCreated()
		{
			Interlocked.CompareExchange(ref s_sharedInstance, Create(), null);
			return s_sharedInstance;
		}

		public static ArrayPool<T> Create()
		{
			return new DefaultArrayPool<T>();
		}

		public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket)
		{
			return new DefaultArrayPool<T>(maxArrayLength, maxArraysPerBucket);
		}

		public abstract T[] Rent(int minimumLength);

		public abstract void Return(T[] array, bool clearArray = false);
	}
	[EventSource(Name = "System.Buffers.ArrayPoolEventSource")]
	internal sealed class ArrayPoolEventSource : EventSource
	{
		internal enum BufferAllocatedReason
		{
			Pooled,
			OverMaximumSize,
			PoolExhausted
		}

		internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource();

		[Event(1, Level = EventLevel.Verbose)]
		internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId)
		{
			EventData* ptr = stackalloc EventData[4];
			*ptr = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bufferId)
			};
			ptr[1] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bufferSize)
			};
			ptr[2] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&poolId)
			};
			ptr[3] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bucketId)
			};
			WriteEventCore(1, 4, ptr);
		}

		[Event(2, Level = EventLevel.Informational)]
		internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason)
		{
			EventData* ptr = stackalloc EventData[5];
			*ptr = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bufferId)
			};
			ptr[1] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bufferSize)
			};
			ptr[2] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&poolId)
			};
			ptr[3] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bucketId)
			};
			ptr[4] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&reason)
			};
			WriteEventCore(2, 5, ptr);
		}

		[Event(3, Level = EventLevel.Verbose)]
		internal void BufferReturned(int bufferId, int bufferSize, int poolId)
		{
			WriteEvent(3, bufferId, bufferSize, poolId);
		}
	}
	internal sealed class DefaultArrayPool<T> : ArrayPool<T>
	{
		private sealed class Bucket
		{
			internal readonly int _bufferLength;

			private readonly T[][] _buffers;

			private readonly int _poolId;

			private SpinLock _lock;

			private int _index;

			internal int Id => GetHashCode();

			internal Bucket(int bufferLength, int numberOfBuffers, int poolId)
			{
				_lock = new SpinLock(Debugger.IsAttached);
				_buffers = new T[numberOfBuffers][];
				_bufferLength = bufferLength;
				_poolId = poolId;
			}

			internal T[] Rent()
			{
				T[][] buffers = _buffers;
				T[] array = null;
				bool lockTaken = false;
				bool flag = false;
				try
				{
					_lock.Enter(ref lockTaken);
					if (_index < buffers.Length)
					{
						array = buffers[_index];
						buffers[_index++] = null;
						flag = array == null;
					}
				}
				finally
				{
					if (lockTaken)
					{
						_lock.Exit(useMemoryBarrier: false);
					}
				}
				if (flag)
				{
					array = new T[_bufferLength];
					System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log;
					if (log.IsEnabled())
					{
						log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled);
					}
				}
				return array;
			}

			internal void Return(T[] array)
			{
				if (array.Length != _bufferLength)
				{
					throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array");
				}
				bool lockTaken = false;
				try
				{
					_lock.Enter(ref lockTaken);
					if (_index != 0)
					{
						_buffers[--_index] = array;
					}
				}
				finally
				{
					if (lockTaken)
					{
						_lock.Exit(useMemoryBarrier: false);
					}
				}
			}
		}

		private const int DefaultMaxArrayLength = 1048576;

		private const int DefaultMaxNumberOfArraysPerBucket = 50;

		private static T[] s_emptyArray;

		private readonly Bucket[] _buckets;

		private int Id => GetHashCode();

		internal DefaultArrayPool()
			: this(1048576, 50)
		{
		}

		internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket)
		{
			if (maxArrayLength <= 0)
			{
				throw new ArgumentOutOfRangeException("maxArrayLength");
			}
			if (maxArraysPerBucket <= 0)
			{
				throw new ArgumentOutOfRangeException("maxArraysPerBucket");
			}
			if (maxArrayLength > 1073741824)
			{
				maxArrayLength = 1073741824;
			}
			else if (maxArrayLength < 16)
			{
				maxArrayLength = 16;
			}
			int id = Id;
			int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength);
			Bucket[] array = new Bucket[num + 1];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id);
			}
			_buckets = array;
		}

		public override T[] Rent(int minimumLength)
		{
			if (minimumLength < 0)
			{
				throw new ArgumentOutOfRangeException("minimumLength");
			}
			if (minimumLength == 0)
			{
				return s_emptyArray ?? (s_emptyArray = new T[0]);
			}
			System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log;
			T[] array = null;
			int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength);
			if (num < _buckets.Length)
			{
				int num2 = num;
				do
				{
					array = _buckets[num2].Rent();
					if (array != null)
					{
						if (log.IsEnabled())
						{
							log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id);
						}
						return array;
					}
				}
				while (++num2 < _buckets.Length && num2 != num + 2);
				array = new T[_buckets[num]._bufferLength];
			}
			else
			{
				array = new T[minimumLength];
			}
			if (log.IsEnabled())
			{
				int hashCode = array.GetHashCode();
				int bucketId = -1;
				log.BufferRented(hashCode, array.Length, Id, bucketId);
				log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted);
			}
			return array;
		}

		public override void Return(T[] array, bool clearArray = false)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (array.Length == 0)
			{
				return;
			}
			int num = System.Buffers.Utilities.SelectBucketIndex(array.Length);
			if (num < _buckets.Length)
			{
				if (clearArray)
				{
					Array.Clear(array, 0, array.Length);
				}
				_buckets[num].Return(array);
			}
			System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log;
			if (log.IsEnabled())
			{
				log.BufferReturned(array.GetHashCode(), array.Length, Id);
			}
		}
	}
	internal static class Utilities
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int SelectBucketIndex(int bufferSize)
		{
			uint num = (uint)(bufferSize - 1) >> 4;
			int num2 = 0;
			if (num > 65535)
			{
				num >>= 16;
				num2 = 16;
			}
			if (num > 255)
			{
				num >>= 8;
				num2 += 8;
			}
			if (num > 15)
			{
				num >>= 4;
				num2 += 4;
			}
			if (num > 3)
			{
				num >>= 2;
				num2 += 2;
			}
			if (num > 1)
			{
				num >>= 1;
				num2++;
			}
			return num2 + (int)num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int GetMaxSizeForBucket(int binIndex)
		{
			return 16 << binIndex;
		}
	}
}

System.ComponentModel.Annotations.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using FxResources.System.ComponentModel.Annotations;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDefaultAlias("System.ComponentModel.Annotations")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("System.ComponentModel.Annotations")]
[assembly: AssemblyFileVersion("5.0.20.51904")]
[assembly: AssemblyInformationalVersion("5.0.0+cf258a14b70ad9069470a108f13765e0e5988f51")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.ComponentModel.Annotations")]
[assembly: AssemblyMetadata("RepositoryUrl", "git://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("5.0.0.0")]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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;
		}
	}
}
namespace FxResources.System.ComponentModel.Annotations
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class NotImplemented
	{
		internal static Exception ByDesignWithMessage(string message)
		{
			return new NotImplementedException(message);
		}
	}
	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 ArgumentIsNullOrWhitespace => GetResourceString("ArgumentIsNullOrWhitespace", "The argument '{0}' cannot be null, empty or contain only whitespace.");

		internal static string AssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties => GetResourceString("AssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties", "The associated metadata type for type '{0}' contains the following unknown properties or fields: {1}. Please make sure that the names of these members match the names of the properties on the main type.");

		internal static string AttributeStore_Unknown_Property => GetResourceString("AttributeStore_Unknown_Property", "The type '{0}' does not contain a public property named '{1}'.");

		internal static string Common_PropertyNotFound => GetResourceString("Common_PropertyNotFound", "The property {0}.{1} could not be found.");

		internal static string CompareAttribute_MustMatch => GetResourceString("CompareAttribute_MustMatch", "'{0}' and '{1}' do not match.");

		internal static string CompareAttribute_UnknownProperty => GetResourceString("CompareAttribute_UnknownProperty", "Could not find a property named {0}.");

		internal static string CreditCardAttribute_Invalid => GetResourceString("CreditCardAttribute_Invalid", "The {0} field is not a valid credit card number.");

		internal static string CustomValidationAttribute_Method_Must_Return_ValidationResult => GetResourceString("CustomValidationAttribute_Method_Must_Return_ValidationResult", "The CustomValidationAttribute method '{0}' in type '{1}' must return System.ComponentModel.DataAnnotations.ValidationResult.  Use System.ComponentModel.DataAnnotations.ValidationResult.Success to represent success.");

		internal static string CustomValidationAttribute_Method_Not_Found => GetResourceString("CustomValidationAttribute_Method_Not_Found", "The CustomValidationAttribute method '{0}' does not exist in type '{1}' or is not public and static.");

		internal static string CustomValidationAttribute_Method_Required => GetResourceString("CustomValidationAttribute_Method_Required", "The CustomValidationAttribute.Method was not specified.");

		internal static string CustomValidationAttribute_Method_Signature => GetResourceString("CustomValidationAttribute_Method_Signature", "The CustomValidationAttribute method '{0}' in type '{1}' must match the expected signature: public static ValidationResult {0}(object value, ValidationContext context).  The value can be strongly typed.  The ValidationContext parameter is optional.");

		internal static string CustomValidationAttribute_Type_Conversion_Failed => GetResourceString("CustomValidationAttribute_Type_Conversion_Failed", "Could not convert the value of type '{0}' to '{1}' as expected by method {2}.{3}.");

		internal static string CustomValidationAttribute_Type_Must_Be_Public => GetResourceString("CustomValidationAttribute_Type_Must_Be_Public", "The custom validation type '{0}' must be public.");

		internal static string CustomValidationAttribute_ValidationError => GetResourceString("CustomValidationAttribute_ValidationError", "{0} is not valid.");

		internal static string CustomValidationAttribute_ValidatorType_Required => GetResourceString("CustomValidationAttribute_ValidatorType_Required", "The CustomValidationAttribute.ValidatorType was not specified.");

		internal static string DataTypeAttribute_EmptyDataTypeString => GetResourceString("DataTypeAttribute_EmptyDataTypeString", "The custom DataType string cannot be null or empty.");

		internal static string DisplayAttribute_PropertyNotSet => GetResourceString("DisplayAttribute_PropertyNotSet", "The {0} property has not been set.  Use the {1} method to get the value.");

		internal static string EmailAddressAttribute_Invalid => GetResourceString("EmailAddressAttribute_Invalid", "The {0} field is not a valid e-mail address.");

		internal static string EnumDataTypeAttribute_TypeCannotBeNull => GetResourceString("EnumDataTypeAttribute_TypeCannotBeNull", "The type provided for EnumDataTypeAttribute cannot be null.");

		internal static string EnumDataTypeAttribute_TypeNeedsToBeAnEnum => GetResourceString("EnumDataTypeAttribute_TypeNeedsToBeAnEnum", "The type '{0}' needs to represent an enumeration type.");

		internal static string FileExtensionsAttribute_Invalid => GetResourceString("FileExtensionsAttribute_Invalid", "The {0} field only accepts files with the following extensions: {1}");

		internal static string LocalizableString_LocalizationFailed => GetResourceString("LocalizableString_LocalizationFailed", "Cannot retrieve property '{0}' because localization failed.  Type '{1}' is not public or does not contain a public static string property with the name '{2}'.");

		internal static string MaxLengthAttribute_InvalidMaxLength => GetResourceString("MaxLengthAttribute_InvalidMaxLength", "MaxLengthAttribute must have a Length value that is greater than zero. Use MaxLength() without parameters to indicate that the string or array can have the maximum allowable length.");

		internal static string MaxLengthAttribute_ValidationError => GetResourceString("MaxLengthAttribute_ValidationError", "The field {0} must be a string or array type with a maximum length of '{1}'.");

		internal static string MetadataTypeAttribute_TypeCannotBeNull => GetResourceString("MetadataTypeAttribute_TypeCannotBeNull", "MetadataClassType cannot be null.");

		internal static string MinLengthAttribute_InvalidMinLength => GetResourceString("MinLengthAttribute_InvalidMinLength", "MinLengthAttribute must have a Length value that is zero or greater.");

		internal static string MinLengthAttribute_ValidationError => GetResourceString("MinLengthAttribute_ValidationError", "The field {0} must be a string or array type with a minimum length of '{1}'.");

		internal static string LengthAttribute_InvalidValueType => GetResourceString("LengthAttribute_InvalidValueType", "The field of type {0} must be a string, array or ICollection type.");

		internal static string PhoneAttribute_Invalid => GetResourceString("PhoneAttribute_Invalid", "The {0} field is not a valid phone number.");

		internal static string RangeAttribute_ArbitraryTypeNotIComparable => GetResourceString("RangeAttribute_ArbitraryTypeNotIComparable", "The type {0} must implement {1}.");

		internal static string RangeAttribute_MinGreaterThanMax => GetResourceString("RangeAttribute_MinGreaterThanMax", "The maximum value '{0}' must be greater than or equal to the minimum value '{1}'.");

		internal static string RangeAttribute_Must_Set_Min_And_Max => GetResourceString("RangeAttribute_Must_Set_Min_And_Max", "The minimum and maximum values must be set.");

		internal static string RangeAttribute_Must_Set_Operand_Type => GetResourceString("RangeAttribute_Must_Set_Operand_Type", "The OperandType must be set when strings are used for minimum and maximum values.");

		internal static string RangeAttribute_ValidationError => GetResourceString("RangeAttribute_ValidationError", "The field {0} must be between {1} and {2}.");

		internal static string RegexAttribute_ValidationError => GetResourceString("RegexAttribute_ValidationError", "The field {0} must match the regular expression '{1}'.");

		internal static string RegularExpressionAttribute_Empty_Pattern => GetResourceString("RegularExpressionAttribute_Empty_Pattern", "The pattern must be set to a valid regular expression.");

		internal static string RequiredAttribute_ValidationError => GetResourceString("RequiredAttribute_ValidationError", "The {0} field is required.");

		internal static string StringLengthAttribute_InvalidMaxLength => GetResourceString("StringLengthAttribute_InvalidMaxLength", "The maximum length must be a nonnegative integer.");

		internal static string StringLengthAttribute_ValidationError => GetResourceString("StringLengthAttribute_ValidationError", "The field {0} must be a string with a maximum length of {1}.");

		internal static string StringLengthAttribute_ValidationErrorIncludingMinimum => GetResourceString("StringLengthAttribute_ValidationErrorIncludingMinimum", "The field {0} must be a string with a minimum length of {2} and a maximum length of {1}.");

		internal static string UIHintImplementation_ControlParameterKeyIsNotAString => GetResourceString("UIHintImplementation_ControlParameterKeyIsNotAString", "The key parameter at position {0} with value '{1}' is not a string. Every key control parameter must be a string.");

		internal static string UIHintImplementation_ControlParameterKeyIsNull => GetResourceString("UIHintImplementation_ControlParameterKeyIsNull", "The key parameter at position {0} is null. Every key control parameter must be a string.");

		internal static string UIHintImplementation_ControlParameterKeyOccursMoreThanOnce => GetResourceString("UIHintImplementation_ControlParameterKeyOccursMoreThanOnce", "The key parameter at position {0} with value '{1}' occurs more than once.");

		internal static string UIHintImplementation_NeedEvenNumberOfControlParameters => GetResourceString("UIHintImplementation_NeedEvenNumberOfControlParameters", "The number of control parameters must be even.");

		internal static string UrlAttribute_Invalid => GetResourceString("UrlAttribute_Invalid", "The {0} field is not a valid fully-qualified http, https, or ftp URL.");

		internal static string ValidationAttribute_Cannot_Set_ErrorMessage_And_Resource => GetResourceString("ValidationAttribute_Cannot_Set_ErrorMessage_And_Resource", "Either ErrorMessageString or ErrorMessageResourceName must be set, but not both.");

		internal static string ValidationAttribute_IsValid_NotImplemented => GetResourceString("ValidationAttribute_IsValid_NotImplemented", "IsValid(object value) has not been implemented by this class.  The preferred entry point is GetValidationResult() and classes should override IsValid(object value, ValidationContext context).");

		internal static string ValidationAttribute_NeedBothResourceTypeAndResourceName => GetResourceString("ValidationAttribute_NeedBothResourceTypeAndResourceName", "Both ErrorMessageResourceType and ErrorMessageResourceName need to be set on this attribute.");

		internal static string ValidationAttribute_ResourcePropertyNotStringType => GetResourceString("ValidationAttribute_ResourcePropertyNotStringType", "The property '{0}' on resource type '{1}' is not a string type.");

		internal static string ValidationAttribute_ResourceTypeDoesNotHaveProperty => GetResourceString("ValidationAttribute_ResourceTypeDoesNotHaveProperty", "The resource type '{0}' does not have an accessible static property named '{1}'.");

		internal static string ValidationAttribute_ValidationError => GetResourceString("ValidationAttribute_ValidationError", "The field {0} is invalid.");

		internal static string Validator_InstanceMustMatchValidationContextInstance => GetResourceString("Validator_InstanceMustMatchValidationContextInstance", "The instance provided must match the ObjectInstance on the ValidationContext supplied.");

		internal static string Validator_Property_Value_Wrong_Type => GetResourceString("Validator_Property_Value_Wrong_Type", "The value for property '{0}' must be of type '{1}'.");

		private static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		internal static string GetResourceString(string resourceKey, string defaultString = null)
		{
			if (UsingResourceKeys())
			{
				return defaultString ?? resourceKey;
			}
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text))
			{
				return defaultString;
			}
			return text;
		}

		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;
		}
	}
}
namespace System.ComponentModel.DataAnnotations
{
	internal class AssociatedMetadataTypeTypeDescriptor : CustomTypeDescriptor
	{
		private static class TypeDescriptorCache
		{
			private static readonly ConcurrentDictionary<Type, Type> s_metadataTypeCache = new ConcurrentDictionary<Type, Type>();

			private static readonly ConcurrentDictionary<(Type, string), Attribute[]> s_typeMemberCache = new ConcurrentDictionary<(Type, string), Attribute[]>();

			private static readonly ConcurrentDictionary<(Type, Type), bool> s_validatedMetadataTypeCache = new ConcurrentDictionary<(Type, Type), bool>();

			public static void ValidateMetadataType(Type type, Type associatedType)
			{
				(Type, Type) key = (type, associatedType);
				if (!s_validatedMetadataTypeCache.ContainsKey(key))
				{
					CheckAssociatedMetadataType(type, associatedType);
					s_validatedMetadataTypeCache.TryAdd(key, value: true);
				}
			}

			public static Type GetAssociatedMetadataType(Type type)
			{
				Type value = null;
				if (s_metadataTypeCache.TryGetValue(type, out value))
				{
					return value;
				}
				MetadataTypeAttribute metadataTypeAttribute = (MetadataTypeAttribute)Attribute.GetCustomAttribute(type, typeof(MetadataTypeAttribute));
				if (metadataTypeAttribute != null)
				{
					value = metadataTypeAttribute.MetadataClassType;
				}
				s_metadataTypeCache.TryAdd(type, value);
				return value;
			}

			private static void CheckAssociatedMetadataType(Type mainType, Type associatedMetadataType)
			{
				HashSet<string> other = new HashSet<string>(from p in mainType.GetProperties()
					select p.Name);
				IEnumerable<string> first = from f in associatedMetadataType.GetFields()
					select f.Name;
				IEnumerable<string> second = from p in associatedMetadataType.GetProperties()
					select p.Name;
				HashSet<string> hashSet = new HashSet<string>(first.Concat(second), StringComparer.Ordinal);
				if (!hashSet.IsSubsetOf(other))
				{
					hashSet.ExceptWith(other);
					throw new InvalidOperationException(System.SR.Format(System.SR.AssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties, mainType.FullName, string.Join(", ", hashSet.ToArray())));
				}
			}

			public static Attribute[] GetAssociatedMetadata(Type type, string memberName)
			{
				(Type, string) key = (type, memberName);
				if (s_typeMemberCache.TryGetValue(key, out var value))
				{
					return value;
				}
				MemberTypes type2 = MemberTypes.Field | MemberTypes.Property;
				BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
				MemberInfo memberInfo = type.GetMember(memberName, type2, bindingAttr).FirstOrDefault();
				value = ((!(memberInfo != null)) ? Array.Empty<Attribute>() : Attribute.GetCustomAttributes(memberInfo, inherit: true));
				s_typeMemberCache.TryAdd(key, value);
				return value;
			}
		}

		private Type AssociatedMetadataType { get; set; }

		private bool IsSelfAssociated { get; set; }

		public AssociatedMetadataTypeTypeDescriptor(ICustomTypeDescriptor parent, Type type, Type associatedMetadataType)
			: base(parent)
		{
			AssociatedMetadataType = associatedMetadataType ?? TypeDescriptorCache.GetAssociatedMetadataType(type);
			IsSelfAssociated = type == AssociatedMetadataType;
			if (AssociatedMetadataType != null)
			{
				TypeDescriptorCache.ValidateMetadataType(type, AssociatedMetadataType);
			}
		}

		public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
		{
			return GetPropertiesWithMetadata(base.GetProperties(attributes));
		}

		public override PropertyDescriptorCollection GetProperties()
		{
			return GetPropertiesWithMetadata(base.GetProperties());
		}

		private PropertyDescriptorCollection GetPropertiesWithMetadata(PropertyDescriptorCollection originalCollection)
		{
			if (AssociatedMetadataType == null)
			{
				return originalCollection;
			}
			bool flag = false;
			List<PropertyDescriptor> list = new List<PropertyDescriptor>();
			foreach (PropertyDescriptor item2 in originalCollection)
			{
				Attribute[] associatedMetadata = TypeDescriptorCache.GetAssociatedMetadata(AssociatedMetadataType, item2.Name);
				PropertyDescriptor item = item2;
				if (associatedMetadata.Length != 0)
				{
					item = new MetadataPropertyDescriptorWrapper(item2, associatedMetadata);
					flag = true;
				}
				list.Add(item);
			}
			if (flag)
			{
				return new PropertyDescriptorCollection(list.ToArray(), readOnly: true);
			}
			return originalCollection;
		}

		public override AttributeCollection GetAttributes()
		{
			AttributeCollection attributeCollection = base.GetAttributes();
			if (AssociatedMetadataType != null && !IsSelfAssociated)
			{
				Attribute[] newAttributes = TypeDescriptor.GetAttributes(AssociatedMetadataType).OfType<Attribute>().ToArray();
				attributeCollection = AttributeCollection.FromExisting(attributeCollection, newAttributes);
			}
			return attributeCollection;
		}
	}
	public class AssociatedMetadataTypeTypeDescriptionProvider : TypeDescriptionProvider
	{
		private readonly Type _associatedMetadataType;

		public AssociatedMetadataTypeTypeDescriptionProvider(Type type)
			: base(TypeDescriptor.GetProvider(type))
		{
		}

		public AssociatedMetadataTypeTypeDescriptionProvider(Type type, Type associatedMetadataType)
			: this(type)
		{
			if (associatedMetadataType == null)
			{
				throw new ArgumentNullException("associatedMetadataType");
			}
			_associatedMetadataType = associatedMetadataType;
		}

		public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
		{
			ICustomTypeDescriptor typeDescriptor = base.GetTypeDescriptor(objectType, instance);
			return new AssociatedMetadataTypeTypeDescriptor(typeDescriptor, objectType, _associatedMetadataType);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
	[Obsolete("This attribute is no longer in use and will be ignored if applied.")]
	public sealed class AssociationAttribute : Attribute
	{
		public string Name { get; }

		public string ThisKey { get; }

		public string OtherKey { get; }

		public bool IsForeignKey { get; set; }

		public IEnumerable<string> ThisKeyMembers => GetKeyMembers(ThisKey);

		public IEnumerable<string> OtherKeyMembers => GetKeyMembers(OtherKey);

		public AssociationAttribute(string name, string thisKey, string otherKey)
		{
			Name = name;
			ThisKey = thisKey;
			OtherKey = otherKey;
		}

		private static string[] GetKeyMembers(string key)
		{
			if (key == null)
			{
				return Array.Empty<string>();
			}
			return key.Replace(" ", string.Empty).Split(',');
		}
	}
	[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
	public class CompareAttribute : ValidationAttribute
	{
		public string OtherProperty { get; }

		public string? OtherPropertyDisplayName { get; internal set; }

		public override bool RequiresValidationContext => true;

		public CompareAttribute(string otherProperty)
			: base(System.SR.CompareAttribute_MustMatch)
		{
			OtherProperty = otherProperty ?? throw new ArgumentNullException("otherProperty");
		}

		public override string FormatErrorMessage(string name)
		{
			return string.Format(CultureInfo.CurrentCulture, base.ErrorMessageString, name, OtherPropertyDisplayName ?? OtherProperty);
		}

		protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
		{
			PropertyInfo runtimeProperty = validationContext.ObjectType.GetRuntimeProperty(OtherProperty);
			if (runtimeProperty == null)
			{
				return new ValidationResult(System.SR.Format(System.SR.CompareAttribute_UnknownProperty, OtherProperty));
			}
			if (runtimeProperty.GetIndexParameters().Any())
			{
				throw new ArgumentException(System.SR.Format(System.SR.Common_PropertyNotFound, validationContext.ObjectType.FullName, OtherProperty));
			}
			object value2 = runtimeProperty.GetValue(validationContext.ObjectInstance, null);
			if (!object.Equals(value, value2))
			{
				if (OtherPropertyDisplayName == null)
				{
					OtherPropertyDisplayName = GetDisplayNameForProperty(runtimeProperty);
				}
				string[] memberNames = ((validationContext.MemberName == null) ? null : new string[1] { validationContext.MemberName });
				return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames);
			}
			return null;
		}

		private string GetDisplayNameForProperty(PropertyInfo property)
		{
			IEnumerable<Attribute> customAttributes = CustomAttributeExtensions.GetCustomAttributes(property, inherit: true);
			DisplayAttribute displayAttribute = customAttributes.OfType<DisplayAttribute>().FirstOrDefault();
			if (displayAttribute != null)
			{
				return displayAttribute.GetName();
			}
			return OtherProperty;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
	public sealed class ConcurrencyCheckAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class CreditCardAttribute : DataTypeAttribute
	{
		public CreditCardAttribute()
			: base(DataType.CreditCard)
		{
			base.DefaultErrorMessage = System.SR.CreditCardAttribute_Invalid;
		}

		public override bool IsValid(object? value)
		{
			if (value == null)
			{
				return true;
			}
			if (!(value is string text))
			{
				return false;
			}
			string text2 = text.Replace("-", string.Empty);
			text2 = text2.Replace(" ", string.Empty);
			int num = 0;
			bool flag = false;
			for (int num2 = text2.Length - 1; num2 >= 0; num2--)
			{
				char c = text2[num2];
				if (c < '0' || c > '9')
				{
					return false;
				}
				int num3 = (c - 48) * ((!flag) ? 1 : 2);
				flag = !flag;
				while (num3 > 0)
				{
					num += num3 % 10;
					num3 /= 10;
				}
			}
			return num % 10 == 0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true)]
	public sealed class CustomValidationAttribute : ValidationAttribute
	{
		private readonly Lazy<string> _malformedErrorMessage;

		private bool _isSingleArgumentMethod;

		private string _lastMessage;

		private MethodInfo _methodInfo;

		private Type _firstParameterType;

		private Tuple<string, Type> _typeId;

		public Type ValidatorType { get; }

		public override object TypeId
		{
			get
			{
				if (_typeId == null)
				{
					_typeId = new Tuple<string, Type>(Method, ValidatorType);
				}
				return _typeId;
			}
		}

		public string Method { get; }

		public override bool RequiresValidationContext
		{
			get
			{
				ThrowIfAttributeNotWellFormed();
				return !_isSingleArgumentMethod;
			}
		}

		public CustomValidationAttribute(Type validatorType, string method)
			: base(() => System.SR.CustomValidationAttribute_ValidationError)
		{
			ValidatorType = validatorType;
			Method = method;
			_malformedErrorMessage = new Lazy<string>(CheckAttributeWellFormed);
		}

		protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
		{
			ThrowIfAttributeNotWellFormed();
			MethodInfo methodInfo = _methodInfo;
			if (!TryConvertValue(value, out var convertedValue))
			{
				return new ValidationResult(System.SR.Format(System.SR.CustomValidationAttribute_Type_Conversion_Failed, (value != null) ? value.GetType().ToString() : "null", _firstParameterType, ValidatorType, Method));
			}
			try
			{
				object[] parameters = ((!_isSingleArgumentMethod) ? new object[2] { convertedValue, validationContext } : new object[1] { convertedValue });
				ValidationResult validationResult = (ValidationResult)methodInfo.Invoke(null, parameters);
				_lastMessage = null;
				if (validationResult != null)
				{
					_lastMessage = validationResult.ErrorMessage;
				}
				return validationResult;
			}
			catch (TargetInvocationException ex)
			{
				throw ex.InnerException;
			}
		}

		public override string FormatErrorMessage(string name)
		{
			ThrowIfAttributeNotWellFormed();
			if (!string.IsNullOrEmpty(_lastMessage))
			{
				return string.Format(CultureInfo.CurrentCulture, _lastMessage, name);
			}
			return base.FormatErrorMessage(name);
		}

		private string CheckAttributeWellFormed()
		{
			return ValidateValidatorTypeParameter() ?? ValidateMethodParameter();
		}

		private string ValidateValidatorTypeParameter()
		{
			if (ValidatorType == null)
			{
				return System.SR.CustomValidationAttribute_ValidatorType_Required;
			}
			if (!ValidatorType.IsVisible)
			{
				return System.SR.Format(System.SR.CustomValidationAttribute_Type_Must_Be_Public, ValidatorType.Name);
			}
			return null;
		}

		private string ValidateMethodParameter()
		{
			if (string.IsNullOrEmpty(Method))
			{
				return System.SR.CustomValidationAttribute_Method_Required;
			}
			MethodInfo methodInfo = ValidatorType.GetRuntimeMethods().SingleOrDefault((MethodInfo m) => string.Equals(m.Name, Method, StringComparison.Ordinal) && m.IsPublic && m.IsStatic);
			if (methodInfo == null)
			{
				return System.SR.Format(System.SR.CustomValidationAttribute_Method_Not_Found, Method, ValidatorType.Name);
			}
			if (!typeof(ValidationResult).IsAssignableFrom(methodInfo.ReturnType))
			{
				return System.SR.Format(System.SR.CustomValidationAttribute_Method_Must_Return_ValidationResult, Method, ValidatorType.Name);
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length == 0 || parameters[0].ParameterType.IsByRef)
			{
				return System.SR.Format(System.SR.CustomValidationAttribute_Method_Signature, Method, ValidatorType.Name);
			}
			_isSingleArgumentMethod = parameters.Length == 1;
			if (!_isSingleArgumentMethod && (parameters.Length != 2 || parameters[1].ParameterType != typeof(ValidationContext)))
			{
				return System.SR.Format(System.SR.CustomValidationAttribute_Method_Signature, Method, ValidatorType.Name);
			}
			_methodInfo = methodInfo;
			_firstParameterType = parameters[0].ParameterType;
			return null;
		}

		private void ThrowIfAttributeNotWellFormed()
		{
			string value = _malformedErrorMessage.Value;
			if (value != null)
			{
				throw new InvalidOperationException(value);
			}
		}

		private bool TryConvertValue(object value, out object convertedValue)
		{
			convertedValue = null;
			Type firstParameterType = _firstParameterType;
			if (value == null)
			{
				if (firstParameterType.IsValueType && (!firstParameterType.IsGenericType || firstParameterType.GetGenericTypeDefinition() != typeof(Nullable<>)))
				{
					return false;
				}
				return true;
			}
			if (firstParameterType.IsInstanceOfType(value))
			{
				convertedValue = value;
				return true;
			}
			try
			{
				convertedValue = Convert.ChangeType(value, firstParameterType, CultureInfo.CurrentCulture);
				return true;
			}
			catch (FormatException)
			{
				return false;
			}
			catch (InvalidCastException)
			{
				return false;
			}
			catch (NotSupportedException)
			{
				return false;
			}
		}
	}
	public enum DataType
	{
		Custom,
		DateTime,
		Date,
		Time,
		Duration,
		PhoneNumber,
		Currency,
		Text,
		Html,
		MultilineText,
		EmailAddress,
		Password,
		Url,
		ImageUrl,
		CreditCard,
		PostalCode,
		Upload
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public class DataTypeAttribute : ValidationAttribute
	{
		private static readonly string[] _dataTypeStrings = Enum.GetNames(typeof(DataType));

		public DataType DataType { get; }

		public string? CustomDataType { get; }

		public DisplayFormatAttribute? DisplayFormat { get; protected set; }

		public DataTypeAttribute(DataType dataType)
		{
			DataType = dataType;
			switch (dataType)
			{
			case DataType.Date:
				DisplayFormat = new DisplayFormatAttribute();
				DisplayFormat.DataFormatString = "{0:d}";
				DisplayFormat.ApplyFormatInEditMode = true;
				break;
			case DataType.Time:
				DisplayFormat = new DisplayFormatAttribute();
				DisplayFormat.DataFormatString = "{0:t}";
				DisplayFormat.ApplyFormatInEditMode = true;
				break;
			case DataType.Currency:
				DisplayFormat = new DisplayFormatAttribute();
				DisplayFormat.DataFormatString = "{0:C}";
				break;
			case DataType.Duration:
			case DataType.PhoneNumber:
				break;
			}
		}

		public DataTypeAttribute(string customDataType)
			: this(DataType.Custom)
		{
			CustomDataType = customDataType;
		}

		public virtual string GetDataTypeName()
		{
			EnsureValidDataType();
			if (DataType == DataType.Custom)
			{
				return CustomDataType;
			}
			return _dataTypeStrings[(int)DataType];
		}

		public override bool IsValid(object? value)
		{
			EnsureValidDataType();
			return true;
		}

		private void EnsureValidDataType()
		{
			if (DataType == DataType.Custom && string.IsNullOrWhiteSpace(CustomDataType))
			{
				throw new InvalidOperationException(System.SR.DataTypeAttribute_EmptyDataTypeString);
			}
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class DisplayAttribute : Attribute
	{
		private readonly LocalizableString _description = new LocalizableString("Description");

		private readonly LocalizableString _groupName = new LocalizableString("GroupName");

		private readonly LocalizableString _name = new LocalizableString("Name");

		private readonly LocalizableString _prompt = new LocalizableString("Prompt");

		private readonly LocalizableString _shortName = new LocalizableString("ShortName");

		private bool? _autoGenerateField;

		private bool? _autoGenerateFilter;

		private int? _order;

		private Type _resourceType;

		public string? ShortName
		{
			get
			{
				return _shortName.Value;
			}
			set
			{
				_shortName.Value = value;
			}
		}

		public string? Name
		{
			get
			{
				return _name.Value;
			}
			set
			{
				_name.Value = value;
			}
		}

		public string? Description
		{
			get
			{
				return _description.Value;
			}
			set
			{
				_description.Value = value;
			}
		}

		public string? Prompt
		{
			get
			{
				return _prompt.Value;
			}
			set
			{
				_prompt.Value = value;
			}
		}

		public string? GroupName
		{
			get
			{
				return _groupName.Value;
			}
			set
			{
				_groupName.Value = value;
			}
		}

		public Type? ResourceType
		{
			get
			{
				return _resourceType;
			}
			set
			{
				if (_resourceType != value)
				{
					_resourceType = value;
					_shortName.ResourceType = value;
					_name.ResourceType = value;
					_description.ResourceType = value;
					_prompt.ResourceType = value;
					_groupName.ResourceType = value;
				}
			}
		}

		public bool AutoGenerateField
		{
			get
			{
				if (!_autoGenerateField.HasValue)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.DisplayAttribute_PropertyNotSet, "AutoGenerateField", "GetAutoGenerateField"));
				}
				return _autoGenerateField.GetValueOrDefault();
			}
			set
			{
				_autoGenerateField = value;
			}
		}

		public bool AutoGenerateFilter
		{
			get
			{
				if (!_autoGenerateFilter.HasValue)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.DisplayAttribute_PropertyNotSet, "AutoGenerateFilter", "GetAutoGenerateFilter"));
				}
				return _autoGenerateFilter.GetValueOrDefault();
			}
			set
			{
				_autoGenerateFilter = value;
			}
		}

		public int Order
		{
			get
			{
				if (!_order.HasValue)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.DisplayAttribute_PropertyNotSet, "Order", "GetOrder"));
				}
				return _order.GetValueOrDefault();
			}
			set
			{
				_order = value;
			}
		}

		public string? GetShortName()
		{
			return _shortName.GetLocalizableValue() ?? GetName();
		}

		public string? GetName()
		{
			return _name.GetLocalizableValue();
		}

		public string? GetDescription()
		{
			return _description.GetLocalizableValue();
		}

		public string? GetPrompt()
		{
			return _prompt.GetLocalizableValue();
		}

		public string? GetGroupName()
		{
			return _groupName.GetLocalizableValue();
		}

		public bool? GetAutoGenerateField()
		{
			return _autoGenerateField;
		}

		public bool? GetAutoGenerateFilter()
		{
			return _autoGenerateFilter;
		}

		public int? GetOrder()
		{
			return _order;
		}
	}
	[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
	public class DisplayColumnAttribute : Attribute
	{
		public string DisplayColumn { get; }

		public string? SortColumn { get; }

		public bool SortDescending { get; }

		public DisplayColumnAttribute(string displayColumn)
			: this(displayColumn, null)
		{
		}

		public DisplayColumnAttribute(string displayColumn, string? sortColumn)
			: this(displayColumn, sortColumn, sortDescending: false)
		{
		}

		public DisplayColumnAttribute(string displayColumn, string? sortColumn, bool sortDescending)
		{
			DisplayColumn = displayColumn;
			SortColumn = sortColumn;
			SortDescending = sortDescending;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class DisplayFormatAttribute : Attribute
	{
		private readonly LocalizableString _nullDisplayText = new LocalizableString("NullDisplayText");

		public string? DataFormatString { get; set; }

		public string? NullDisplayText
		{
			get
			{
				return _nullDisplayText.Value;
			}
			set
			{
				_nullDisplayText.Value = value;
			}
		}

		public bool ConvertEmptyStringToNull { get; set; }

		public bool ApplyFormatInEditMode { get; set; }

		public bool HtmlEncode { get; set; }

		public Type? NullDisplayTextResourceType
		{
			get
			{
				return _nullDisplayText.ResourceType;
			}
			set
			{
				_nullDisplayText.ResourceType = value;
			}
		}

		public DisplayFormatAttribute()
		{
			ConvertEmptyStringToNull = true;
			HtmlEncode = true;
		}

		public string? GetNullDisplayText()
		{
			return _nullDisplayText.GetLocalizableValue();
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
	public sealed class EditableAttribute : Attribute
	{
		public bool AllowEdit { get; }

		public bool AllowInitialValue { get; set; }

		public EditableAttribute(bool allowEdit)
		{
			AllowEdit = allowEdit;
			AllowInitialValue = allowEdit;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class EmailAddressAttribute : DataTypeAttribute
	{
		public EmailAddressAttribute()
			: base(DataType.EmailAddress)
		{
			base.DefaultErrorMessage = System.SR.EmailAddressAttribute_Invalid;
		}

		public override bool IsValid(object? value)
		{
			if (value == null)
			{
				return true;
			}
			if (!(value is string text))
			{
				return false;
			}
			int num = text.IndexOf('@');
			if (num > 0 && num != text.Length - 1)
			{
				return num == text.LastIndexOf('@');
			}
			return false;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class EnumDataTypeAttribute : DataTypeAttribute
	{
		public Type EnumType { get; }

		public EnumDataTypeAttribute(Type enumType)
			: base("Enumeration")
		{
			EnumType = enumType;
		}

		public override bool IsValid(object? value)
		{
			if (EnumType == null)
			{
				throw new InvalidOperationException(System.SR.EnumDataTypeAttribute_TypeCannotBeNull);
			}
			if (!EnumType.IsEnum)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.EnumDataTypeAttribute_TypeNeedsToBeAnEnum, EnumType.FullName));
			}
			if (value == null)
			{
				return true;
			}
			string text = value as string;
			if (text != null && text.Length == 0)
			{
				return true;
			}
			Type type = value.GetType();
			if (type.IsEnum && EnumType != type)
			{
				return false;
			}
			if (!type.IsValueType && type != typeof(string))
			{
				return false;
			}
			if (type == typeof(bool) || type == typeof(float) || type == typeof(double) || type == typeof(decimal) || type == typeof(char))
			{
				return false;
			}
			object obj;
			if (type.IsEnum)
			{
				obj = value;
			}
			else
			{
				try
				{
					obj = ((text != null) ? Enum.Parse(EnumType, text, ignoreCase: false) : Enum.ToObject(EnumType, value));
				}
				catch (ArgumentException)
				{
					return false;
				}
			}
			if (IsEnumTypeInFlagsMode(EnumType))
			{
				string underlyingTypeValueString = GetUnderlyingTypeValueString(EnumType, obj);
				string value2 = obj.ToString();
				return !underlyingTypeValueString.Equals(value2);
			}
			return Enum.IsDefined(EnumType, obj);
		}

		private static bool IsEnumTypeInFlagsMode(Type enumType)
		{
			return enumType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any();
		}

		private static string GetUnderlyingTypeValueString(Type enumType, object enumValue)
		{
			return Convert.ChangeType(enumValue, Enum.GetUnderlyingType(enumType), CultureInfo.InvariantCulture).ToString();
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class FileExtensionsAttribute : DataTypeAttribute
	{
		private string _extensions;

		public string Extensions
		{
			get
			{
				if (!string.IsNullOrWhiteSpace(_extensions))
				{
					return _extensions;
				}
				return "png,jpg,jpeg,gif";
			}
			set
			{
				_extensions = value;
			}
		}

		private string ExtensionsFormatted => ExtensionsParsed.Aggregate((string left, string right) => left + ", " + right);

		private string ExtensionsNormalized => Extensions.Replace(" ", string.Empty).Replace(".", string.Empty).ToLowerInvariant();

		private IEnumerable<string> ExtensionsParsed => from e in ExtensionsNormalized.Split(',')
			select "." + e;

		public FileExtensionsAttribute()
			: base(DataType.Upload)
		{
			base.DefaultErrorMessage = System.SR.FileExtensionsAttribute_Invalid;
		}

		public override string FormatErrorMessage(string name)
		{
			return string.Format(CultureInfo.CurrentCulture, base.ErrorMessageString, name, ExtensionsFormatted);
		}

		public override bool IsValid(object? value)
		{
			if (value != null)
			{
				if (value is string fileName)
				{
					return ValidateExtension(fileName);
				}
				return false;
			}
			return true;
		}

		private bool ValidateExtension(string fileName)
		{
			return ExtensionsParsed.Contains(Path.GetExtension(fileName).ToLowerInvariant());
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	[Obsolete("This attribute is no longer in use and will be ignored if applied.")]
	public sealed class FilterUIHintAttribute : Attribute
	{
		private readonly UIHintAttribute.UIHintImplementation _implementation;

		public string FilterUIHint => _implementation.UIHint;

		public string? PresentationLayer => _implementation.PresentationLayer;

		public IDictionary<string, object?> ControlParameters => _implementation.ControlParameters;

		public FilterUIHintAttribute(string filterUIHint)
			: this(filterUIHint, null, Array.Empty<object>())
		{
		}

		public FilterUIHintAttribute(string filterUIHint, string? presentationLayer)
			: this(filterUIHint, presentationLayer, Array.Empty<object>())
		{
		}

		public FilterUIHintAttribute(string filterUIHint, string? presentationLayer, params object?[] controlParameters)
		{
			_implementation = new UIHintAttribute.UIHintImplementation(filterUIHint, presentationLayer, controlParameters);
		}

		public override int GetHashCode()
		{
			return _implementation.GetHashCode();
		}

		public override bool Equals(object? obj)
		{
			if (obj is FilterUIHintAttribute filterUIHintAttribute)
			{
				return _implementation.Equals(filterUIHintAttribute._implementation);
			}
			return false;
		}
	}
	public interface IValidatableObject
	{
		IEnumerable<ValidationResult> Validate(ValidationContext validationContext);
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
	public sealed class KeyAttribute : Attribute
	{
	}
	internal class LocalizableString
	{
		private readonly string _propertyName;

		private Func<string> _cachedResult;

		private string _propertyValue;

		private Type _resourceType;

		public string Value
		{
			get
			{
				return _propertyValue;
			}
			set
			{
				if (_propertyValue != value)
				{
					ClearCache();
					_propertyValue = value;
				}
			}
		}

		public Type ResourceType
		{
			get
			{
				return _resourceType;
			}
			set
			{
				if (_resourceType != value)
				{
					ClearCache();
					_resourceType = value;
				}
			}
		}

		public LocalizableString(string propertyName)
		{
			_propertyName = propertyName;
		}

		private void ClearCache()
		{
			_cachedResult = null;
		}

		public string GetLocalizableValue()
		{
			if (_cachedResult == null)
			{
				if (_propertyValue == null || _resourceType == null)
				{
					_cachedResult = () => _propertyValue;
				}
				else
				{
					PropertyInfo property = _resourceType.GetRuntimeProperty(_propertyValue);
					bool flag = false;
					if (!_resourceType.IsVisible || property == null || property.PropertyType != typeof(string))
					{
						flag = true;
					}
					else
					{
						MethodInfo getMethod = property.GetMethod;
						if (getMethod == null || !getMethod.IsPublic || !getMethod.IsStatic)
						{
							flag = true;
						}
					}
					if (flag)
					{
						string exceptionMessage = System.SR.Format(System.SR.LocalizableString_LocalizationFailed, _propertyName, _resourceType.FullName, _propertyValue);
						_cachedResult = delegate
						{
							throw new InvalidOperationException(exceptionMessage);
						};
					}
					else
					{
						_cachedResult = () => (string)property.GetValue(null, null);
					}
				}
			}
			return _cachedResult();
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public class MaxLengthAttribute : ValidationAttribute
	{
		public int Length { get; }

		private static string DefaultErrorMessageString => System.SR.MaxLengthAttribute_ValidationError;

		public MaxLengthAttribute(int length)
			: base(() => DefaultErrorMessageString)
		{
			Length = length;
		}

		public MaxLengthAttribute()
			: base(() => DefaultErrorMessageString)
		{
			Length = -1;
		}

		public override bool IsValid(object? value)
		{
			EnsureLegalLengths();
			if (value == null)
			{
				return true;
			}
			int num;
			if (value is string text)
			{
				num = text.Length;
			}
			else
			{
				if (!CountPropertyHelper.TryGetCount(value, out var count))
				{
					throw new InvalidCastException(System.SR.Format(System.SR.LengthAttribute_InvalidValueType, value.GetType()));
				}
				num = count;
			}
			if (-1 != Length)
			{
				return num <= Length;
			}
			return true;
		}

		public override string FormatErrorMessage(string name)
		{
			return string.Format(CultureInfo.CurrentCulture, base.ErrorMessageString, name, Length);
		}

		private void EnsureLegalLengths()
		{
			if (Length == 0 || Length < -1)
			{
				throw new InvalidOperationException(System.SR.MaxLengthAttribute_InvalidMaxLength);
			}
		}
	}
	internal static class CountPropertyHelper
	{
		public static bool TryGetCount(object value, out int count)
		{
			if (value is ICollection collection)
			{
				count = collection.Count;
				return true;
			}
			PropertyInfo runtimeProperty = value.GetType().GetRuntimeProperty("Count");
			if (runtimeProperty != null && runtimeProperty.CanRead && runtimeProperty.PropertyType == typeof(int))
			{
				count = (int)runtimeProperty.GetValue(value);
				return true;
			}
			count = -1;
			return false;
		}
	}
	internal class MetadataPropertyDescriptorWrapper : PropertyDescriptor
	{
		private readonly PropertyDescriptor _descriptor;

		private readonly bool _isReadOnly;

		public override Type ComponentType => _descriptor.ComponentType;

		public override bool IsReadOnly
		{
			get
			{
				if (!_isReadOnly)
				{
					return _descriptor.IsReadOnly;
				}
				return true;
			}
		}

		public override Type PropertyType => _descriptor.PropertyType;

		public override bool SupportsChangeEvents => _descriptor.SupportsChangeEvents;

		public MetadataPropertyDescriptorWrapper(PropertyDescriptor descriptor, Attribute[] newAttributes)
			: base(descriptor, newAttributes)
		{
			_descriptor = descriptor;
			_isReadOnly = newAttributes.OfType<ReadOnlyAttribute>().FirstOrDefault()?.IsReadOnly ?? false;
		}

		public override void AddValueChanged(object component, EventHandler handler)
		{
			_descriptor.AddValueChanged(component, handler);
		}

		public override bool CanResetValue(object component)
		{
			return _descriptor.CanResetValue(component);
		}

		public override object GetValue(object component)
		{
			return _descriptor.GetValue(component);
		}

		public override void RemoveValueChanged(object component, EventHandler handler)
		{
			_descriptor.RemoveValueChanged(component, handler);
		}

		public override void ResetValue(object component)
		{
			_descriptor.ResetValue(component);
		}

		public override void SetValue(object component, object value)
		{
			_descriptor.SetValue(component, value);
		}

		public override bool ShouldSerializeValue(object component)
		{
			return _descriptor.ShouldSerializeValue(component);
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
	public sealed class MetadataTypeAttribute : Attribute
	{
		private readonly Type _metadataClassType;

		public Type MetadataClassType
		{
			get
			{
				if (_metadataClassType == null)
				{
					throw new InvalidOperationException(System.SR.MetadataTypeAttribute_TypeCannotBeNull);
				}
				return _metadataClassType;
			}
		}

		public MetadataTypeAttribute(Type metadataClassType)
		{
			_metadataClassType = metadataClassType;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public class MinLengthAttribute : ValidationAttribute
	{
		public int Length { get; }

		public MinLengthAttribute(int length)
			: base(System.SR.MinLengthAttribute_ValidationError)
		{
			Length = length;
		}

		public override bool IsValid(object? value)
		{
			EnsureLegalLengths();
			if (value == null)
			{
				return true;
			}
			int num;
			if (value is string text)
			{
				num = text.Length;
			}
			else
			{
				if (!CountPropertyHelper.TryGetCount(value, out var count))
				{
					throw new InvalidCastException(System.SR.Format(System.SR.LengthAttribute_InvalidValueType, value.GetType()));
				}
				num = count;
			}
			return num >= Length;
		}

		public override string FormatErrorMessage(string name)
		{
			return string.Format(CultureInfo.CurrentCulture, base.ErrorMessageString, name, Length);
		}

		private void EnsureLegalLengths()
		{
			if (Length < 0)
			{
				throw new InvalidOperationException(System.SR.MinLengthAttribute_InvalidMinLength);
			}
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class PhoneAttribute : DataTypeAttribute
	{
		public PhoneAttribute()
			: base(DataType.PhoneNumber)
		{
			base.DefaultErrorMessage = System.SR.PhoneAttribute_Invalid;
		}

		public override bool IsValid(object? value)
		{
			if (value == null)
			{
				return true;
			}
			if (!(value is string text))
			{
				return false;
			}
			string potentialPhoneNumber = text.Replace("+", string.Empty).TrimEnd();
			potentialPhoneNumber = RemoveExtension(potentialPhoneNumber);
			bool flag = false;
			string text2 = potentialPhoneNumber;
			foreach (char c in text2)
			{
				if (char.IsDigit(c))
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				return false;
			}
			string text3 = potentialPhoneNumber;
			foreach (char c2 in text3)
			{
				if (!char.IsDigit(c2) && !char.IsWhiteSpace(c2) && "-.()".IndexOf(c2) == -1)
				{
					return false;
				}
			}
			return true;
		}

		private static string RemoveExtension(string potentialPhoneNumber)
		{
			int num = potentialPhoneNumber.LastIndexOf("ext.", StringComparison.OrdinalIgnoreCase);
			if (num >= 0)
			{
				string potentialExtension = potentialPhoneNumber.Substring(num + "ext.".Length);
				if (MatchesExtension(potentialExtension))
				{
					return potentialPhoneNumber.Substring(0, num);
				}
			}
			num = potentialPhoneNumber.LastIndexOf("ext", StringComparison.OrdinalIgnoreCase);
			if (num >= 0)
			{
				string potentialExtension2 = potentialPhoneNumber.Substring(num + "ext".Length);
				if (MatchesExtension(potentialExtension2))
				{
					return potentialPhoneNumber.Substring(0, num);
				}
			}
			num = potentialPhoneNumber.LastIndexOf("x", StringComparison.OrdinalIgnoreCase);
			if (num >= 0)
			{
				string potentialExtension3 = potentialPhoneNumber.Substring(num + "x".Length);
				if (MatchesExtension(potentialExtension3))
				{
					return potentialPhoneNumber.Substring(0, num);
				}
			}
			return potentialPhoneNumber;
		}

		private static bool MatchesExtension(string potentialExtension)
		{
			potentialExtension = potentialExtension.TrimStart();
			if (potentialExtension.Length == 0)
			{
				return false;
			}
			string text = potentialExtension;
			foreach (char c in text)
			{
				if (!char.IsDigit(c))
				{
					return false;
				}
			}
			return true;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public class RangeAttribute : ValidationAttribute
	{
		public object Minimum { get; private set; }

		public object Maximum { get; private set; }

		public Type OperandType { get; }

		public bool ParseLimitsInInvariantCulture { get; set; }

		public bool ConvertValueInInvariantCulture { get; set; }

		private Func<object, object?>? Conversion { get; set; }

		public RangeAttribute(int minimum, int maximum)
			: base(() => System.SR.RangeAttribute_ValidationError)
		{
			Minimum = minimum;
			Maximum = maximum;
			OperandType = typeof(int);
		}

		public RangeAttribute(double minimum, double maximum)
			: base(() => System.SR.RangeAttribute_ValidationError)
		{
			Minimum = minimum;
			Maximum = maximum;
			OperandType = typeof(double);
		}

		public RangeAttribute(Type type, string minimum, string maximum)
			: base(() => System.SR.RangeAttribute_ValidationError)
		{
			OperandType = type;
			Minimum = minimum;
			Maximum = maximum;
		}

		private void Initialize(IComparable minimum, IComparable maximum, Func<object, object> conversion)
		{
			if (minimum.CompareTo(maximum) > 0)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.RangeAttribute_MinGreaterThanMax, maximum, minimum));
			}
			Minimum = minimum;
			Maximum = maximum;
			Conversion = conversion;
		}

		public override bool IsValid(object? value)
		{
			SetupConversion();
			if (value != null)
			{
				string obj = value as string;
				if (obj == null || obj.Length != 0)
				{
					object obj2;
					try
					{
						obj2 = Conversion(value);
					}
					catch (FormatException)
					{
						return false;
					}
					catch (InvalidCastException)
					{
						return false;
					}
					catch (NotSupportedException)
					{
						return false;
					}
					IComparable comparable = (IComparable)Minimum;
					IComparable comparable2 = (IComparable)Maximum;
					if (comparable.CompareTo(obj2) <= 0)
					{
						return comparable2.CompareTo(obj2) >= 0;
					}
					return false;
				}
			}
			return true;
		}

		public override string FormatErrorMessage(string name)
		{
			SetupConversion();
			return string.Format(CultureInfo.CurrentCulture, base.ErrorMessageString, name, Minimum, Maximum);
		}

		private void SetupConversion()
		{
			if (Conversion != null)
			{
				return;
			}
			object minimum = Minimum;
			object maximum = Maximum;
			if (minimum == null || maximum == null)
			{
				throw new InvalidOperationException(System.SR.RangeAttribute_Must_Set_Min_And_Max);
			}
			Type type2 = minimum.GetType();
			if (type2 == typeof(int))
			{
				Initialize((int)minimum, (int)maximum, (object v) => Convert.ToInt32(v, CultureInfo.InvariantCulture));
				return;
			}
			if (type2 == typeof(double))
			{
				Initialize((double)minimum, (double)maximum, (object v) => Convert.ToDouble(v, CultureInfo.InvariantCulture));
				return;
			}
			Type type = OperandType;
			if (type == null)
			{
				throw new InvalidOperationException(System.SR.RangeAttribute_Must_Set_Operand_Type);
			}
			Type typeFromHandle = typeof(IComparable);
			if (!typeFromHandle.IsAssignableFrom(type))
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.RangeAttribute_ArbitraryTypeNotIComparable, type.FullName, typeFromHandle.FullName));
			}
			TypeConverter converter = TypeDescriptor.GetConverter(type);
			IComparable minimum2 = (IComparable)(ParseLimitsInInvariantCulture ? converter.ConvertFromInvariantString((string)minimum) : converter.ConvertFromString((string)minimum));
			IComparable maximum2 = (IComparable)(ParseLimitsInInvariantCulture ? converter.ConvertFromInvariantString((string)maximum) : converter.ConvertFromString((string)maximum));
			Func<object, object> conversion = ((!ConvertValueInInvariantCulture) ? ((Func<object, object>)((object value) => (!(value.GetType() == type)) ? converter.ConvertFrom(value) : value)) : ((Func<object, object>)((object value) => (!(value.GetType() == type)) ? converter.ConvertFrom(null, CultureInfo.InvariantCulture, value) : value)));
			Initialize(minimum2, maximum2, conversion);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public class RegularExpressionAttribute : ValidationAttribute
	{
		public int MatchTimeoutInMilliseconds { get; set; }

		public string Pattern { get; }

		private Regex? Regex { get; set; }

		public RegularExpressionAttribute(string pattern)
			: base(() => System.SR.RegexAttribute_ValidationError)
		{
			Pattern = pattern;
			MatchTimeoutInMilliseconds = 2000;
		}

		public override bool IsValid(object? value)
		{
			SetupRegex();
			string text = Convert.ToString(value, CultureInfo.CurrentCulture);
			if (string.IsNullOrEmpty(text))
			{
				return true;
			}
			Match match = Regex.Match(text);
			if (match.Success && match.Index == 0)
			{
				return match.Length == text.Length;
			}
			return false;
		}

		public override string FormatErrorMessage(string name)
		{
			SetupRegex();
			return string.Format(CultureInfo.CurrentCulture, base.ErrorMessageString, name, Pattern);
		}

		private void SetupRegex()
		{
			if (Regex == null)
			{
				if (string.IsNullOrEmpty(Pattern))
				{
					throw new InvalidOperationException(System.SR.RegularExpressionAttribute_Empty_Pattern);
				}
				Regex = ((MatchTimeoutInMilliseconds == -1) ? new Regex(Pattern) : new Regex(Pattern, RegexOptions.None, TimeSpan.FromMilliseconds(MatchTimeoutInMilliseconds)));
			}
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public class RequiredAttribute : ValidationAttribute
	{
		public bool AllowEmptyStrings { get; set; }

		public RequiredAttribute()
			: base(() => System.SR.RequiredAttribute_ValidationError)
		{
		}

		public override bool IsValid(object? value)
		{
			if (value == null)
			{
				return false;
			}
			if (!AllowEmptyStrings && value is string value2)
			{
				return !string.IsNullOrWhiteSpace(value2);
			}
			return true;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class ScaffoldColumnAttribute : Attribute
	{
		public bool Scaffold { get; }

		public ScaffoldColumnAttribute(bool scaffold)
		{
			Scaffold = scaffold;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public class StringLengthAttribute : ValidationAttribute
	{
		public int MaximumLength { get; }

		public int MinimumLength { get; set; }

		public StringLengthAttribute(int maximumLength)
			: base(() => System.SR.StringLengthAttribute_ValidationError)
		{
			MaximumLength = maximumLength;
		}

		public override bool IsValid(object? value)
		{
			EnsureLegalLengths();
			if (value == null)
			{
				return true;
			}
			int length = ((string)value).Length;
			if (length >= MinimumLength)
			{
				return length <= MaximumLength;
			}
			return false;
		}

		public override string FormatErrorMessage(string name)
		{
			EnsureLegalLengths();
			string format = ((MinimumLength != 0 && !base.CustomErrorMessageSet) ? System.SR.StringLengthAttribute_ValidationErrorIncludingMinimum : base.ErrorMessageString);
			return string.Format(CultureInfo.CurrentCulture, format, name, MaximumLength, MinimumLength);
		}

		private void EnsureLegalLengths()
		{
			if (MaximumLength < 0)
			{
				throw new InvalidOperationException(System.SR.StringLengthAttribute_InvalidMaxLength);
			}
			if (MaximumLength < MinimumLength)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.RangeAttribute_MinGreaterThanMax, MaximumLength, MinimumLength));
			}
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
	public sealed class TimestampAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
	public class UIHintAttribute : Attribute
	{
		internal class UIHintImplementation
		{
			private readonly object[] _inputControlParameters;

			private IDictionary<string, object> _controlParameters;

			public string UIHint { get; }

			public string PresentationLayer { get; }

			public IDictionary<string, object> ControlParameters => _controlParameters ?? (_controlParameters = BuildControlParametersDictionary());

			public UIHintImplementation(string uiHint, string presentationLayer, params object[] controlParameters)
			{
				UIHint = uiHint;
				PresentationLayer = presentationLayer;
				if (controlParameters != null)
				{
					_inputControlParameters = new object[controlParameters.Length];
					Array.Copy(controlParameters, _inputControlParameters, controlParameters.Length);
				}
			}

			public override int GetHashCode()
			{
				string text = UIHint ?? string.Empty;
				string text2 = PresentationLayer ?? string.Empty;
				return text.GetHashCode() ^ text2.GetHashCode();
			}

			public override bool Equals(object obj)
			{
				if (!(obj is UIHintImplementation uIHintImplementation) || UIHint != uIHintImplementation.UIHint || PresentationLayer != uIHintImplementation.PresentationLayer)
				{
					return false;
				}
				IDictionary<string, object> controlParameters;
				IDictionary<string, object> controlParameters2;
				try
				{
					controlParameters = ControlParameters;
					controlParameters2 = uIHintImplementation.ControlParameters;
				}
				catch (InvalidOperationException)
				{
					return false;
				}
				if (controlParameters.Count != controlParameters2.Count)
				{
					return false;
				}
				return controlParameters.OrderBy((KeyValuePair<string, object> p) => p.Key).SequenceEqual(controlParameters2.OrderBy((KeyValuePair<string, object> p) => p.Key));
			}

			private IDictionary<string, object> BuildControlParametersDictionary()
			{
				IDictionary<string, object> dictionary = new Dictionary<string, object>();
				object[] inputControlParameters = _inputControlParameters;
				if (inputControlParameters == null || inputControlParameters.Length == 0)
				{
					return dictionary;
				}
				if (inputControlParameters.Length % 2 != 0)
				{
					throw new InvalidOperationException(System.SR.UIHintImplementation_NeedEvenNumberOfControlParameters);
				}
				for (int i = 0; i < inputControlParameters.Length; i += 2)
				{
					object obj = inputControlParameters[i];
					object value = inputControlParameters[i + 1];
					if (obj == null)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.UIHintImplementation_ControlParameterKeyIsNull, i));
					}
					if (!(obj is string text))
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.UIHintImplementation_ControlParameterKeyIsNotAString, i, inputControlParameters[i].ToString()));
					}
					if (dictionary.ContainsKey(text))
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.UIHintImplementation_ControlParameterKeyOccursMoreThanOnce, i, text));
					}
					dictionary[text] = value;
				}
				return dictionary;
			}
		}

		private readonly UIHintImplementation _implementation;

		public string UIHint => _implementation.UIHint;

		public string? PresentationLayer => _implementation.PresentationLayer;

		public IDictionary<string, object?> ControlParameters => _implementation.ControlParameters;

		public UIHintAttribute(string uiHint)
			: this(uiHint, null, Array.Empty<object>())
		{
		}

		public UIHintAttribute(string uiHint, string? presentationLayer)
			: this(uiHint, presentationLayer, Array.Empty<object>())
		{
		}

		public UIHintAttribute(string uiHint, string? presentationLayer, params object?[]? controlParameters)
		{
			_implementation = new UIHintImplementation(uiHint, presentationLayer, controlParameters);
		}

		public override int GetHashCode()
		{
			return _implementation.GetHashCode();
		}

		public override bool Equals(object? obj)
		{
			if (obj is UIHintAttribute uIHintAttribute)
			{
				return _implementation.Equals(uIHintAttribute._implementation);
			}
			return false;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class UrlAttribute : DataTypeAttribute
	{
		public UrlAttribute()
			: base(DataType.Url)
		{
			base.DefaultErrorMessage = System.SR.UrlAttribute_Invalid;
		}

		public override bool IsValid(object? value)
		{
			if (value == null)
			{
				return true;
			}
			if (value is string text)
			{
				if (!text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !text.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
				{
					return text.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase);
				}
				return true;
			}
			return false;
		}
	}
	public abstract class ValidationAttribute : Attribute
	{
		private string _errorMessage;

		private Func<string> _errorMessageResourceAccessor;

		private string _errorMessageResourceName;

		private Type _errorMessageResourceType;

		private volatile bool _hasBaseIsValid;

		private string _defaultErrorMessage;

		internal string? DefaultErrorMessage
		{
			set
			{
				_defaultErrorMessage = value;
				_errorMessageResourceAccessor = null;
				CustomErrorMessageSet = true;
			}
		}

		protected string ErrorMessageString
		{
			get
			{
				SetupResourceAccessor();
				return _errorMessageResourceAccessor();
			}
		}

		internal bool CustomErrorMessageSet { get; private set; }

		public virtual bool RequiresValidationContext => false;

		public string? ErrorMessage
		{
			get
			{
				return _errorMessage ?? _defaultErrorMessage;
			}
			set
			{
				_errorMessage = value;
				_errorMessageResourceAccessor = null;
				CustomErrorMessageSet = true;
				if (value == null)
				{
					_defaultErrorMessage = null;
				}
			}
		}

		public string? ErrorMessageResourceName
		{
			get
			{
				return _errorMessageResourceName;
			}
			set
			{
				_errorMessageResourceName = value;
				_errorMessageResourceAccessor = null;
				CustomErrorMessageSet = true;
			}
		}

		public Type? ErrorMessageResourceType
		{
			get
			{
				return _errorMessageResourceType;
			}
			set
			{
				_errorMessageResourceType = value;
				_errorMessageResourceAccessor = null;
				CustomErrorMessageSet = true;
			}
		}

		protected ValidationAttribute()
			: this(() => System.SR.ValidationAttribute_ValidationError)
		{
		}

		protected ValidationAttribute(string errorMessage)
		{
			string errorMessage2 = errorMessage;
			this..ctor(() => errorMessage2);
		}

		protected ValidationAttribute(Func<string> errorMessageAccessor)
		{
			_errorMessageResourceAccessor = errorMessageAccessor;
		}

		private void SetupResourceAccessor()
		{
			if (_errorMessageResourceAccessor != null)
			{
				return;
			}
			string localErrorMessage = ErrorMessage;
			bool flag = !string.IsNullOrEmpty(_errorMessageResourceName);
			bool flag2 = !string.IsNullOrEmpty(_errorMessage);
			bool flag3 = _errorMessageResourceType != null;
			bool flag4 = !string.IsNullOrEmpty(_defaultErrorMessage);
			if ((flag && flag2) || !(flag || flag2 || flag4))
			{
				throw new InvalidOperationException(System.SR.ValidationAttribute_Cannot_Set_ErrorMessage_And_Resource);
			}
			if (flag3 != flag)
			{
				throw new InvalidOperationException(System.SR.ValidationAttribute_NeedBothResourceTypeAndResourceName);
			}
			if (flag)
			{
				SetResourceAccessorByPropertyLookup();
				return;
			}
			_errorMessageResourceAccessor = () => localErrorMessage;
		}

		private void SetResourceAccessorByPropertyLookup()
		{
			PropertyInfo property = _errorMessageResourceType.GetTypeInfo().GetDeclaredProperty(_errorMessageResourceName);
			if (property != null && !ValidationAttributeStore.IsStatic(property))
			{
				property = null;
			}
			if (property != null)
			{
				MethodInfo getMethod = property.GetMethod;
				if (getMethod == null || (!getMethod.IsAssembly && !getMethod.IsPublic))
				{
					property = null;
				}
			}
			if (property == null)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.ValidationAttribute_ResourceTypeDoesNotHaveProperty, _errorMessageResourceType.FullName, _errorMessageResourceName));
			}
			if (property.PropertyType != typeof(string))
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.ValidationAttribute_ResourcePropertyNotStringType, property.Name, _errorMessageResourceType.FullName));
			}
			_errorMessageResourceAccessor = () => (string)property.GetValue(null, null);
		}

		public virtual string FormatErrorMessage(string name)
		{
			return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
		}

		public virtual bool IsValid(object? value)
		{
			if (!_hasBaseIsValid)
			{
				_hasBaseIsValid = true;
			}
			return IsValid(value, null) == ValidationResult.Success;
		}

		protected virtual ValidationResult? IsValid(object? value, ValidationContext validationContext)
		{
			if (_hasBaseIsValid)
			{
				throw System.NotImplemented.ByDesignWithMessage(System.SR.ValidationAttribute_IsValid_NotImplemented);
			}
			ValidationResult result = ValidationResult.Success;
			if (!IsValid(value))
			{
				string memberName = validationContext.MemberName;
				string[] memberNames = ((memberName == null) ? null : new string[1] { memberName });
				result = new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames);
			}
			return result;
		}

		public ValidationResult? GetValidationResult(object? value, ValidationContext validationContext)
		{
			if (validationContext == null)
			{
				throw new ArgumentNullException("validationContext");
			}
			ValidationResult validationResult = IsValid(value, validationContext);
			if (validationResult != null && string.IsNullOrEmpty(validationResult.ErrorMessage))
			{
				string errorMessage = FormatErrorMessage(validationContext.DisplayName);
				validationResult = new ValidationResult(errorMessage, validationResult.MemberNames);
			}
			return validationResult;
		}

		public void Validate(object? value, string name)
		{
			if (!IsValid(value))
			{
				throw new ValidationException(FormatErrorMessage(name), this, value);
			}
		}

		public void Validate(object? value, ValidationContext validationContext)
		{
			if (validationContext == null)
			{
				throw new ArgumentNullException("validationContext");
			}
			ValidationResult validationResult = GetValidationResult(value, validationContext);
			if (validationResult != null)
			{
				throw new ValidationException(validationResult, this, value);
			}
		}
	}
	internal class ValidationAttributeStore
	{
		private abstract class StoreItem
		{
			internal IEnumerable<ValidationAttribute> ValidationAttributes { get; }

			internal DisplayAttribute DisplayAttribute { get; }

			internal StoreItem(IEnumerable<Attribute> attributes)
			{
				ValidationAttributes = attributes.OfType<ValidationAttribute>();
				DisplayAttribute = attributes.OfType<DisplayAttribute>().SingleOrDefault();
			}
		}

		private class TypeStoreItem : StoreItem
		{
			private readonly object _syncRoot = new object();

			private readonly Type _type;

			private Dictionary<string, PropertyStoreItem> _propertyStoreItems;

			internal TypeStoreItem(Type type, IEnumerable<Attribute> attributes)
				: base(attributes)
			{
				_type = type;
			}

			internal PropertyStoreItem GetPropertyStoreItem(string propertyName)
			{
				if (!TryGetPropertyStoreItem(propertyName, out var item))
				{
					throw new ArgumentException(System.SR.Format(System.SR.AttributeStore_Unknown_Property, _type.Name, propertyName), "propertyName");
				}
				return item;
			}

			internal bool TryGetPropertyStoreItem(string propertyName, [NotNullWhen(true)] out PropertyStoreItem item)
			{
				if (string.IsNullOrEmpty(propertyName))
				{
					throw new ArgumentNullException("propertyName");
				}
				if (_propertyStoreItems == null)
				{
					lock (_syncRoot)
					{
						if (_propertyStoreItems == null)
						{
							_propertyStoreItems = CreatePropertyStoreItems();
						}
					}
				}
				return _propertyStoreItems.TryGetValue(propertyName, out item);
			}

			private Dictionary<string, PropertyStoreItem> CreatePropertyStoreItems()
			{
				Dictionary<string, PropertyStoreItem> dictionary = new Dictionary<string, PropertyStoreItem>();
				IEnumerable<PropertyInfo> enumerable = from prop in _type.GetRuntimeProperties()
					where IsPublic(prop) && !prop.GetIndexParameters().Any()
					select prop;
				foreach (PropertyInfo item in enumerable)
				{
					PropertyStoreItem value = new PropertyStoreItem(item.PropertyType, CustomAttributeExtensions.GetCustomAttributes(item, inherit: true));
					dictionary[item.Name] = value;
				}
				return dictionary;
			}
		}

		private class PropertyStoreItem : StoreItem
		{
			internal Type PropertyType { get; }

			internal PropertyStoreItem(Type propertyType, IEnumerable<Attribute> attributes)
				: base(attributes)
			{
				PropertyType = propertyType;
			}
		}

		private readonly Dictionary<Type, TypeStoreItem> _typeStoreItems = new Dictionary<Type, TypeStoreItem>();

		internal static ValidationAttributeStore Instance { get; } = new ValidationAttributeStore();


		internal IEnumerable<ValidationAttribute> GetTypeValidationAttributes(ValidationContext validationContext)
		{
			EnsureValidationContext(validationContext);
			TypeStoreItem typeStoreItem = GetTypeStoreItem(validationContext.ObjectType);
			return typeStoreItem.ValidationAttributes;
		}

		internal DisplayAttribute GetTypeDisplayAttribute(ValidationContext validationContext)
		{
			EnsureValidationContext(validationContext);
			TypeStoreItem typeStoreItem = GetTypeStoreItem(validationContext.ObjectType);
			return typeStoreItem.DisplayAttribute;
		}

		internal IEnumerable<ValidationAttribute> GetPropertyValidationAttributes(ValidationContext validationContext)
		{
			EnsureValidationContext(validationContext);
			TypeStoreItem typeStoreItem = GetTypeStoreItem(validationContext.ObjectType);
			PropertyStoreItem propertyStoreItem = typeStoreItem.GetPropertyStoreItem(validationContext.MemberName);
			return propertyStoreItem.ValidationAttributes;
		}

		internal DisplayAttribute GetPropertyDisplayAttribute(ValidationContext validationContext)
		{
			EnsureValidationContext(validationContext);
			TypeStoreItem typeStoreItem = GetTypeStoreItem(validationContext.ObjectType);
			PropertyStoreItem propertyStoreItem = typeStoreItem.GetPropertyStoreItem(validationContext.MemberName);
			return propertyStoreItem.DisplayAttribute;
		}

		internal Type GetPropertyType(ValidationContext validationContext)
		{
			EnsureValidationContext(validationContext);
			TypeStoreItem typeStoreItem = GetTypeStoreItem(validationContext.ObjectType);
			PropertyStoreItem propertyStoreItem = typeStoreItem.GetPropertyStoreItem(validationContext.MemberName);
			return propertyStoreItem.PropertyType;
		}

		internal bool IsPropertyContext(ValidationContext validationContext)
		{
			EnsureValidationContext(validationContext);
			TypeStoreItem typeStoreItem = GetTypeStoreItem(validationContext.ObjectType);
			PropertyStoreItem item;
			return typeStoreItem.TryGetPropertyStoreItem(validationContext.MemberName, out item);
		}

		private TypeStoreItem GetTypeStoreItem(Type type)
		{
			lock (_typeStoreItems)
			{
				if (!_typeStoreItems.TryGetValue(type, out var value))
				{
					IEnumerable<Attribute> customAttributes = CustomAttributeExtensions.GetCustomAttributes(type, inherit: true);
					value = new TypeStoreItem(type, customAttributes);
					_typeStoreItems[type] = value;
				}
				return value;
			}
		}

		private static void EnsureValidationContext(ValidationContext validationContext)
		{
			if (validationContext == null)
			{
				throw new ArgumentNullException("validationContext");
			}
		}

		internal static bool IsPublic(PropertyInfo p)
		{
			if (!(p.GetMethod != null) || !p.GetMethod.IsPublic)
			{
				if (p.SetMethod != null)
				{
					return p.SetMethod.IsPublic;
				}
				return false;
			}
			return true;
		}

		internal static bool IsStatic(PropertyInfo p)
		{
			if (!(p.GetMethod != null) || !p.GetMethod.IsStatic)
			{
				if (p.SetMethod != null)
				{
					return p.SetMethod.IsStatic;
				}
				return false;
			}
			return true;
		}
	}
	public sealed class ValidationContext : IServiceProvider
	{
		private readonly Dictionary<object, object> _items;

		private string _displayName;

		private Func<Type, object> _serviceProvider;

		public object ObjectInstance { get; }

		public Type ObjectType => ObjectInstance.GetType();

		public string DisplayName
		{
			get
			{
				if (string.IsNullOrEmpty(_displayName))
				{
					_displayName = GetDisplayName();
					if (string.IsNullOrEmpty(_displayName))
					{
						_displayName = ObjectType.Name;
					}
				}
				return _displayName;
			}
			set
			{
				if (string.IsNullOrEmpty(value))
				{
					throw new ArgumentNullException("value");
				}
				_displayName = value;
			}
		}

		public string? MemberName { get; set; }

		public IDictionary<object, object?> Items => _items;

		public ValidationContext(object instance)
			: this(instance, null, null)
		{
		}

		public ValidationContext(object instance, IDictionary<object, object?>? items)
			: this(instance, null, items)
		{
		}

		public ValidationContext(object instance, IServiceProvider? serviceProvider, IDictionary<object, object?>? items)
		{
			IServiceProvider serviceProvider2 = serviceProvider;
			base..ctor();
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			if (serviceProvider2 != null)
			{
				InitializeServiceProvider((Type serviceType) => serviceProvider2.GetService(serviceType));
			}
			_items = ((items != null) ? new Dictionary<object, object>(items) : new Dictionary<object, object>());
			ObjectInstance = instance;
		}

		private string GetDisplayName()
		{
			string text = null;
			ValidationAttributeStore instance = ValidationAttributeStore.Instance;
			DisplayAttribute displayAttribute = null;
			if (string.IsNullOrEmpty(MemberName))
			{
				displayAttribute = instance.GetTypeDisplayAttribute(this);
			}
			else if (instance.IsPropertyContext(this))
			{
				displayAttribute = instance.GetPropertyDisplayAttribute(this);
			}
			if (displayAttribute != null)
			{
				text = displayAttribute.GetName();
			}
			return text ?? MemberName;
		}

		public void InitializeServiceProvider(Func<Type, object?> serviceProvider)
		{
			_serviceProvider = serviceProvider;
		}

		public object? GetService(Type serviceType)
		{
			return _serviceProvider?.Invoke(serviceType);
		}
	}
	[Serializable]
	[TypeForwardedFrom("System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
	public class ValidationException : Exception
	{
		private ValidationResult _validationResult;

		public ValidationAttribute? ValidationAttribute { get; }

		public ValidationResult ValidationResult => _validationResult ?? (_validationResult = new ValidationResult(Message));

		public object? Value { get; }

		public ValidationException(ValidationResult validationResult, ValidationAttribute? validatingAttribute, object? value)
			: this(validationResult.ErrorMessage, validatingAttribute, value)
		{
			_validationResult = validationResult;
		}

		public ValidationException(string? errorMessage, ValidationAttribute? validatingAttribute, object? value)
			: base(errorMessage)
		{
			Value = value;
			ValidationAttribute = validatingAttribute;
		}

		public ValidationException()
		{
		}

		public ValidationException(string? message)
			: base(message)
		{
		}

		public ValidationException(string? message, Exception? innerException)
			: base(message, innerException)
		{
		}

		protected ValidationException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	public class ValidationResult
	{
		public static readonly ValidationResult? Success;

		public IEnumerable<string> MemberNames { get; }

		public string? ErrorMessage { get; set; }

		public ValidationResult(string? errorMessage)
			: this(errorMessage, null)
		{
		}

		public ValidationResult(string? errorMessage, IEnumerable<string>? memberNames)
		{
			ErrorMessage = errorMessage;
			MemberNames = memberNames ?? Array.Empty<string>();
		}

		protected ValidationResult(ValidationResult validationResult)
		{
			if (validationResult == null)
			{
				throw new ArgumentNullException("validationResult");
			}
			ErrorMessage = validationResult.ErrorMessage;
			MemberNames = validationResult.MemberNames;
		}

		public override string ToString()
		{
			return ErrorMessage ?? base.ToString();
		}
	}
	public static class Validator
	{
		private class ValidationError
		{
			private readonly object _value;

			private readonly ValidationAttribute _validationAttribute;

			internal ValidationResult ValidationResult { get; }

			internal ValidationError(ValidationAttribute validationAttribute, object value, ValidationResult validationResult)
			{
				_validationAttribute = validationAttribute;
				ValidationResult = validationResult;
				_value = value;
			}

			internal void ThrowValidationException()
			{
				throw new ValidationException(ValidationResult, _validationAttribute, _value);
			}
		}

		private static readonly ValidationAttributeStore _store = ValidationAttributeStore.Instance;

		public static bool TryValidateProperty(object? value, ValidationContext validationContext, ICollection<ValidationResult>? validationResults)
		{
			Type propertyType = _store.GetPropertyType(validationContext);
			string memberName = validationContext.MemberName;
			EnsureValidPropertyType(memberName, propertyType, value);
			bool result = true;
			bool breakOnFirstError = validationResults == null;
			IEnumerable<ValidationAttribute> propertyValidationAttributes = _store.GetPropertyValidationAttributes(validationContext);
			foreach (ValidationError validationError in GetValidationErrors(value, validationContext, propertyValidationAttributes, breakOnFirstError))
			{
				result = false;
				validationResults?.Add(validationError.ValidationResult);
			}
			return result;
		}

		public static bool TryValidateObject(object instance, ValidationContext validationContext, ICollection<ValidationResult>? validationResults)
		{
			return TryValidateObject(instance, validationContext, validationResults, validateAllProperties: false);
		}

		public static bool TryValidateObject(object instance, ValidationContext validationContext, ICollection<ValidationResult>? validationResults, bool validateAllProperties)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			if (validationContext != null && instance != validationContext.ObjectInstance)
			{
				throw new ArgumentException(System.SR.Validator_InstanceMustMatchValidationContextInstance, "instance");
			}
			bool result = true;
			bool breakOnFirstError = validationResults == null;
			foreach (ValidationError objectValidationError in GetObjectValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError))
			{
				result = false;
				validationResults?.Add(objectValidationError.ValidationResult);
			}
			return result;
		}

		public static bool TryValidateValue(object value, ValidationContext validationContext, ICollection<ValidationResult>? validationResults, IEnumerable<ValidationAttribute> validationAttributes)
		{
			bool result = true;
			bool breakOnFirstError = validationResults == null;
			foreach (ValidationError validationError in GetValidationErrors(value, validationContext, validationAttributes, breakOnFirstError))
			{
				result = false;
				validationResults?.Add(validationError.ValidationResult);
			}
			return result;
		}

		public static void ValidateProperty(object? value, ValidationContext validationContext)
		{
			Type propertyType = _store.GetPropertyType(validationContext);
			EnsureValidPropertyType(validationContext.MemberName, propertyType, value);
			IEnumerable<ValidationAttribute> propertyValidationAttributes = _store.GetPropertyValidationAttributes(validationContext);
			GetValidationErrors(value, validationContext, propertyValidationAttributes, breakOnFirstError: false).FirstOrDefault()?.ThrowValidationException();
		}

		public static void ValidateObject(object instance, ValidationContext validationContext)
		{
			ValidateObject(instance, validationContext, validateAllProperties: false);
		}

		public static void ValidateObject(object instance, ValidationContext validationContext, bool validateAllProperties)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			if (validationContext == null)
			{
				throw new ArgumentNullException("validationContext");
			}
			if (instance != validationContext.ObjectInstance)
			{
				throw new ArgumentException(System.SR.Validator_InstanceMustMatchValidationContextInstance, "instance");
			}
			GetObjectValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError: false).FirstOrDefault()?.ThrowValidationException();
		}

		public static void ValidateValue(object value, ValidationContext validationContext, IEnumerable<ValidationAttribute> validationAttributes)
		{
			if (validationContext == null)
			{
				throw new ArgumentNullException("validationContext");
			}
			GetValidationErrors(value, validationContext, validationAttributes, breakOnFirstError: false).FirstOrDefault()?.ThrowValidationException();
		}

		private static ValidationContext CreateValidationContext(object instance, ValidationContext validationContext)
		{
			return new ValidationContext(instance, validationContext, validationContext.Items);
		}

		private static bool CanBeAssigned(Type destinationType, object value)
		{
			if (value == null)
			{
				if (destinationType.IsValueType)
				{
					if (destinationType.IsGenericType)
					{
						return destinationType.GetGenericTypeDefinition() == typeof(Nullable<>);
					}
					return false;
				}
				return true;
			}
			return destinationType.IsInstanceOfType(value);
		}

		private static void EnsureValidPropertyType(string propertyName, Type propertyType, object value)
		{
			if (!CanBeAssigned(propertyType, value))
			{
				throw new ArgumentException(System.SR.Format(System.SR.Validator_Property_Value_Wrong_Type, propertyName, propertyType), "value");
			}
		}

		private static IEnumerable<ValidationError> GetObjectValidationErrors(object instance, ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError)
		{
			if (validationContext == null)
			{
				throw new ArgumentNullException("validationContext");
			}
			List<ValidationError> list = new List<ValidationError>();
			list.AddRange(GetObjectPropertyValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError));
			if (list.Any())
			{
				return list;
			}
			IEnumerable<ValidationAttribute> typeValidationAttributes = _store.GetTypeValidationAttributes(validationContext);
			list.AddRange(GetValidationErrors(instance, validationContext, typeValidationAttributes, breakOnFirstError));
			if (list.Any())
			{
				return list;
			}
			if (instance is IValidatableObject validatableObject)
			{
				IEnumerable<ValidationResult> enumerable = validatableObject.Validate(validationContext);
				if (enumerable != null)
				{
					foreach (ValidationResult item in enumerable.Where((ValidationResult r) => r != ValidationResult.Success))
					{
						list.Add(new ValidationError(null, instance, item));
					}
				}
			}
			return list;
		}

		private static IEnumerable<ValidationError> GetObjectPropertyValidationErrors(object instance, ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError)
		{
			ICollection<KeyValuePair<ValidationContext, object>> propertyValues = GetPropertyValues(instance, validationContext);
			List<ValidationError> list = new List<ValidationError>();
			foreach (KeyValuePair<ValidationContext, object> item in propertyValues)
			{
				IEnumerable<ValidationAttribute> propertyValidationAttributes = _store.GetPropertyValidationAttributes(item.Key);
				if (validateAllProperties)
				{
					list.AddRange(GetValidationErrors(item.Value, item.Key, propertyValidationAttributes, breakOnFirstError));
				}
				else
				{
					RequiredAttribute requiredAttribute = propertyValidationAttributes.OfType<RequiredAttribute>().FirstOrDefault();
					if (requiredAttribute != null)
					{
						ValidationResult validationResult = requiredAttribute.GetValidationResult(item.Value, item.Key);
						if (validationResult != ValidationResult.Success)
						{
							list.Add(new ValidationError(requiredAttribute, item.Value, validationResult));
						}
					}
				}
				if (breakOnFirstError && list.Any())
				{
					break;
				}
			}
			return list;
		}

		private static ICollection<KeyValuePair<ValidationContext, object>> GetPropertyValues(object instance, ValidationContext validationContext)
		{
			IEnumerable<PropertyInfo> enumerable = from p in instance.GetType().GetRuntimeProperties()
				where ValidationAttributeStore.IsPublic(p) && !p.GetIndexParameters().Any()
				select p;
			List<KeyValuePair<ValidationContext, object>> list = new List<KeyValuePair<ValidationContext, object>>(enumerable.Count());
			foreach (PropertyInfo item in enumerable)
			{
				ValidationContext validationContext2 = CreateValidationContext(instance, validationContext);
				validationContext2.MemberName = item.Name;
				if (_store.GetPropertyValidationAttributes(validationContext2).Any())
				{
					list.Add(new KeyValuePair<ValidationContext, object>(validationContext2, item.GetValue(instance, null)));
				}
			}
			return list;
		}

		private static IEnumerable<ValidationError> GetValidationErrors(object value, ValidationContext validationContext, IEnumerable<ValidationAttribute> attributes, bool breakOnFirstError)
		{
			if (validationContext == null)
			{
				throw new ArgumentNullException("validationContext");
			}
			List<ValidationError> list = new List<ValidationError>();
			RequiredAttribute requiredAttribute = attributes.OfType<RequiredAttribute>().FirstOrDefault();
			if (requiredAttribute != null && !TryValidate(value, validationContext, requiredAttribute, out var validationError))
			{
				list.Add(validationError);
				return list;
			}
			foreach (ValidationAttribute attribute in attributes)
			{
				if (attribute != requiredAttribute && !TryValidate(value, validationContext, attribute, out validationError))
				{
					list.Add(validationError);
					if (breakOnFirstError)
					{
						break;
					}
				}
			}
			return list;
		}

		private static bool TryValidate(object value, ValidationContext validationContext, ValidationAttribute attribute, [NotNullWhen(false)] out ValidationError validationError)
		{
			ValidationResult validationResult = attribute.GetValidationResult(value, validationContext);
			if (validationResult != ValidationResult.Success)
			{
				validationError = new ValidationError(attribute, value, validationResult);
				return false;
			}
			validationError = null;
			return true;
		}
	}
}
namespace System.ComponentModel.DataAnnotations.Schema
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class ColumnAttribute : Attribute
	{
		private int _order = -1;

		private string _typeName;

		public string? Name { get; }

		public int Order
		{
			get
			{
				return _order;
			}
			set
			{
				if (value < 0)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_order = value;
			}
		}

		public string? TypeName
		{
			get
			{
				return _typeName;
			}
			[param: DisallowNull]
			set
			{
				if (string.IsNullOrWhiteSpace(value))
				{
					throw new ArgumentException(System.SR.Format(System.SR.ArgumentIsNullOrWhitespace, "value"), "value");
				}
				_typeName = value;
			}
		}

		public ColumnAttribute()
		{
		}

		public ColumnAttribute(string name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentIsNullOrWhitespace, "name"), "name");
			}
			Name = name;
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
	public class ComplexTypeAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class DatabaseGeneratedAttribute : Attribute
	{
		public DatabaseGeneratedOption DatabaseGeneratedOption { get; }

		public DatabaseGeneratedAttribute(DatabaseGeneratedOption databaseGeneratedOption)
		{
			if (!Enum.IsDefined(typeof(DatabaseGeneratedOption), databaseGeneratedOption))
			{
				throw new ArgumentOutOfRangeException("databaseGeneratedOption");
			}
			DatabaseGeneratedOption = databaseGeneratedOption;
		}
	}
	public enum DatabaseGeneratedOption
	{
		None,
		Identity,
		Computed
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class ForeignKeyAttribute : Attribute
	{
		public string Name { get; }

		public ForeignKeyAttribute(string name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentIsNullOrWhitespace, "name"), "name");
			}
			Name = name;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class InversePropertyAttribute : Attribute
	{
		public string Property { get; }

		public InversePropertyAttribute(string property)
		{
			if (string.IsNullOrWhiteSpace(property))
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentIsNullOrWhitespace, "property"), "property");
			}
			Property = property;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class NotMappedAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
	public class TableAttribute : Attribute
	{
		private string _schema;

		public string Name { get; }

		public string? Schema
		{
			get
			{
				return _schema;
			}
			[param: DisallowNull]
			set
			{
				if (string.IsNullOrWhiteSpace(value))
				{
					throw new ArgumentException(System.SR.Format(System.SR.ArgumentIsNullOrWhitespace, "value"), "value");
				}
				_schema = value;
			}
		}

		public TableAttribute(string name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentIsNullOrWhitespace, "name"), "name");
			}
			Name = name;
		}
	}
}

System.Diagnostics.DiagnosticSource.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Net;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using FxResources.System.Diagnostics.DiagnosticSource;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Diagnostics.DiagnosticSource")]
[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("Provides Classes that allow you to decouple code logging rich (unserializable) diagnostics/telemetry (e.g. framework) from code that consumes it (e.g. tools)\r\n\r\nCommonly Used Types:\r\nSystem.Diagnostics.DiagnosticListener\r\nSystem.Diagnostics.DiagnosticSource")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Diagnostics.DiagnosticSource")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
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]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : 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.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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.Diagnostics.DiagnosticSource
{
	internal static class SR
	{
	}
}
namespace Internal
{
	internal static class PaddingHelpers
	{
		internal const int CACHE_LINE_SIZE = 128;
	}
	[StructLayout(LayoutKind.Explicit, Size = 124)]
	internal struct PaddingFor32
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				ToCharsBuffer(bytes[i], chars, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan());
			Span<char> buffer = span;
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				ToCharsBuffer(readOnlySpan[i], buffer, num, casing);
				num += 2;
			}
			return buffer.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			return TryDecodeFromUtf16_Scalar(chars, bytes, out charsProcessed);
		}

		private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < bytes.Length)
			{
				num3 = FromChar(chars[num + 1]);
				num4 = FromChar(chars[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				bytes[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				long num2 = -17875860044349952L << (int)num;
				ulong num3 = num - 64;
				return (long)((ulong)num2 & num3) < 0L;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ActivityIdFormatInvalid => GetResourceString("ActivityIdFormatInvalid");

		internal static string ActivityNotRunning => GetResourceString("ActivityNotRunning");

		internal static string ActivityNotStarted => GetResourceString("ActivityNotStarted");

		internal static string ActivityStartAlreadyStarted => GetResourceString("ActivityStartAlreadyStarted");

		internal static string ActivitySetParentAlreadyStarted => GetResourceString("ActivitySetParentAlreadyStarted");

		internal static string EndTimeNotUtc => GetResourceString("EndTimeNotUtc");

		internal static string OperationNameInvalid => GetResourceString("OperationNameInvalid");

		internal static string ParentIdAlreadySet => GetResourceString("ParentIdAlreadySet");

		internal static string ParentIdInvalid => GetResourceString("ParentIdInvalid");

		internal static string SetFormatOnStartedActivity => GetResourceString("SetFormatOnStartedActivity");

		internal static string SetParentIdOnActivityWithParent => GetResourceString("SetParentIdOnActivityWithParent");

		internal static string StartTimeNotUtc => GetResourceString("StartTimeNotUtc");

		internal static string KeyAlreadyExist => GetResourceString("KeyAlreadyExist");

		internal static string InvalidTraceParent => GetResourceString("InvalidTraceParent");

		internal static string UnableAccessServicePointTable => GetResourceString("UnableAccessServicePointTable");

		internal static string UnableToInitialize => GetResourceString("UnableToInitialize");

		internal static string UnsupportedType => GetResourceString("UnsupportedType");

		internal static string Arg_BufferTooSmall => GetResourceString("Arg_BufferTooSmall");

		internal static string InvalidInstrumentType => GetResourceString("InvalidInstrumentType");

		internal static string InvalidHistogramExplicitBucketBoundaries => GetResourceString("InvalidHistogramExplicitBucketBoundaries");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.Runtime.Versioning
{
	internal abstract class OSPlatformAttribute : Attribute
	{
		public string PlatformName { get; }

		private protected OSPlatformAttribute(string platformName)
		{
			PlatformName = platformName;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
	internal sealed class TargetPlatformAttribute : OSPlatformAttribute
	{
		public TargetPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public string Message { get; }

		public UnsupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}

		public UnsupportedOSPlatformAttribute(string platformName, string message)
			: base(platformName)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public ObsoletedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}

		public ObsoletedOSPlatformAttribute(string platformName, string message)
			: base(platformName)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public UnsupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
}
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.CompilerServices
{
	[EditorBrowsable(EditorBrowsableState.Never)]
	internal static class IsExternalInit
	{
	}
}
namespace System.Diagnostics
{
	public readonly struct ActivityChangedEventArgs
	{
		public Activity? Previous { get; init; }

		public Activity? Current { get; init; }

		internal ActivityChangedEventArgs(Activity previous, Activity current)
		{
			Previous = previous;
			Current = current;
		}
	}
	public class Activity : IDisposable
	{
		public struct Enumerator<T>
		{
			private static readonly DiagNode<T> s_Empty = new DiagNode<T>(default(T));

			private DiagNode<T> _nextNode;

			private DiagNode<T> _currentNode;

			public readonly ref T Current => ref _currentNode.Value;

			internal Enumerator(DiagNode<T> head)
			{
				_nextNode = head;
				_currentNode = s_Empty;
			}

			[EditorBrowsable(EditorBrowsableState.Never)]
			public readonly Enumerator<T> GetEnumerator()
			{
				return this;
			}

			public bool MoveNext()
			{
				if (_nextNode == null)
				{
					_currentNode = s_Empty;
					return false;
				}
				_currentNode = _nextNode;
				_nextNode = _nextNode.Next;
				return true;
			}
		}

		private sealed class BaggageLinkedList : IEnumerable<KeyValuePair<string, string>>, IEnumerable
		{
			private DiagNode<KeyValuePair<string, string>> _first;

			public DiagNode<KeyValuePair<string, string>> First => _first;

			public BaggageLinkedList(KeyValuePair<string, string> firstValue, bool set = false)
			{
				_first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, string>>(firstValue));
			}

			public void Add(KeyValuePair<string, string> value)
			{
				DiagNode<KeyValuePair<string, string>> diagNode = new DiagNode<KeyValuePair<string, string>>(value);
				lock (this)
				{
					diagNode.Next = _first;
					_first = diagNode;
				}
			}

			public void Set(KeyValuePair<string, string> value)
			{
				if (value.Value == null)
				{
					Remove(value.Key);
					return;
				}
				lock (this)
				{
					for (DiagNode<KeyValuePair<string, string>> diagNode = _first; diagNode != null; diagNode = diagNode.Next)
					{
						if (diagNode.Value.Key == value.Key)
						{
							diagNode.Value = value;
							return;
						}
					}
					DiagNode<KeyValuePair<string, string>> diagNode2 = new DiagNode<KeyValuePair<string, string>>(value);
					diagNode2.Next = _first;
					_first = diagNode2;
				}
			}

			public void Remove(string key)
			{
				lock (this)
				{
					if (_first == null)
					{
						return;
					}
					if (_first.Value.Key == key)
					{
						_first = _first.Next;
						return;
					}
					DiagNode<KeyValuePair<string, string>> diagNode = _first;
					while (diagNode.Next != null)
					{
						if (diagNode.Next.Value.Key == key)
						{
							diagNode.Next = diagNode.Next.Next;
							break;
						}
						diagNode = diagNode.Next;
					}
				}
			}

			public DiagEnumerator<KeyValuePair<string, string>> GetEnumerator()
			{
				return new DiagEnumerator<KeyValuePair<string, string>>(_first);
			}

			IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()
			{
				return GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		internal sealed class TagsLinkedList : IEnumerable<KeyValuePair<string, object>>, IEnumerable
		{
			private DiagNode<KeyValuePair<string, object>> _first;

			private DiagNode<KeyValuePair<string, object>> _last;

			private StringBuilder _stringBuilder;

			public DiagNode<KeyValuePair<string, object>> First => _first;

			public TagsLinkedList(KeyValuePair<string, object> firstValue, bool set = false)
			{
				_last = (_first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, object>>(firstValue)));
			}

			public TagsLinkedList(IEnumerator<KeyValuePair<string, object>> e)
			{
				_last = (_first = new DiagNode<KeyValuePair<string, object>>(e.Current));
				while (e.MoveNext())
				{
					_last.Next = new DiagNode<KeyValuePair<string, object>>(e.Current);
					_last = _last.Next;
				}
			}

			public TagsLinkedList(IEnumerable<KeyValuePair<string, object>> list)
			{
				Add(list);
			}

			public void Add(IEnumerable<KeyValuePair<string, object>> list)
			{
				IEnumerator<KeyValuePair<string, object>> enumerator = list.GetEnumerator();
				if (enumerator.MoveNext())
				{
					if (_first == null)
					{
						_last = (_first = new DiagNode<KeyValuePair<string, object>>(enumerator.Current));
					}
					else
					{
						_last.Next = new DiagNode<KeyValuePair<string, object>>(enumerator.Current);
						_last = _last.Next;
					}
					while (enumerator.MoveNext())
					{
						_last.Next = new DiagNode<KeyValuePair<string, object>>(enumerator.Current);
						_last = _last.Next;
					}
				}
			}

			public void Add(KeyValuePair<string, object> value)
			{
				DiagNode<KeyValuePair<string, object>> diagNode = new DiagNode<KeyValuePair<string, object>>(value);
				lock (this)
				{
					if (_first == null)
					{
						_first = (_last = diagNode);
						return;
					}
					_last.Next = diagNode;
					_last = diagNode;
				}
			}

			public object Get(string key)
			{
				for (DiagNode<KeyValuePair<string, object>> diagNode = _first; diagNode != null; diagNode = diagNode.Next)
				{
					if (diagNode.Value.Key == key)
					{
						return diagNode.Value.Value;
					}
				}
				return null;
			}

			public void Remove(string key)
			{
				lock (this)
				{
					if (_first == null)
					{
						return;
					}
					if (_first.Value.Key == key)
					{
						_first = _first.Next;
						if (_first == null)
						{
							_last = null;
						}
						return;
					}
					DiagNode<KeyValuePair<string, object>> diagNode = _first;
					while (diagNode.Next != null)
					{
						if (diagNode.Next.Value.Key == key)
						{
							if (_last == diagNode.Next)
							{
								_last = diagNode;
							}
							diagNode.Next = diagNode.Next.Next;
							break;
						}
						diagNode = diagNode.Next;
					}
				}
			}

			public void Set(KeyValuePair<string, object> value)
			{
				if (value.Value == null)
				{
					Remove(value.Key);
					return;
				}
				lock (this)
				{
					for (DiagNode<KeyValuePair<string, object>> diagNode = _first; diagNode != null; diagNode = diagNode.Next)
					{
						if (diagNode.Value.Key == value.Key)
						{
							diagNode.Value = value;
							return;
						}
					}
					DiagNode<KeyValuePair<string, object>> diagNode2 = new DiagNode<KeyValuePair<string, object>>(value);
					if (_first == null)
					{
						_first = (_last = diagNode2);
						return;
					}
					_last.Next = diagNode2;
					_last = diagNode2;
				}
			}

			public DiagEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				return new DiagEnumerator<KeyValuePair<string, object>>(_first);
			}

			IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
			{
				return GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}

			public IEnumerable<KeyValuePair<string, string>> EnumerateStringValues()
			{
				for (DiagNode<KeyValuePair<string, object>> current = _first; current != null; current = current.Next)
				{
					if (current.Value.Value is string || current.Value.Value == null)
					{
						yield return new KeyValuePair<string, string>(current.Value.Key, (string)current.Value.Value);
					}
				}
			}

			public override string ToString()
			{
				lock (this)
				{
					if (_first == null)
					{
						return string.Empty;
					}
					if (_stringBuilder == null)
					{
						_stringBuilder = new StringBuilder();
					}
					_stringBuilder.Append(_first.Value.Key);
					_stringBuilder.Append(':');
					_stringBuilder.Append(_first.Value.Value);
					for (DiagNode<KeyValuePair<string, object>> next = _first.Next; next != null; next = next.Next)
					{
						_stringBuilder.Append(", ");
						_stringBuilder.Append(next.Value.Key);
						_stringBuilder.Append(':');
						_stringBuilder.Append(next.Value.Value);
					}
					string result = _stringBuilder.ToString();
					_stringBuilder.Clear();
					return result;
				}
			}
		}

		[Flags]
		private enum State : byte
		{
			None = 0,
			FormatUnknown = 0,
			FormatHierarchical = 1,
			FormatW3C = 2,
			FormatFlags = 3,
			IsStopped = 0x80
		}

		private static readonly IEnumerable<KeyValuePair<string, string>> s_emptyBaggageTags = new KeyValuePair<string, string>[0];

		private static readonly IEnumerable<KeyValuePair<string, object>> s_emptyTagObjects = new KeyValuePair<string, object>[0];

		private static readonly IEnumerable<ActivityLink> s_emptyLinks = new ActivityLink[0];

		private static readonly IEnumerable<ActivityEvent> s_emptyEvents = new ActivityEvent[0];

		private static readonly ActivitySource s_defaultSource = new ActivitySource(string.Empty);

		private static readonly AsyncLocal<Activity> s_current = new AsyncLocal<Activity>();

		private const byte ActivityTraceFlagsIsSet = 128;

		private const int RequestIdMaxLength = 1024;

		private static readonly string s_uniqSuffix = $"-{GetRandomNumber():x}.";

		private static long s_currentRootId = (uint)GetRandomNumber();

		private static ActivityIdFormat s_defaultIdFormat;

		private string _traceState;

		private State _state;

		private int _currentChildId;

		private string _id;

		private string _rootId;

		private string _parentId;

		private string _parentSpanId;

		private string _traceId;

		private string _spanId;

		private byte _w3CIdFlags;

		private byte _parentTraceFlags;

		private TagsLinkedList _tags;

		private BaggageLinkedList _baggage;

		private DiagLinkedList<ActivityLink> _links;

		private DiagLinkedList<ActivityEvent> _events;

		private Dictionary<string, object> _customProperties;

		private string _displayName;

		private ActivityStatusCode _statusCode;

		private string _statusDescription;

		private Activity _previousActiveActivity;

		public static bool ForceDefaultIdFormat { get; set; }

		public ActivityStatusCode Status => _statusCode;

		public string? StatusDescription => _statusDescription;

		public bool HasRemoteParent { get; private set; }

		public static Activity? Current
		{
			get
			{
				return s_current.Value;
			}
			set
			{
				if (ValidateSetCurrent(value))
				{
					SetCurrent(value);
				}
			}
		}

		public ActivityKind Kind { get; private set; }

		public string OperationName { get; }

		public string DisplayName
		{
			get
			{
				return _displayName ?? OperationName;
			}
			set
			{
				_displayName = value ?? throw new ArgumentNullException("value");
			}
		}

		public ActivitySource Source { get; private set; }

		public Activity? Parent { get; private set; }

		public TimeSpan Duration { get; private set; }

		public DateTime StartTimeUtc { get; private set; }

		public string? Id
		{
			get
			{
				if (_id == null && _spanId != null)
				{
					Span<char> buffer = stackalloc char[2];
					System.HexConverter.ToCharsBuffer((byte)(0xFFFFFF7Fu & _w3CIdFlags), buffer, 0, System.HexConverter.Casing.Lower);
					string value = "00-" + _traceId + "-" + _spanId + "-" + buffer;
					Interlocked.CompareExchange(ref _id, value, null);
				}
				return _id;
			}
		}

		public string? ParentId
		{
			get
			{
				if (_parentId == null)
				{
					if (_parentSpanId != null)
					{
						Span<char> buffer = stackalloc char[2];
						System.HexConverter.ToCharsBuffer((byte)(0xFFFFFF7Fu & _parentTraceFlags), buffer, 0, System.HexConverter.Casing.Lower);
						string value = "00-" + _traceId + "-" + _parentSpanId + "-" + buffer;
						Interlocked.CompareExchange(ref _parentId, value, null);
					}
					else if (Parent != null)
					{
						Interlocked.CompareExchange(ref _parentId, Parent.Id, null);
					}
				}
				return _parentId;
			}
		}

		public string? RootId
		{
			get
			{
				if (_rootId == null)
				{
					string text = null;
					if (Id != null)
					{
						text = GetRootId(Id);
					}
					else if (ParentId != null)
					{
						text = GetRootId(ParentId);
					}
					if (text != null)
					{
						Interlocked.CompareExchange(ref _rootId, text, null);
					}
				}
				return _rootId;
			}
		}

		public IEnumerable<KeyValuePair<string, string?>> Tags => _tags?.EnumerateStringValues() ?? s_emptyBaggageTags;

		public IEnumerable<KeyValuePair<string, object?>> TagObjects
		{
			get
			{
				IEnumerable<KeyValuePair<string, object>> tags = _tags;
				return tags ?? s_emptyTagObjects;
			}
		}

		public IEnumerable<ActivityEvent> Events
		{
			get
			{
				IEnumerable<ActivityEvent> events = _events;
				return events ?? s_emptyEvents;
			}
		}

		public IEnumerable<ActivityLink> Links
		{
			get
			{
				IEnumerable<ActivityLink> links = _links;
				return links ?? s_emptyLinks;
			}
		}

		public IEnumerable<KeyValuePair<string, string?>> Baggage
		{
			get
			{
				for (Activity activity2 = this; activity2 != null; activity2 = activity2.Parent)
				{
					if (activity2._baggage != null)
					{
						return Iterate(activity2);
					}
				}
				return s_emptyBaggageTags;
				static IEnumerable<KeyValuePair<string, string>> Iterate(Activity activity)
				{
					do
					{
						if (activity._baggage != null)
						{
							for (DiagNode<KeyValuePair<string, string>> current = activity._baggage.First; current != null; current = current.Next)
							{
								yield return current.Value;
							}
						}
						activity = activity.Parent;
					}
					while (activity != null);
				}
			}
		}

		public ActivityContext Context => new ActivityContext(TraceId, SpanId, ActivityTraceFlags, TraceStateString);

		public string? TraceStateString
		{
			get
			{
				for (Activity activity = this; activity != null; activity = activity.Parent)
				{
					string traceState = activity._traceState;
					if (traceState != null)
					{
						return traceState;
					}
				}
				return null;
			}
			set
			{
				_traceState = value;
			}
		}

		public ActivitySpanId SpanId
		{
			get
			{
				if (_spanId == null && _id != null && IdFormat == ActivityIdFormat.W3C)
				{
					string value = ActivitySpanId.CreateFromString(_id.AsSpan(36, 16)).ToHexString();
					Interlocked.CompareExchange(ref _spanId, value, null);
				}
				return new ActivitySpanId(_spanId);
			}
		}

		public ActivityTraceId TraceId
		{
			get
			{
				if (_traceId == null)
				{
					TrySetTraceIdFromParent();
				}
				return new ActivityTraceId(_traceId);
			}
		}

		public bool Recorded => (ActivityTraceFlags & ActivityTraceFlags.Recorded) != 0;

		public bool IsAllDataRequested { get; set; }

		public ActivityTraceFlags ActivityTraceFlags
		{
			get
			{
				if (!W3CIdFlagsSet)
				{
					TrySetTraceFlagsFromParent();
				}
				return (ActivityTraceFlags)(-129 & (int)_w3CIdFlags);
			}
			set
			{
				_w3CIdFlags = (byte)(0x80u | (byte)value);
			}
		}

		public ActivitySpanId ParentSpanId
		{
			get
			{
				if (_parentSpanId == null)
				{
					string text = null;
					if (_parentId != null && IsW3CId(_parentId))
					{
						try
						{
							text = ActivitySpanId.CreateFromString(_parentId.AsSpan(36, 16)).ToHexString();
						}
						catch
						{
						}
					}
					else if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C)
					{
						text = Parent.SpanId.ToHexString();
					}
					if (text != null)
					{
						Interlocked.CompareExchange(ref _parentSpanId, text, null);
					}
				}
				return new ActivitySpanId(_parentSpanId);
			}
		}

		public static Func<ActivityTraceId>? TraceIdGenerator { get; set; }

		public static ActivityIdFormat DefaultIdFormat
		{
			get
			{
				if (s_defaultIdFormat == ActivityIdFormat.Unknown)
				{
					s_defaultIdFormat = ActivityIdFormat.Hierarchical;
				}
				return s_defaultIdFormat;
			}
			set
			{
				if (ActivityIdFormat.Hierarchical > value || value > ActivityIdFormat.W3C)
				{
					throw new ArgumentException(System.SR.ActivityIdFormatInvalid);
				}
				s_defaultIdFormat = value;
			}
		}

		private bool W3CIdFlagsSet => (_w3CIdFlags & 0x80) != 0;

		public bool IsStopped
		{
			get
			{
				return (_state & State.IsStopped) != 0;
			}
			private set
			{
				if (value)
				{
					_state |= State.IsStopped;
				}
				else
				{
					_state &= ~State.IsStopped;
				}
			}
		}

		public ActivityIdFormat IdFormat
		{
			get
			{
				return (ActivityIdFormat)(_state & State.FormatFlags);
			}
			private set
			{
				_state = (_state & ~State.FormatFlags) | (State)((byte)value & 3u);
			}
		}

		public static event EventHandler<ActivityChangedEventArgs>? CurrentChanged;

		public Activity SetStatus(ActivityStatusCode code, string? description = null)
		{
			_statusCode = code;
			_statusDescription = ((code == ActivityStatusCode.Error) ? description : null);
			return this;
		}

		public Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects()
		{
			return new Enumerator<KeyValuePair<string, object>>(_tags?.First);
		}

		public Enumerator<ActivityEvent> EnumerateEvents()
		{
			return new Enumerator<ActivityEvent>(_events?.First);
		}

		public Enumerator<ActivityLink> EnumerateLinks()
		{
			return new Enumerator<ActivityLink>(_links?.First);
		}

		public string? GetBaggageItem(string key)
		{
			foreach (KeyValuePair<string, string> item in Baggage)
			{
				if (key == item.Key)
				{
					return item.Value;
				}
			}
			return null;
		}

		public object? GetTagItem(string key)
		{
			return _tags?.Get(key) ?? null;
		}

		public Activity(string operationName)
		{
			Source = s_defaultSource;
			IsAllDataRequested = true;
			if (string.IsNullOrEmpty(operationName))
			{
				NotifyError(new ArgumentException(System.SR.OperationNameInvalid));
			}
			OperationName = operationName ?? string.Empty;
		}

		public Activity AddTag(string key, string? value)
		{
			return AddTag(key, (object?)value);
		}

		public Activity AddTag(string key, object? value)
		{
			KeyValuePair<string, object> keyValuePair = new KeyValuePair<string, object>(key, value);
			if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(keyValuePair), null) != null)
			{
				_tags.Add(keyValuePair);
			}
			return this;
		}

		public Activity SetTag(string key, object? value)
		{
			KeyValuePair<string, object> keyValuePair = new KeyValuePair<string, object>(key, value);
			if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(keyValuePair, set: true), null) != null)
			{
				_tags.Set(keyValuePair);
			}
			return this;
		}

		public Activity AddEvent(ActivityEvent e)
		{
			if (_events != null || Interlocked.CompareExchange(ref _events, new DiagLinkedList<ActivityEvent>(e), null) != null)
			{
				_events.Add(e);
			}
			return this;
		}

		public Activity AddException(Exception exception, in TagList tags = default(TagList), DateTimeOffset timestamp = default(DateTimeOffset))
		{
			if (exception == null)
			{
				throw new ArgumentNullException("exception");
			}
			TagList tags2 = tags;
			Source.NotifyActivityAddException(this, exception, ref tags2);
			bool flag = false;
			bool flag2 = false;
			bool flag3 = false;
			for (int i = 0; i < tags2.Count; i++)
			{
				if (tags2[i].Key == "exception.message")
				{
					flag = true;
				}
				else if (tags2[i].Key == "exception.stacktrace")
				{
					flag2 = true;
				}
				else if (tags2[i].Key == "exception.type")
				{
					flag3 = true;
				}
			}
			if (!flag)
			{
				tags2.Add(new KeyValuePair<string, object>("exception.message", exception.Message));
			}
			if (!flag2)
			{
				tags2.Add(new KeyValuePair<string, object>("exception.stacktrace", exception.ToString()));
			}
			if (!flag3)
			{
				tags2.Add(new KeyValuePair<string, object>("exception.type", exception.GetType().ToString()));
			}
			return AddEvent(new ActivityEvent("exception", timestamp, ref tags2));
		}

		public Activity AddLink(ActivityLink link)
		{
			if (_links != null || Interlocked.CompareExchange(ref _links, new DiagLinkedList<ActivityLink>(link), null) != null)
			{
				_links.Add(link);
			}
			return this;
		}

		public Activity AddBaggage(string key, string? value)
		{
			KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>(key, value);
			if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(keyValuePair), null) != null)
			{
				_baggage.Add(keyValuePair);
			}
			return this;
		}

		public Activity SetBaggage(string key, string? value)
		{
			KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>(key, value);
			if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(keyValuePair, set: true), null) != null)
			{
				_baggage.Set(keyValuePair);
			}
			return this;
		}

		public Activity SetParentId(string parentId)
		{
			if (_id != null || _spanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ActivitySetParentAlreadyStarted));
			}
			else if (Parent != null)
			{
				NotifyError(new InvalidOperationException(System.SR.SetParentIdOnActivityWithParent));
			}
			else if (ParentId != null || _parentSpanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ParentIdAlreadySet));
			}
			else if (string.IsNullOrEmpty(parentId))
			{
				NotifyError(new ArgumentException(System.SR.ParentIdInvalid));
			}
			else
			{
				_parentId = parentId;
			}
			return this;
		}

		public Activity SetParentId(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags activityTraceFlags = ActivityTraceFlags.None)
		{
			if (_id != null || _spanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ActivitySetParentAlreadyStarted));
			}
			else if (Parent != null)
			{
				NotifyError(new InvalidOperationException(System.SR.SetParentIdOnActivityWithParent));
			}
			else if (ParentId != null || _parentSpanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ParentIdAlreadySet));
			}
			else
			{
				_traceId = traceId.ToHexString();
				_parentSpanId = spanId.ToHexString();
				ActivityTraceFlags = activityTraceFlags;
				_parentTraceFlags = (byte)activityTraceFlags;
			}
			return this;
		}

		public Activity SetStartTime(DateTime startTimeUtc)
		{
			if (startTimeUtc.Kind != DateTimeKind.Utc)
			{
				NotifyError(new InvalidOperationException(System.SR.StartTimeNotUtc));
			}
			else
			{
				StartTimeUtc = startTimeUtc;
			}
			return this;
		}

		public Activity SetEndTime(DateTime endTimeUtc)
		{
			if (endTimeUtc.Kind != DateTimeKind.Utc)
			{
				NotifyError(new InvalidOperationException(System.SR.EndTimeNotUtc));
			}
			else
			{
				Duration = endTimeUtc - StartTimeUtc;
				if (Duration.Ticks <= 0)
				{
					Duration = new TimeSpan(1L);
				}
			}
			return this;
		}

		public Activity Start()
		{
			if (_id != null || _spanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ActivityStartAlreadyStarted));
			}
			else
			{
				_previousActiveActivity = Current;
				if (_parentId == null && _parentSpanId == null && _previousActiveActivity != null)
				{
					Parent = _previousActiveActivity;
				}
				if (StartTimeUtc == default(DateTime))
				{
					StartTimeUtc = GetUtcNow();
				}
				if (IdFormat == ActivityIdFormat.Unknown)
				{
					IdFormat = (ForceDefaultIdFormat ? DefaultIdFormat : ((Parent != null) ? Parent.IdFormat : ((_parentSpanId != null) ? ActivityIdFormat.W3C : ((_parentId == null) ? DefaultIdFormat : ((!IsW3CId(_parentId)) ? ActivityIdFormat.Hierarchical : ActivityIdFormat.W3C)))));
				}
				if (IdFormat == ActivityIdFormat.W3C)
				{
					GenerateW3CId();
				}
				else
				{
					_id = GenerateHierarchicalId();
				}
				SetCurrent(this);
				Source.NotifyActivityStart(this);
			}
			return this;
		}

		public void Stop()
		{
			if (_id == null && _spanId == null)
			{
				NotifyError(new InvalidOperationException(System.SR.ActivityNotStarted));
			}
			else if (!IsStopped)
			{
				IsStopped = true;
				if (Duration == TimeSpan.Zero)
				{
					SetEndTime(GetUtcNow());
				}
				Source.NotifyActivityStop(this);
				SetCurrent(_previousActiveActivity);
			}
		}

		public Activity SetIdFormat(ActivityIdFormat format)
		{
			if (_id != null || _spanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.SetFormatOnStartedActivity));
			}
			else
			{
				IdFormat = format;
			}
			return this;
		}

		private static bool IsW3CId(string id)
		{
			if (id.Length == 55 && (('0' <= id[0] && id[0] <= '9') || ('a' <= id[0] && id[0] <= 'f')) && (('0' <= id[1] && id[1] <= '9') || ('a' <= id[1] && id[1] <= 'f')))
			{
				if (id[0] == 'f')
				{
					return id[1] != 'f';
				}
				return true;
			}
			return false;
		}

		internal static bool TryConvertIdToContext(string traceParent, string traceState, bool isRemote, out ActivityContext context)
		{
			context = default(ActivityContext);
			if (!IsW3CId(traceParent))
			{
				return false;
			}
			ReadOnlySpan<char> idData = traceParent.AsSpan(3, 32);
			ReadOnlySpan<char> idData2 = traceParent.AsSpan(36, 16);
			if (!ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData) || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData2) || !System.HexConverter.IsHexLowerChar(traceParent[53]) || !System.HexConverter.IsHexLowerChar(traceParent[54]))
			{
				return false;
			}
			context = new ActivityContext(new ActivityTraceId(idData.ToString()), new ActivitySpanId(idData2.ToString()), (ActivityTraceFlags)ActivityTraceId.HexByteFromChars(traceParent[53], traceParent[54]), traceState, isRemote);
			return true;
		}

		public void Dispose()
		{
			if (!IsStopped)
			{
				Stop();
			}
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
		}

		public void SetCustomProperty(string propertyName, object? propertyValue)
		{
			if (_customProperties == null)
			{
				Interlocked.CompareExchange(ref _customProperties, new Dictionary<string, object>(), null);
			}
			lock (_customProperties)
			{
				if (propertyValue == null)
				{
					_customProperties.Remove(propertyName);
				}
				else
				{
					_customProperties[propertyName] = propertyValue;
				}
			}
		}

		public object? GetCustomProperty(string propertyName)
		{
			if (_customProperties == null)
			{
				return null;
			}
			lock (_customProperties)
			{
				object value;
				return _customProperties.TryGetValue(propertyName, out value) ? value : null;
			}
		}

		internal static Activity Create(ActivitySource source, string name, ActivityKind kind, string parentId, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, DateTimeOffset startTime, ActivityTagsCollection samplerTags, ActivitySamplingResult request, bool startIt, ActivityIdFormat idFormat, string traceState)
		{
			Activity activity = new Activity(name);
			activity.Source = source;
			activity.Kind = kind;
			activity.IdFormat = idFormat;
			activity._traceState = traceState;
			if (links != null)
			{
				using IEnumerator<ActivityLink> enumerator = links.GetEnumerator();
				if (enumerator.MoveNext())
				{
					activity._links = new DiagLinkedList<ActivityLink>(enumerator);
				}
			}
			if (tags != null)
			{
				using IEnumerator<KeyValuePair<string, object>> enumerator2 = tags.GetEnumerator();
				if (enumerator2.MoveNext())
				{
					activity._tags = new TagsLinkedList(enumerator2);
				}
			}
			if (samplerTags != null)
			{
				if (activity._tags == null)
				{
					activity._tags = new TagsLinkedList(samplerTags);
				}
				else
				{
					activity._tags.Add(samplerTags);
				}
			}
			if (parentId != null)
			{
				activity._parentId = parentId;
			}
			else if (parentContext != default(ActivityContext))
			{
				activity._traceId = parentContext.TraceId.ToString();
				if (parentContext.SpanId != default(ActivitySpanId))
				{
					activity._parentSpanId = parentContext.SpanId.ToString();
				}
				activity.ActivityTraceFlags = parentContext.TraceFlags;
				activity._parentTraceFlags = (byte)parentContext.TraceFlags;
				activity.HasRemoteParent = parentContext.IsRemote;
			}
			activity.IsAllDataRequested = request == ActivitySamplingResult.AllData || request == ActivitySamplingResult.AllDataAndRecorded;
			if (request == ActivitySamplingResult.AllDataAndRecorded)
			{
				activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded;
			}
			if (startTime != default(DateTimeOffset))
			{
				activity.StartTimeUtc = startTime.UtcDateTime;
			}
			if (startIt)
			{
				activity.Start();
			}
			return activity;
		}

		private static void SetCurrent(Activity activity)
		{
			EventHandler<ActivityChangedEventArgs> currentChanged = Activity.CurrentChanged;
			if (currentChanged == null)
			{
				s_current.Value = activity;
				return;
			}
			Activity value = s_current.Value;
			s_current.Value = activity;
			currentChanged(null, new ActivityChangedEventArgs(value, activity));
		}

		private void GenerateW3CId()
		{
			if (_traceId == null && !TrySetTraceIdFromParent())
			{
				_traceId = (TraceIdGenerator?.Invoke() ?? ActivityTraceId.CreateRandom()).ToHexString();
			}
			if (!W3CIdFlagsSet)
			{
				TrySetTraceFlagsFromParent();
			}
			_spanId = ActivitySpanId.CreateRandom().ToHexString();
		}

		private static void NotifyError(Exception exception)
		{
			try
			{
				throw exception;
			}
			catch
			{
			}
		}

		private string GenerateHierarchicalId()
		{
			if (Parent != null)
			{
				return AppendSuffix(Parent.Id, Interlocked.Increment(ref Parent._currentChildId).ToString(), '.');
			}
			if (ParentId != null)
			{
				string text = ((ParentId[0] == '|') ? ParentId : ("|" + ParentId));
				char c = text[text.Length - 1];
				if (c != '.' && c != '_')
				{
					text += ".";
				}
				return AppendSuffix(text, Interlocked.Increment(ref s_currentRootId).ToString("x"), '_');
			}
			return GenerateRootId();
		}

		private string GetRootId(string id)
		{
			if (IdFormat == ActivityIdFormat.W3C)
			{
				return id.Substring(3, 32);
			}
			int num = id.IndexOf('.');
			if (num < 0)
			{
				num = id.Length;
			}
			int num2 = ((id[0] == '|') ? 1 : 0);
			return id.Substring(num2, num - num2);
		}

		private string AppendSuffix(string parentId, string suffix, char delimiter)
		{
			if (parentId.Length + suffix.Length < 1024)
			{
				return parentId + suffix + delimiter;
			}
			int num = 1015;
			while (num > 1 && parentId[num - 1] != '.' && parentId[num - 1] != '_')
			{
				num--;
			}
			if (num == 1)
			{
				return GenerateRootId();
			}
			string text = ((int)GetRandomNumber()).ToString("x8");
			return parentId.Substring(0, num) + text + "#";
		}

		private unsafe static long GetRandomNumber()
		{
			Guid guid = Guid.NewGuid();
			return *(long*)(&guid);
		}

		private static bool ValidateSetCurrent(Activity activity)
		{
			int num;
			if (activity != null)
			{
				if (activity.Id != null)
				{
					num = ((!activity.IsStopped) ? 1 : 0);
					if (num != 0)
					{
						goto IL_002c;
					}
				}
				else
				{
					num = 0;
				}
				NotifyError(new InvalidOperationException(System.SR.ActivityNotRunning));
			}
			else
			{
				num = 1;
			}
			goto IL_002c;
			IL_002c:
			return (byte)num != 0;
		}

		private bool TrySetTraceIdFromParent()
		{
			if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C)
			{
				_traceId = Parent.TraceId.ToHexString();
			}
			else if (_parentId != null && IsW3CId(_parentId))
			{
				try
				{
					_traceId = ActivityTraceId.CreateFromString(_parentId.AsSpan(3, 32)).ToHexString();
				}
				catch
				{
				}
			}
			return _traceId != null;
		}

		private void TrySetTraceFlagsFromParent()
		{
			if (W3CIdFlagsSet)
			{
				return;
			}
			if (Parent != null)
			{
				ActivityTraceFlags = Parent.ActivityTraceFlags;
			}
			else if (_parentId != null && IsW3CId(_parentId))
			{
				if (System.HexConverter.IsHexLowerChar(_parentId[53]) && System.HexConverter.IsHexLowerChar(_parentId[54]))
				{
					_w3CIdFlags = (byte)(ActivityTraceId.HexByteFromChars(_parentId[53], _parentId[54]) | 0x80u);
				}
				else
				{
					_w3CIdFlags = 128;
				}
			}
		}

		private static string GenerateRootId()
		{
			return $"|{Interlocked.Increment(ref s_currentRootId):x}{s_uniqSuffix}";
		}

		internal static DateTime GetUtcNow()
		{
			return DateTime.UtcNow;
		}
	}
	[Flags]
	public enum ActivityTraceFlags
	{
		None = 0,
		Recorded = 1
	}
	public enum ActivityIdFormat
	{
		Unknown,
		Hierarchical,
		W3C
	}
	public readonly struct ActivityTraceId : IEquatable<ActivityTraceId>
	{
		private readonly string _hexString;

		internal ActivityTraceId(string hexString)
		{
			_hexString = hexString;
		}

		public static ActivityTraceId CreateRandom()
		{
			Span<byte> obj = stackalloc byte[16];
			SetToRandomBytes(obj);
			return CreateFromBytes(obj);
		}

		public static ActivityTraceId CreateFromBytes(ReadOnlySpan<byte> idData)
		{
			if (idData.Length != 16)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return new ActivityTraceId(System.HexConverter.ToString(idData, System.HexConverter.Casing.Lower));
		}

		public static ActivityTraceId CreateFromUtf8String(ReadOnlySpan<byte> idData)
		{
			return new ActivityTraceId(idData);
		}

		public static ActivityTraceId CreateFromString(ReadOnlySpan<char> idData)
		{
			if (idData.Length != 32 || !IsLowerCaseHexAndNotAllZeros(idData))
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return new ActivityTraceId(idData.ToString());
		}

		public string ToHexString()
		{
			return _hexString ?? "00000000000000000000000000000000";
		}

		public override string ToString()
		{
			return ToHexString();
		}

		public static bool operator ==(ActivityTraceId traceId1, ActivityTraceId traceId2)
		{
			return traceId1._hexString == traceId2._hexString;
		}

		public static bool operator !=(ActivityTraceId traceId1, ActivityTraceId traceId2)
		{
			return traceId1._hexString != traceId2._hexString;
		}

		public bool Equals(ActivityTraceId traceId)
		{
			return _hexString == traceId._hexString;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is ActivityTraceId activityTraceId)
			{
				return _hexString == activityTraceId._hexString;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return ToHexString().GetHashCode();
		}

		private ActivityTraceId(ReadOnlySpan<byte> idData)
		{
			if (idData.Length != 32)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			Span<ulong> span = stackalloc ulong[2];
			if (!Utf8Parser.TryParse(idData.Slice(0, 16), out span[0], out int bytesConsumed, 'x'))
			{
				_hexString = CreateRandom()._hexString;
				return;
			}
			if (!Utf8Parser.TryParse(idData.Slice(16, 16), out span[1], out bytesConsumed, 'x'))
			{
				_hexString = CreateRandom()._hexString;
				return;
			}
			if (BitConverter.IsLittleEndian)
			{
				span[0] = BinaryPrimitives.ReverseEndianness(span[0]);
				span[1] = BinaryPrimitives.ReverseEndianness(span[1]);
			}
			_hexString = System.HexConverter.ToString(MemoryMarshal.AsBytes(span), System.HexConverter.Casing.Lower);
		}

		public void CopyTo(Span<byte> destination)
		{
			SetSpanFromHexChars(ToHexString().AsSpan(), destination);
		}

		internal static void SetToRandomBytes(Span<byte> outBytes)
		{
			RandomNumberGenerator current = RandomNumberGenerator.Current;
			Unsafe.WriteUnaligned(ref outBytes[0], current.Next());
			if (outBytes.Length == 16)
			{
				Unsafe.WriteUnaligned(ref outBytes[8], current.Next());
			}
		}

		internal static void SetSpanFromHexChars(ReadOnlySpan<char> charData, Span<byte> outBytes)
		{
			for (int i = 0; i < outBytes.Length; i++)
			{
				outBytes[i] = HexByteFromChars(charData[i * 2], charData[i * 2 + 1]);
			}
		}

		internal static byte HexByteFromChars(char char1, char char2)
		{
			int num = System.HexConverter.FromLowerChar(char1);
			int num2 = System.HexConverter.FromLowerChar(char2);
			if ((num | num2) == 255)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return (byte)((num << 4) | num2);
		}

		internal static bool IsLowerCaseHexAndNotAllZeros(ReadOnlySpan<char> idData)
		{
			bool result = false;
			for (int i = 0; i < idData.Length; i++)
			{
				char c = idData[i];
				if (!System.HexConverter.IsHexLowerChar(c))
				{
					return false;
				}
				if (c != '0')
				{
					result = true;
				}
			}
			return result;
		}
	}
	public readonly struct ActivitySpanId : IEquatable<ActivitySpanId>
	{
		private readonly string _hexString;

		internal ActivitySpanId(string hexString)
		{
			_hexString = hexString;
		}

		public unsafe static ActivitySpanId CreateRandom()
		{
			ulong num = default(ulong);
			ActivityTraceId.SetToRandomBytes(new Span<byte>(&num, 8));
			return new ActivitySpanId(System.HexConverter.ToString(new ReadOnlySpan<byte>(&num, 8), System.HexConverter.Casing.Lower));
		}

		public static ActivitySpanId CreateFromBytes(ReadOnlySpan<byte> idData)
		{
			if (idData.Length != 8)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return new ActivitySpanId(System.HexConverter.ToString(idData, System.HexConverter.Casing.Lower));
		}

		public static ActivitySpanId CreateFromUtf8String(ReadOnlySpan<byte> idData)
		{
			return new ActivitySpanId(idData);
		}

		public static ActivitySpanId CreateFromString(ReadOnlySpan<char> idData)
		{
			if (idData.Length != 16 || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData))
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return new ActivitySpanId(idData.ToString());
		}

		public string ToHexString()
		{
			return _hexString ?? "0000000000000000";
		}

		public override string ToString()
		{
			return ToHexString();
		}

		public static bool operator ==(ActivitySpanId spanId1, ActivitySpanId spandId2)
		{
			return spanId1._hexString == spandId2._hexString;
		}

		public static bool operator !=(ActivitySpanId spanId1, ActivitySpanId spandId2)
		{
			return spanId1._hexString != spandId2._hexString;
		}

		public bool Equals(ActivitySpanId spanId)
		{
			return _hexString == spanId._hexString;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is ActivitySpanId activitySpanId)
			{
				return _hexString == activitySpanId._hexString;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return ToHexString().GetHashCode();
		}

		private unsafe ActivitySpanId(ReadOnlySpan<byte> idData)
		{
			if (idData.Length != 16)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			if (!Utf8Parser.TryParse(idData, out ulong value, out int _, 'x'))
			{
				_hexString = CreateRandom()._hexString;
				return;
			}
			if (BitConverter.IsLittleEndian)
			{
				value = BinaryPrimitives.ReverseEndianness(value);
			}
			_hexString = System.HexConverter.ToString(new ReadOnlySpan<byte>(&value, 8), System.HexConverter.Casing.Lower);
		}

		public void CopyTo(Span<byte> destination)
		{
			ActivityTraceId.SetSpanFromHexChars(ToHexString().AsSpan(), destination);
		}
	}
	public enum ActivityStatusCode
	{
		Unset,
		Ok,
		Error
	}
	public class ActivityTagsCollection : IDictionary<string, object?>, ICollection<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable
	{
		public struct Enumerator : IEnumerator<KeyValuePair<string, object?>>, IEnumerator, IDisposable
		{
			private List<KeyValuePair<string, object>>.Enumerator _enumerator;

			public KeyValuePair<string, object?> Current => _enumerator.Current;

			object IEnumerator.Current => ((IEnumerator)_enumerator).Current;

			internal Enumerator(List<KeyValuePair<string, object>> list)
			{
				_enumerator = list.GetEnumerator();
			}

			public void Dispose()
			{
				_enumerator.Dispose();
			}

			public bool MoveNext()
			{
				return _enumerator.MoveNext();
			}

			void IEnumerator.Reset()
			{
				((IEnumerator)_enumerator).Reset();
			}
		}

		private readonly List<KeyValuePair<string, object>> _list = new List<KeyValuePair<string, object>>();

		public object? this[string key]
		{
			get
			{
				int num = FindIndex(key);
				if (num >= 0)
				{
					return _list[num].Value;
				}
				return null;
			}
			set
			{
				if (key == null)
				{
					throw new ArgumentNullException("key");
				}
				int num = FindIndex(key);
				if (value == null)
				{
					if (num >= 0)
					{
						_list.RemoveAt(num);
					}
				}
				else if (num >= 0)
				{
					_list[num] = new KeyValuePair<string, object>(key, value);
				}
				else
				{
					_list.Add(new KeyValuePair<string, object>(key, value));
				}
			}
		}

		public ICollection<string> Keys
		{
			get
			{
				List<string> list = new List<string>(_list.Count);
				foreach (KeyValuePair<string, object> item in _list)
				{
					list.Add(item.Key);
				}
				return list;
			}
		}

		public ICollection<object?> Values
		{
			get
			{
				List<object> list = new List<object>(_list.Count);
				foreach (KeyValuePair<string, object> item in _list)
				{
					list.Add(item.Value);
				}
				return list;
			}
		}

		public bool IsReadOnly => false;

		public int Count => _list.Count;

		public ActivityTagsCollection()
		{
		}

		public ActivityTagsCollection(IEnumerable<KeyValuePair<string, object?>> list)
		{
			if (list == null)
			{
				throw new ArgumentNullException("list");
			}
			foreach (KeyValuePair<string, object> item in list)
			{
				if (item.Key != null)
				{
					this[item.Key] = item.Value;
				}
			}
		}

		public void Add(string key, object? value)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			if (FindIndex(key) >= 0)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.KeyAlreadyExist, key));
			}
			_list.Add(new KeyValuePair<string, object>(key, value));
		}

		public void Add(KeyValuePair<string, object?> item)
		{
			if (item.Key == null)
			{
				throw new ArgumentNullException("item");
			}
			if (FindIndex(item.Key) >= 0)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.KeyAlreadyExist, item.Key));
			}
			_list.Add(item);
		}

		public void Clear()
		{
			_list.Clear();
		}

		public bool Contains(KeyValuePair<string, object?> item)
		{
			return _list.Contains(item);
		}

		public bool ContainsKey(string key)
		{
			return FindIndex(key) >= 0;
		}

		public void CopyTo(KeyValuePair<string, object?>[] array, int arrayIndex)
		{
			_list.CopyTo(array, arrayIndex);
		}

		IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
		{
			return new Enumerator(_list);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(_list);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new Enumerator(_list);
		}

		public bool Remove(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			int num = FindIndex(key);
			if (num >= 0)
			{
				_list.RemoveAt(num);
				return true;
			}
			return false;
		}

		public bool Remove(KeyValuePair<string, object?> item)
		{
			return _list.Remove(item);
		}

		public bool TryGetValue(string key, out object? value)
		{
			int num = FindIndex(key);
			if (num >= 0)
			{
				value = _list[num].Value;
				return true;
			}
			value = null;
			return false;
		}

		private int FindIndex(string key)
		{
			for (int i = 0; i < _list.Count; i++)
			{
				if (_list[i].Key == key)
				{
					return i;
				}
			}
			return -1;
		}
	}
	public readonly struct ActivityContext : IEquatable<ActivityContext>
	{
		public ActivityTraceId TraceId { get; }

		public ActivitySpanId SpanId { get; }

		public ActivityTraceFlags TraceFlags { get; }

		public string? TraceState { get; }

		public bool IsRemote { get; }

		public ActivityContext(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags traceFlags, string? traceState = null, bool isRemote = false)
		{
			TraceId = traceId;
			SpanId = spanId;
			TraceFlags = traceFlags;
			TraceState = traceState;
			IsRemote = isRemote;
		}

		public static bool TryParse(string? traceParent, string? traceState, bool isRemote, out ActivityContext context)
		{
			if (traceParent == null)
			{
				context = default(ActivityContext);
				return false;
			}
			return Activity.TryConvertIdToContext(traceParent, traceState, isRemote, out context);
		}

		public static bool TryParse(string? traceParent, string? traceState, out ActivityContext context)
		{
			return TryParse(traceParent, traceState, isRemote: false, out context);
		}

		public static ActivityContext Parse(string traceParent, string? traceState)
		{
			if (traceParent == null)
			{
				throw new ArgumentNullException("traceParent");
			}
			if (!Activity.TryConvertIdToContext(traceParent, traceState, isRemote: false, out var context))
			{
				throw new ArgumentException(System.SR.InvalidTraceParent);
			}
			return context;
		}

		public bool Equals(ActivityContext value)
		{
			if (SpanId.Equals(value.SpanId) && TraceId.Equals(value.TraceId) && TraceFlags == value.TraceFlags && TraceState == value.TraceState)
			{
				return IsRemote == value.IsRemote;
			}
			return false;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (!(obj is ActivityContext value))
			{
				return false;
			}
			return Equals(value);
		}

		public static bool operator ==(ActivityContext left, ActivityContext right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ActivityContext left, ActivityContext right)
		{
			return !(left == right);
		}

		public override int GetHashCode()
		{
			if (this == default(ActivityContext))
			{
				return 0;
			}
			int num = 5381;
			num = (num << 5) + num + TraceId.GetHashCode();
			num = (num << 5) + num + SpanId.GetHashCode();
			num = (int)((num << 5) + num + TraceFlags);
			return (num << 5) + num + ((TraceState != null) ? TraceState.GetHashCode() : 0);
		}
	}
	public readonly struct ActivityCreationOptions<T>
	{
		private readonly ActivityTagsCollection _samplerTags;

		private readonly ActivityContext _context;

		private readonly string _traceState;

		public ActivitySource Source { get; }

		public string Name { get; }

		public ActivityKind Kind { get; }

		public T Parent { get; }

		public IEnumerable<KeyValuePair<string, object?>>? Tags { get; }

		public IEnumerable<ActivityLink>? Links { get; }

		public ActivityTagsCollection SamplingTags
		{
			get
			{
				if (_samplerTags == null)
				{
					Unsafe.AsRef(in _samplerTags) = new ActivityTagsCollection();
				}
				return _samplerTags;
			}
		}

		public ActivityTraceId TraceId
		{
			get
			{
				if (Parent is ActivityContext && IdFormat == ActivityIdFormat.W3C && _context == default(ActivityContext))
				{
					ActivityTraceId traceId = Activity.TraceIdGenerator?.Invoke() ?? ActivityTraceId.CreateRandom();
					Unsafe.AsRef(in _context) = new ActivityContext(traceId, default(ActivitySpanId), ActivityTraceFlags.None);
				}
				return _context.TraceId;
			}
		}

		public string? TraceState
		{
			get
			{
				return _traceState;
			}
			init
			{
				_traceState = value;
			}
		}

		internal ActivityIdFormat IdFormat { get; }

		internal ActivityCreationOptions(ActivitySource source, string name, T parent, ActivityKind kind, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, ActivityIdFormat idFormat)
		{
			Source = source;
			Name = name;
			Kind = kind;
			Parent = parent;
			Tags = tags;
			Links = links;
			IdFormat = idFormat;
			if (IdFormat == ActivityIdFormat.Unknown && Activity.ForceDefaultIdFormat)
			{
				IdFormat = Activity.DefaultIdFormat;
			}
			_samplerTags = null;
			_traceState = null;
			if (parent is ActivityContext)
			{
				object obj = parent;
				ActivityContext activityContext = (ActivityContext)((obj is ActivityContext) ? obj : null);
				if (activityContext != default(ActivityContext))
				{
					_context = activityContext;
					if (IdFormat == ActivityIdFormat.Unknown)
					{
						IdFormat = ActivityIdFormat.W3C;
					}
					_traceState = activityContext.TraceState;
					return;
				}
			}
			if ((object)parent is string traceParent)
			{
				if (IdFormat != ActivityIdFormat.Hierarchical)
				{
					if (ActivityContext.TryParse(traceParent, null, out _context))
					{
						IdFormat = ActivityIdFormat.W3C;
					}
					if (IdFormat == ActivityIdFormat.Unknown)
					{
						IdFormat = ActivityIdFormat.Hierarchical;
					}
				}
				else
				{
					_context = default(ActivityContext);
				}
			}
			else
			{
				_context = default(ActivityContext);
				if (IdFormat == ActivityIdFormat.Unknown)
				{
					IdFormat = ((Activity.Current != null) ? Activity.Current.IdFormat : Activity.DefaultIdFormat);
				}
			}
		}

		internal void SetTraceState(string traceState)
		{
			Unsafe.AsRef(in _traceState) = traceState;
		}

		internal ActivityTagsCollection GetSamplingTags()
		{
			return _samplerTags;
		}

		internal ActivityContext GetContext()
		{
			return _context;
		}
	}
	public enum ActivitySamplingResult
	{
		None,
		PropagationData,
		AllData,
		AllDataAndRecorded
	}
	public readonly struct ActivityEvent
	{
		private static readonly IEnumerable<KeyValuePair<string, object>> s_emptyTags = Array.Empty<KeyValuePair<string, object>>();

		private readonly Activity.TagsLinkedList _tags;

		public string Name { get; }

		public DateTimeOffset Timestamp { get; }

		public IEnumerable<KeyValuePair<string, object?>> Tags
		{
			get
			{
				IEnumerable<KeyValuePair<string, object>> tags = _tags;
				return tags ?? s_emptyTags;
			}
		}

		public ActivityEvent(string name)
			: this(name, DateTimeOffset.UtcNow)
		{
		}

		public ActivityEvent(string name, DateTimeOffset timestamp = default(DateTimeOffset), ActivityTagsCollection? tags = null)
			: this(name, timestamp, tags, tags?.Count ?? 0)
		{
		}

		internal ActivityEvent(string name, DateTimeOffset timestamp, ref TagList tags)
			: this(name, timestamp, tags, tags.Count)
		{
		}

		private ActivityEvent(string name, DateTimeOffset timestamp, IEnumerable<KeyValuePair<string, object>> tags, int tagsCount)
		{
			Name = name ?? string.Empty;
			Timestamp = ((timestamp != default(DateTimeOffset)) ? timestamp : DateTimeOffset.UtcNow);
			_tags = ((tagsCount > 0) ? new Activity.TagsLinkedList(tags) : null);
		}

		public Activity.Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects()
		{
			return new Activity.Enumerator<KeyValuePair<string, object>>(_tags?.First);
		}
	}
	public enum ActivityKind
	{
		Internal,
		Server,
		Client,
		Producer,
		Consumer
	}
	public readonly struct ActivityLink : IEquatable<ActivityLink>
	{
		private readonly Activity.TagsLinkedList _tags;

		public ActivityContext Context { get; }

		public IEnumerable<KeyValuePair<string, object?>>? Tags => _tags;

		public ActivityLink(ActivityContext context, ActivityTagsCollection? tags = null)
		{
			Context = context;
			_tags = ((tags != null && tags.Count > 0) ? new Activity.TagsLinkedList(tags) : null);
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is ActivityLink value)
			{
				return Equals(value);
			}
			return false;
		}

		public bool Equals(ActivityLink value)
		{
			if (Context == value.Context)
			{
				return value.Tags == Tags;
			}
			return false;
		}

		public static bool operator ==(ActivityLink left, ActivityLink right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ActivityLink left, ActivityLink right)
		{
			return !left.Equals(right);
		}

		public Activity.Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects()
		{
			return new Activity.Enumerator<KeyValuePair<string, object>>(_tags?.First);
		}

		public override int GetHashCode()
		{
			if (this == default(ActivityLink))
			{
				return 0;
			}
			int num = 5381;
			num = (num << 5) + num + Context.GetHashCode();
			if (Tags != null)
			{
				foreach (KeyValuePair<string, object> tag in Tags)
				{
					num = (num << 5) + num + tag.Key.GetHashCode();
					if (tag.Value != null)
					{
						num = (num << 5) + num + tag.Value.GetHashCode();
					}
				}
			}
			return num;
		}
	}
	public delegate ActivitySamplingResult SampleActivity<T>(ref ActivityCreationOptions<T> options);
	public delegate void ExceptionRecorder(Activity activity, Exception exception, ref TagList tags);
	public sealed class ActivityListener : IDisposable
	{
		public Action<Activity>? ActivityStarted { get; set; }

		public Action<Activity>? ActivityStopped { get; set; }

		public ExceptionRecorder? ExceptionRecorder { get; set; }

		public Func<ActivitySource, bool>? ShouldListenTo { get; set; }

		public SampleActivity<string>? SampleUsingParentId { get; set; }

		public SampleActivity<ActivityContext>? Sample { get; set; }

		public void Dispose()
		{
			ActivitySource.DetachListener(this);
		}
	}
	public sealed class ActivitySource : IDisposable
	{
		internal delegate void Function<T, TParent>(T item, ref ActivityCreationOptions<TParent> data, ref ActivitySamplingResult samplingResult, ref ActivityCreationOptions<ActivityContext> dataWithContext);

		private static readonly SynchronizedList<ActivitySource> s_activeSources = new SynchronizedList<ActivitySource>();

		private static readonly SynchronizedList<ActivityListener> s_allListeners = new SynchronizedList<ActivityListener>();

		private SynchronizedList<ActivityListener> _listeners;

		public string Name { get; }

		public string? Version { get; }

		public IEnumerable<KeyValuePair<string, object?>>? Tags { get; }

		public ActivitySource(string name)
			: this(name, "", null)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public ActivitySource(string name, string? version = "")
			: this(name, version, null)
		{
		}

		public ActivitySource(string name, string? version = "", IEnumerable<KeyValuePair<string, object?>>? tags = null)
		{
			Name = name ?? throw new ArgumentNullException("name");
			Version = version;
			if (tags != null)
			{
				List<KeyValuePair<string, object>> list = new List<KeyValuePair<string, object>>(tags);
				list.Sort((KeyValuePair<string, object> left, KeyValuePair<string, object> right) => string.Compare(left.Key, right.Key, StringComparison.Ordinal));
				Tags = list.AsReadOnly();
			}
			s_activeSources.Add(this);
			if (s_allListeners.Count > 0)
			{
				s_allListeners.EnumWithAction(delegate(ActivityListener listener, object source)
				{
					Func<ActivitySource, bool> shouldListenTo = listener.ShouldListenTo;
					if (shouldListenTo != null)
					{
						ActivitySource activitySource = (ActivitySource)source;
						if (shouldListenTo(activitySource))
						{
							activitySource.AddListener(listener);
						}
					}
				}, this);
			}
			GC.KeepAlive(DiagnosticSourceEventSource.Log);
		}

		public bool HasListeners()
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners != null)
			{
				return listeners.Count > 0;
			}
			return false;
		}

		public Activity? CreateActivity(string name, ActivityKind kind)
		{
			return CreateActivity(name, kind, default(ActivityContext), null, null, null, default(DateTimeOffset), startIt: false);
		}

		public Activity? CreateActivity(string name, ActivityKind kind, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, ActivityIdFormat idFormat = ActivityIdFormat.Unknown)
		{
			return CreateActivity(name, kind, parentContext, null, tags, links, default(DateTimeOffset), startIt: false, idFormat);
		}

		public Activity? CreateActivity(string name, ActivityKind kind, string? parentId, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, ActivityIdFormat idFormat = ActivityIdFormat.Unknown)
		{
			return CreateActivity(name, kind, default(ActivityContext), parentId, tags, links, default(DateTimeOffset), startIt: false, idFormat);
		}

		public Activity? StartActivity([CallerMemberName] string name = "", ActivityKind kind = ActivityKind.Internal)
		{
			return CreateActivity(name, kind, default(ActivityContext), null, null, null, default(DateTimeOffset));
		}

		public Activity? StartActivity(string name, ActivityKind kind, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset))
		{
			return CreateActivity(name, kind, parentContext, null, tags, links, startTime);
		}

		public Activity? StartActivity(string name, ActivityKind kind, string? parentId, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset))
		{
			return CreateActivity(name, kind, default(ActivityContext), parentId, tags, links, startTime);
		}

		public Activity? StartActivity(ActivityKind kind, ActivityContext parentContext = default(ActivityContext), IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset), [CallerMemberName] string name = "")
		{
			return CreateActivity(name, kind, parentContext, null, tags, links, startTime);
		}

		private Activity CreateActivity(string name, ActivityKind kind, ActivityContext context, string parentId, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, DateTimeOffset startTime, bool startIt = true, ActivityIdFormat idFormat = ActivityIdFormat.Unknown)
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners == null || listeners.Count == 0)
			{
				return null;
			}
			Activity result2 = null;
			ActivitySamplingResult samplingResult = ActivitySamplingResult.None;
			ActivityTagsCollection activityTagsCollection;
			string traceState;
			if (parentId != null)
			{
				ActivityCreationOptions<string> activityCreationOptions = default(ActivityCreationOptions<string>);
				ActivityCreationOptions<ActivityContext> dataWithContext2 = default(ActivityCreationOptions<ActivityContext>);
				activityCreationOptions = new ActivityCreationOptions<string>(this, name, parentId, kind, tags, links, idFormat);
				if (activityCreationOptions.IdFormat == ActivityIdFormat.W3C)
				{
					dataWithContext2 = new ActivityCreationOptions<ActivityContext>(this, name, activityCreationOptions.GetContext(), kind, tags, links, ActivityIdFormat.W3C);
				}
				listeners.EnumWithFunc(delegate(ActivityListener listener, ref ActivityCreationOptions<string> data, ref ActivitySamplingResult result, ref ActivityCreationOptions<ActivityContext> dataWithContext)
				{
					SampleActivity<string> sampleUsingParentId = listener.SampleUsingParentId;
					if (sampleUsingParentId != null)
					{
						ActivitySamplingResult activitySamplingResult2 = sampleUsingParentId(ref data);
						dataWithContext.SetTraceState(data.TraceState);
						if (activitySamplingResult2 > result)
						{
							result = activitySamplingResult2;
						}
					}
					else if (data.IdFormat == ActivityIdFormat.W3C)
					{
						SampleActivity<ActivityContext> sample2 = listener.Sample;
						if (sample2 != null)
						{
							ActivitySamplingResult activitySamplingResult3 = sample2(ref dataWithContext);
							data.SetTraceState(dataWithContext.TraceState);
							if (activitySamplingResult3 > result)
							{
								result = activitySamplingResult3;
							}
						}
					}
				}, ref activityCreationOptions, ref samplingResult, ref dataWithContext2);
				if (context == default(ActivityContext))
				{
					if (activityCreationOptions.GetContext() != default(ActivityContext))
					{
						context = activityCreationOptions.GetContext();
						parentId = null;
					}
					else if (dataWithContext2.GetContext() != default(ActivityContext))
					{
						context = dataWithContext2.GetContext();
						parentId = null;
					}
				}
				activityTagsCollection = activityCreationOptions.GetSamplingTags();
				ActivityTagsCollection samplingTags = dataWithContext2.GetSamplingTags();
				if (samplingTags != null)
				{
					if (activityTagsCollection == null)
					{
						activityTagsCollection = samplingTags;
					}
					else
					{
						foreach (KeyValuePair<string, object?> item in samplingTags)
						{
							activityTagsCollection.Add(item);
						}
					}
				}
				idFormat = activityCreationOptions.IdFormat;
				traceState = activityCreationOptions.TraceState;
			}
			else
			{
				bool flag = context == default(ActivityContext) && Activity.Current != null;
				ActivityCreationOptions<ActivityContext> data2 = new ActivityCreationOptions<ActivityContext>(this, name, flag ? Activity.Current.Context : context, kind, tags, links, idFormat);
				listeners.EnumWithFunc(delegate(ActivityListener listener, ref ActivityCreationOptions<ActivityContext> data, ref ActivitySamplingResult result, ref ActivityCreationOptions<ActivityContext> unused)
				{
					SampleActivity<ActivityContext> sample = listener.Sample;
					if (sample != null)
					{
						ActivitySamplingResult activitySamplingResult = sample(ref data);
						if (activitySamplingResult > result)
						{
							result = activitySamplingResult;
						}
					}
				}, ref data2, ref samplingResult, ref data2);
				if (!flag)
				{
					context = data2.GetContext();
				}
				activityTagsCollection = data2.GetSamplingTags();
				idFormat = data2.IdFormat;
				traceState = data2.TraceState;
			}
			if (samplingResult != 0)
			{
				result2 = Activity.Create(this, name, kind, parentId, context, tags, links, startTime, activityTagsCollection, samplingResult, startIt, idFormat, traceState);
			}
			return result2;
		}

		public void Dispose()
		{
			_listeners = null;
			s_activeSources.Remove(this);
		}

		public static void AddActivityListener(ActivityListener listener)
		{
			if (listener == null)
			{
				throw new ArgumentNullException("listener");
			}
			if (!s_allListeners.AddIfNotExist(listener))
			{
				return;
			}
			s_activeSources.EnumWithAction(delegate(ActivitySource source, object obj)
			{
				Func<ActivitySource, bool> shouldListenTo = ((ActivityListener)obj).ShouldListenTo;
				if (shouldListenTo != null && shouldListenTo(source))
				{
					source.AddListener((ActivityListener)obj);
				}
			}, listener);
		}

		internal void AddListener(ActivityListener listener)
		{
			if (_listeners == null)
			{
				Interlocked.CompareExchange(ref _listeners, new SynchronizedList<ActivityListener>(), null);
			}
			_listeners.AddIfNotExist(listener);
		}

		internal static void DetachListener(ActivityListener listener)
		{
			s_allListeners.Remove(listener);
			s_activeSources.EnumWithAction(delegate(ActivitySource source, object obj)
			{
				source._listeners?.Remove((ActivityListener)obj);
			}, listener);
		}

		internal void NotifyActivityStart(Activity activity)
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners != null && listeners.Count > 0)
			{
				listeners.EnumWithAction(delegate(ActivityListener listener, object obj)
				{
					listener.ActivityStarted?.Invoke((Activity)obj);
				}, activity);
			}
		}

		internal void NotifyActivityStop(Activity activity)
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners != null && listeners.Count > 0)
			{
				listeners.EnumWithAction(delegate(ActivityListener listener, object obj)
				{
					listener.ActivityStopped?.Invoke((Activity)obj);
				}, activity);
			}
		}

		internal void NotifyActivityAddException(Activity activity, Exception exception, ref TagList tags)
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners != null && listeners.Count > 0)
			{
				listeners.EnumWithExceptionNotification(activity, exception, ref tags);
			}
		}
	}
	internal sealed class SynchronizedList<T>
	{
		private readonly List<T> _list;

		private uint _version;

		public int Count => _list.Count;

		public SynchronizedList()
		{
			_list = new List<T>();
		}

		public void Add(T item)
		{
			lock (_list)
			{
				_list.Add(item);
				_version++;
			}
		}

		public bool AddIfNotExist(T item)
		{
			lock (_list)
			{
				if (!_list.Contains(item))
				{
					_list.Add(item);
					_version++;
					return true;
				}
				return false;
			}
		}

		public bool Remove(T item)
		{
			lock (_list)
			{
				if (_list.Remove(item))
				{
					_version++;
					return true;
				}
				return false;
			}
		}

		public void EnumWithFunc<TParent>(ActivitySource.Function<T, TParent> func, ref ActivityCreationOptions<TParent> data, ref ActivitySamplingResult samplingResult, ref ActivityCreationOptions<ActivityContext> dataWithContext)
		{
			uint version = _version;
			int num = 0;
			while (num < _list.Count)
			{
				T item;
				lock (_list)
				{
					if (version != _version)
					{
						version = _version;
						num = 0;
						continue;
					}
					item = _list[num];
					num++;
					goto IL_004f;
				}
				IL_004f:
				func(item, ref data, ref samplingResult, ref dataWithContext);
			}
		}

		public void EnumWithAction(Action<T, object> action, object arg)
		{
			uint version = _version;
			int num = 0;
			while (num < _list.Count)
			{
				T arg2;
				lock (_list)
				{
					if (version != _version)
					{
						version = _version;
						num = 0;
						continue;
					}
					arg2 = _list[num];
					num++;
					goto IL_004f;
				}
				IL_004f:
				action(arg2, arg);
			}
		}

		public void EnumWithExceptionNotification(Activity activity, Exception exception, ref TagList tags)
		{
			if (typeof(T) != typeof(ActivityListener))
			{
				return;
			}
			uint version = _version;
			int num = 0;
			while (num < _list.Count)
			{
				T val;
				lock (_list)
				{
					if (version != _version)
					{
						version = _version;
						num = 0;
						continue;
					}
					val = _list[num];
					num++;
					goto IL_006b;
				}
				IL_006b:
				(val as ActivityListener).ExceptionRecorder?.Invoke(activity, exception, ref tags);
			}
		}
	}
	public abstract class DiagnosticSource
	{
		internal const string WriteRequiresUnreferencedCode = "The type of object being written to DiagnosticSource cannot be discovered statically.";

		internal const string WriteOfTRequiresUnreferencedCode = "Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.";

		[RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")]
		public abstract void Write(string name, object? value);

		[RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")]
		public void Write<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name, T value)
		{
			Write(name, (object?)value);
		}

		public abstract bool IsEnabled(string name);

		public virtual bool IsEnabled(string name, object? arg1, object? arg2 = null)
		{
			return IsEnabled(name);
		}

		[RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")]
		public Activity StartActivity(Activity activity, object? args)
		{
			activity.Start();
			Write(activity.OperationName + ".Start", args);
			return activity;
		}

		[RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")]
		public Activity StartActivity<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(Activity activity, T args)
		{
			return StartActivity(activity, (object?)args);
		}

		[RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")]
		public void StopActivity(Activity activity, object? args)
		{
			if (activity.Duration == TimeSpan.Zero)
			{
				activity.SetEndTime(Activity.GetUtcNow());
			}
			Write(activity.OperationName + ".Stop", args);
			activity.Stop();
		}

		[RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")]
		public void StopActivity<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(Activity activity, T args)
		{
			StopActivity(activity, (object?)args);
		}

		public virtual void OnActivityImport(Activity activity, object? payload)
		{
		}

		public virtual void OnActivityExport(Activity activity, object? payload)
		{
		}
	}
	public class DiagnosticListener : DiagnosticSource, IObservable<KeyValuePair<string, object?>>, IDisposable
	{
		private sealed class DiagnosticSubscription : IDisposable
		{
			internal IObserver<KeyValuePair<string, object>> Observer;

			internal Predicate<string> IsEnabled1Arg;

			internal Func<string, object, object, bool> IsEnabled3Arg;

			internal Action<Activity, object> OnActivityImport;

			internal Action<Activity, object> OnActivityExport;

			internal DiagnosticListener Owner;

			internal DiagnosticSubscription Next;

			public void Dispose()
			{
				DiagnosticSubscription subscriptions;
				DiagnosticSubscription value;
				do
				{
					subscriptions = Owner._subscriptions;
					value = Remove(subscriptions, this);
				}
				while (Interlocked.CompareExchange(ref Owner._subscriptions, value, subscriptions) != subscriptions);
			}

			private static DiagnosticSubscription Remove(DiagnosticSubscription subscriptions, DiagnosticSubscription subscription)
			{
				if (subscriptions == null)
				{
					return null;
				}
				if (subscriptions.Observer == subscription.Observer && subscriptions.IsEnabled1Arg == subscription.IsEnabled1Arg && subscriptions.IsEnabled3Arg == subscription.IsEnabled3Arg)
				{
					return subscriptions.Next;
				}
				return new DiagnosticSubscription
				{
					Observer = subscriptions.Observer,
					Owner = subscriptions.Owner,
					IsEnabled1Arg = subscriptions.IsEnabled1Arg,
					IsEnabled3Arg = subscriptions.IsEnabled3Arg,
					Next = Remove(subscriptions.Next, subscription)
				};
			}
		}

		private sealed class AllListenerObservable : IObservable<DiagnosticListener>
		{
			internal sealed class AllListenerSubscription : IDisposable
			{
				private readonly AllListenerObservable _owner;

				internal readonly IObserver<DiagnosticListener> Subscriber;

				internal AllListenerSubscription Next;

				internal AllListenerSubscription(AllListenerObservable owner, IObserver<DiagnosticListener> subscriber, AllListenerSubscription next)
				{
					_owner = owner;
					Subscriber = subscriber;
					Next = next;
				}

				public void Dispose()
				{
					if (_owner.Remove(this))
					{
						Subscriber.OnCompleted();
					}
				}
			}

			private AllListenerSubscription _subscriptions;

			public IDisposable Subscribe(IObserver<DiagnosticListener> observer)
			{
				lock (s_allListenersLock)
				{
					for (DiagnosticListener diagnosticListener = s_allListeners; diagnosticListener != null; diagnosticListener = diagnosticListener._next)
					{
						observer.OnNext(diagnosticListener);
					}
					_subscriptions = new AllListenerSubscription(this, observer, _subscriptions);
					return _subscriptions;
				}
			}

			internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener)
			{
				for (AllListenerSubscription allListenerSubscription = _subscriptions; allListenerSubscription != null; allListenerSubscription = allListenerSubscription.Next)
				{
					allListenerSubscription.Subscriber.OnNext(diagnosticListener);
				}
			}

			private bool Remove(AllListenerSubscription subscription)
			{
				lock (s_allListenersLock)
				{
					if (_subscriptions == subscription)
					{
						_subscriptions = subscription.Next;
						return true;
					}
					if (_subscriptions != null)
					{
						AllListenerSubscription allListenerSubscription = _subscriptions;
						while (allListenerSubscription.Next != null)
						{
							if (allListenerSubscription.Next == subscription)
							{
								allListenerSubscription.Next = allListenerSubscription.Next.Next;
								return true;
							}
							allListenerSubscription = allListenerSubscription.Next;
						}
					}
					return false;
				}
			}
		}

		private volatile DiagnosticSubscription _subscriptions;

		private DiagnosticListener _next;

		private bool _disposed;

		private static DiagnosticListener s_allListeners;

		private static volatile AllListenerObservable s_allListenerObservable;

		private static readonly object s_allListenersLock = new object();

		public static IObservable<DiagnosticListener> AllListeners => s_allListenerObservable ?? Interlocked.CompareExchange(ref s_allListenerObservable, new AllListenerObservable(), null) ?? s_allListenerObservable;

		public string Name { get; }

		public override void OnActivityImport(Activity activity, object? payload)
		{
			for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next)
			{
				diagnosticSubscription.OnActivityImport?.Invoke(activity, payload);
			}
		}

		public override void OnActivityExport(Activity activity, object? payload)
		{
			for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next)
			{
				diagnosticSubscription.OnActivityExport?.Invoke(activity, payload);
			}
		}

		public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer, Func<string, object?, object?, bool>? isEnabled, Action<Activity, object?>? onActivityImport = null, Action<Activity, object?>? onActivityExport = null)
		{
			if (isEnabled != null)
			{
				return SubscribeInternal(observer, (string name) => IsEnabled(name, null), isEnabled, onActivityImport, onActivityExport);
			}
			return SubscribeInternal(observer, null, null, onActivityImport, onActivityExport);
		}

		public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer, Predicate<string>? isEnabled)
		{
			if (isEnabled == null)
			{
				return SubscribeInternal(observer, null, null, null, null);
			}
			Predicate<string> localIsEnabled = isEnabled;
			return SubscribeInternal(observer, isEnabled, (string name, object arg1, object arg2) => localIsEnabled(name), null, null);
		}

		public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer, Func<string, object?, object?, bool>? isEnabled)
		{
			if (isEnabled != null)
			{
				return SubscribeInternal(observer, (string name) => IsEnabled(name, null), isEnabled, null, null);
			}
			return SubscribeInternal(observer, null, null, null, null);
		}

		public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer)
		{
			return SubscribeInternal(observer, null, null, null, null);
		}

		public DiagnosticListener(string name)
		{
			Name = name;
			lock (s_allListenersLock)
			{
				s_allListenerObservable?.OnNewDiagnosticListener(this);
				_next = s_allListeners;
				s_allListeners = this;
			}
			GC.KeepAlive(DiagnosticSourceEventSource.Log);
		}

		public virtual void Dispose()
		{
			lock (s_allListenersLock)
			{
				if (_disposed)
				{
					return;
				}
				_disposed = true;
				if (s_allListeners == this)
				{
					s_allListeners = s_allListeners._next;
				}
				else
				{
					for (DiagnosticListener next = s_allListeners; next != null; next = next._next)
					{
						if (next._next == this)
						{
							next._next = _next;
							break;
						}
					}
				}
				_next = null;
			}
			DiagnosticSubscription value = null;
			for (value = Interlocked.Exchange(ref _subscriptions, value); value != null; value = value.Next)
			{
				value.Observer.OnCompleted();
			}
		}

		public override string ToString()
		{
			return Name ?? string.Empty;
		}

		public bool IsEnabled()
		{
			return _subscriptions != null;
		}

		public override bool IsEnabled(string name)
		{
			for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next)
			{
				if (diagnosticSubscription.IsEnabled1Arg == null || diagnosticSubscription.IsEnabled1Arg(name))
				{
					return true;
				}
			}
			return false;
		}

		public override bool IsEnabled(string name, object? arg1, object? arg2 = null)
		{
			for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next)
			{
				if (diagnosticSubscription.IsEnabled3Arg == null || diagnosticSubscription.IsEnabled3Arg(name, arg1, arg2))
				{
					return true;
				}
			}
			return false;
		}

		[RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")]
		public override void Write(string name, object? value)
		{
			for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next)
			{
				diagnosticSubscription.Observer.OnNext(new KeyValuePair<string, object>(name, value));
			}
		}

		private DiagnosticSubscription SubscribeInternal(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled1Arg, Func<string, object, object, bool> isEnabled3Arg, Action<Activity, object> onActivityImport, Action<Activity, object> onActivityExport)
		{
			if (_disposed)
			{
				return new DiagnosticSubscription
				{
					Owner = this
				};
			}
			DiagnosticSubscription diagnosticSubscription = new DiagnosticSubscription
			{
				Observer = observer,
				IsEnabled1Arg = isEnabled1Arg,
				IsEnabled3Arg = isEnabled3Arg,
				OnActivityImport = onActivityImport,
				OnActivityExport = onActivityExport,
				Owner = this,
				Next = _subscriptions
			};
			while (Interlocked.CompareExchange(ref _subscriptions, diagnosticSubscription, diagnosticSubscription.Next) != diagnosticSubscription.Next)
			{
				diagnosticSubscription.Next = _subscriptions;
			}
			return diagnosticSubscription;
		}
	}
	[EventSource(Name = "Microsoft-Diagnostics-DiagnosticSource")]
	internal sealed class DiagnosticSourceEventSource : EventSource
	{
		public static class Keywords
		{
			public const EventKeywords Messages = (EventKeywords)1L;

			public const EventKeywords Events = (EventKeywords)2L;

			public const EventKeywords IgnoreShortCutKeywords = (EventKeywords)2048L;

			public const EventKeywords AspNetCoreHosting = (EventKeywords)4096L;

			public const EventKeywords EntityFrameworkCoreCommands = (EventKeywords)8192L;
		}

		public static readonly DiagnosticSourceEventSource Log = new DiagnosticSourceEventSource();

		private readonly string AspNetCoreHostingKeywordValue = "Microsoft.AspNetCore/Microsoft.AspNetCore.Hosting.BeginRequest@Activity1Start:-httpContext.Request.Method;httpContext.Request.Host;httpContext.Request.Path;httpContext.Request.QueryString\nMicrosoft.AspNetCore/Microsoft.AspNetCore.Hosting.EndRequest@Activity1Stop:-httpContext.TraceIdentifier;httpContext.Response.StatusCode";

		private readonly string EntityFrameworkCoreCommandsKeywordValue = "Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.BeforeExecuteCommand@Activity2Start:-Command.Connection.DataSource;Command.Connection.Database;Command.CommandText\nMicrosoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.AfterExecuteCommand@Activity2Stop:-";

		private IDisposable _listener;

		private volatile bool _false;

		[Event(1, Keywords = (EventKeywords)1L)]
		public void Message(string Message)
		{
			WriteEvent(1, Message);
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Arguments parameter is preserved by DynamicDependency")]
		[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(KeyValuePair<, >))]
		[Event(2, Keywords = (EventKeywords)2L)]
		public void Event(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
		{
			WriteEvent(2, SourceName, EventName, Arguments);
		}

		[Event(3, Keywords = (EventKeywords)2L)]
		public void EventJson(string SourceName, string EventName, string ArgmentsJson)
		{
			WriteEvent(3, SourceName, EventName, ArgmentsJson);
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Arguments parameter is preserved by DynamicDependency")]
		[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(KeyValuePair<, >))]
		[Event(4, Keywords = (EventKeywords)2L)]
		public void Activity1Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
		{
			WriteEvent(4, SourceName, EventName, Arguments);
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Arguments parameter is preserved by DynamicDependency")]
		[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(KeyValuePair<, >))]
		[Event(5, Keywords = (EventKeywords)2L)]
		public void Activity1Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
		{
			WriteEvent(5, SourceName, EventName, Arguments);
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Arguments parameter is preserved by DynamicDependency")]
		[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(KeyValuePair<, >))]
		[Event(6, Keywords = (EventKeywords)2L)]
		public void Activity2Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
		{
			WriteEvent(6, SourceName, EventName, Arguments);
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Arguments parameter is preserved by DynamicDependency")]
		[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(KeyValuePair<, >))]
		[Event(7, Keywords = (EventKeywords)2L)]
		public void Activity2Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
		{
			WriteEvent(7, SourceName, EventName, Arguments);
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Arguments parameter is preserved by DynamicDependency")]
		[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(KeyValuePair<, >))]
		[Event(8, Keywords = (EventKeywords)2L, ActivityOptions = EventActivityOptions.Recursive)]
		public void RecursiveActivity1Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
		{
			WriteEvent(8, SourceName, EventName, Arguments);
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:

System.IO.Pipelines.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using FxResources.System.IO.Pipelines;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.IO.Pipelines.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.IO.Pipelines")]
[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("Single producer single consumer byte buffer management.\r\n\r\nCommonly Used Types:\r\nSystem.IO.Pipelines.Pipe\r\nSystem.IO.Pipelines.PipeWriter\r\nSystem.IO.Pipelines.PipeReader")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.IO.Pipelines")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.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.IO.Pipelines
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string AdvanceToInvalidCursor => GetResourceString("AdvanceToInvalidCursor");

		internal static string ArgumentOutOfRange_NeedPosNum => GetResourceString("ArgumentOutOfRange_NeedPosNum");

		internal static string ConcurrentOperationsNotSupported => GetResourceString("ConcurrentOperationsNotSupported");

		internal static string FlushCanceledOnPipeWriter => GetResourceString("FlushCanceledOnPipeWriter");

		internal static string GetResultBeforeCompleted => GetResourceString("GetResultBeforeCompleted");

		internal static string InvalidExaminedOrConsumedPosition => GetResourceString("InvalidExaminedOrConsumedPosition");

		internal static string InvalidExaminedPosition => GetResourceString("InvalidExaminedPosition");

		internal static string InvalidZeroByteRead => GetResourceString("InvalidZeroByteRead");

		internal static string ObjectDisposed_StreamClosed => GetResourceString("ObjectDisposed_StreamClosed");

		internal static string NoReadingOperationToComplete => GetResourceString("NoReadingOperationToComplete");

		internal static string NotSupported_UnreadableStream => GetResourceString("NotSupported_UnreadableStream");

		internal static string NotSupported_UnwritableStream => GetResourceString("NotSupported_UnwritableStream");

		internal static string ReadCanceledOnPipeReader => GetResourceString("ReadCanceledOnPipeReader");

		internal static string ReaderAndWriterHasToBeCompleted => GetResourceString("ReaderAndWriterHasToBeCompleted");

		internal static string ReadingAfterCompleted => GetResourceString("ReadingAfterCompleted");

		internal static string ReadingIsInProgress => GetResourceString("ReadingIsInProgress");

		internal static string WritingAfterCompleted => GetResourceString("WritingAfterCompleted");

		internal static string UnflushedBytesNotSupported => GetResourceString("UnflushedBytesNotSupported");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.Threading
{
	internal static class CancellationTokenExtensions
	{
		internal static CancellationTokenRegistration UnsafeRegister(this CancellationToken cancellationToken, Action<object> callback, object state)
		{
			return cancellationToken.Register(callback, state);
		}
	}
}
namespace System.Threading.Tasks
{
	internal static class TaskToAsyncResult
	{
		private sealed class TaskAsyncResult : IAsyncResult
		{
			internal readonly Task _task;

			private readonly AsyncCallback _callback;

			public object AsyncState { get; }

			public bool CompletedSynchronously { get; }

			public bool IsCompleted => _task.IsCompleted;

			public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle;

			internal TaskAsyncResult(Task task, object state, AsyncCallback callback)
			{
				_task = task;
				AsyncState = state;
				if (task.IsCompleted)
				{
					CompletedSynchronously = true;
					callback?.Invoke(this);
				}
				else if (callback != null)
				{
					_callback = callback;
					_task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().OnCompleted(delegate
					{
						_callback(this);
					});
				}
			}
		}

		public static IAsyncResult Begin(Task task, AsyncCallback? callback, object? state)
		{
			if (task == null)
			{
				throw new ArgumentNullException("task");
			}
			return new TaskAsyncResult(task, state, callback);
		}

		public static void End(IAsyncResult asyncResult)
		{
			Unwrap(asyncResult).GetAwaiter().GetResult();
		}

		public static TResult End<TResult>(IAsyncResult asyncResult)
		{
			return Unwrap<TResult>(asyncResult).GetAwaiter().GetResult();
		}

		public static Task Unwrap(IAsyncResult asyncResult)
		{
			if (asyncResult == null)
			{
				throw new ArgumentNullException("asyncResult");
			}
			return (asyncResult as TaskAsyncResult)?._task ?? throw new ArgumentException(null, "asyncResult");
		}

		public static Task<TResult> Unwrap<TResult>(IAsyncResult asyncResult)
		{
			if (asyncResult == null)
			{
				throw new ArgumentNullException("asyncResult");
			}
			return ((asyncResult as TaskAsyncResult)?._task as Task<TResult>) ?? throw new ArgumentException(null, "asyncResult");
		}
	}
}
namespace System.IO
{
	internal static class StreamHelpers
	{
		public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize)
		{
			if (destination == null)
			{
				throw new ArgumentNullException("destination");
			}
			if (bufferSize <= 0)
			{
				throw new ArgumentOutOfRangeException("bufferSize", bufferSize, System.SR.ArgumentOutOfRange_NeedPosNum);
			}
			bool canRead = source.CanRead;
			if (!canRead && !source.CanWrite)
			{
				throw new ObjectDisposedException(null, System.SR.ObjectDisposed_StreamClosed);
			}
			bool canWrite = destination.CanWrite;
			if (!canWrite && !destination.CanRead)
			{
				throw new ObjectDisposedException("destination", System.SR.ObjectDisposed_StreamClosed);
			}
			if (!canRead)
			{
				throw new NotSupportedException(System.SR.NotSupported_UnreadableStream);
			}
			if (!canWrite)
			{
				throw new NotSupportedException(System.SR.NotSupported_UnwritableStream);
			}
		}
	}
}
namespace System.IO.Pipelines
{
	internal sealed class BufferSegment : ReadOnlySequenceSegment<byte>
	{
		private IMemoryOwner<byte> _memoryOwner;

		private byte[] _array;

		private BufferSegment _next;

		private int _end;

		public int End
		{
			get
			{
				return _end;
			}
			set
			{
				_end = value;
				base.Memory = AvailableMemory.Slice(0, value);
			}
		}

		public BufferSegment? NextSegment
		{
			get
			{
				return _next;
			}
			set
			{
				base.Next = value;
				_next = value;
			}
		}

		internal object? MemoryOwner => ((object)_memoryOwner) ?? ((object)_array);

		public Memory<byte> AvailableMemory { get; private set; }

		public int Length => End;

		public int WritableBytes
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return AvailableMemory.Length - End;
			}
		}

		public void SetOwnedMemory(IMemoryOwner<byte> memoryOwner)
		{
			_memoryOwner = memoryOwner;
			AvailableMemory = memoryOwner.Memory;
		}

		public void SetOwnedMemory(byte[] arrayPoolBuffer)
		{
			_array = arrayPoolBuffer;
			AvailableMemory = arrayPoolBuffer;
		}

		public void Reset()
		{
			ResetMemory();
			base.Next = null;
			base.RunningIndex = 0L;
			_next = null;
		}

		public void ResetMemory()
		{
			IMemoryOwner<byte> memoryOwner = _memoryOwner;
			if (memoryOwner != null)
			{
				_memoryOwner = null;
				memoryOwner.Dispose();
			}
			else
			{
				ArrayPool<byte>.Shared.Return(_array);
				_array = null;
			}
			base.Memory = default(ReadOnlyMemory<byte>);
			_end = 0;
			AvailableMemory = default(Memory<byte>);
		}

		public void SetNext(BufferSegment segment)
		{
			NextSegment = segment;
			segment = this;
			while (segment.Next != null)
			{
				segment.NextSegment.RunningIndex = segment.RunningIndex + segment.Length;
				segment = segment.NextSegment;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static long GetLength(BufferSegment startSegment, int startIndex, BufferSegment endSegment, int endIndex)
		{
			return endSegment.RunningIndex + (uint)endIndex - (startSegment.RunningIndex + (uint)startIndex);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static long GetLength(long startPosition, BufferSegment endSegment, int endIndex)
		{
			return endSegment.RunningIndex + (uint)endIndex - startPosition;
		}
	}
	internal readonly struct CompletionData
	{
		public Action<object?> Completion { get; }

		public object? CompletionState { get; }

		public ExecutionContext? ExecutionContext { get; }

		public SynchronizationContext? SynchronizationContext { get; }

		public CompletionData(Action<object?> completion, object? completionState, ExecutionContext? executionContext, SynchronizationContext? synchronizationContext)
		{
			Completion = completion;
			CompletionState = completionState;
			ExecutionContext = executionContext;
			SynchronizationContext = synchronizationContext;
		}
	}
	public struct FlushResult
	{
		internal ResultFlags _resultFlags;

		public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0;

		public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0;

		public FlushResult(bool isCanceled, bool isCompleted)
		{
			_resultFlags = ResultFlags.None;
			if (isCanceled)
			{
				_resultFlags |= ResultFlags.Canceled;
			}
			if (isCompleted)
			{
				_resultFlags |= ResultFlags.Completed;
			}
		}
	}
	internal sealed class InlineScheduler : PipeScheduler
	{
		public override void Schedule(Action<object?> action, object? state)
		{
			action(state);
		}

		internal override void UnsafeSchedule(Action<object?> action, object? state)
		{
			action(state);
		}
	}
	public interface IDuplexPipe
	{
		PipeReader Input { get; }

		PipeWriter Output { get; }
	}
	internal struct BufferSegmentStack
	{
		private readonly struct SegmentAsValueType
		{
			private readonly BufferSegment _value;

			private SegmentAsValueType(BufferSegment value)
			{
				_value = value;
			}

			public static implicit operator SegmentAsValueType(BufferSegment s)
			{
				return new SegmentAsValueType(s);
			}

			public static implicit operator BufferSegment(SegmentAsValueType s)
			{
				return s._value;
			}
		}

		private SegmentAsValueType[] _array;

		private int _size;

		public int Count => _size;

		public BufferSegmentStack(int size)
		{
			_array = new SegmentAsValueType[size];
			_size = 0;
		}

		public bool TryPop([NotNullWhen(true)] out BufferSegment? result)
		{
			int num = _size - 1;
			SegmentAsValueType[] array = _array;
			if ((uint)num >= (uint)array.Length)
			{
				result = null;
				return false;
			}
			_size = num;
			result = array[num];
			array[num] = default(SegmentAsValueType);
			return true;
		}

		public void Push(BufferSegment item)
		{
			int size = _size;
			SegmentAsValueType[] array = _array;
			if ((uint)size < (uint)array.Length)
			{
				array[size] = item;
				_size = size + 1;
			}
			else
			{
				PushWithResize(item);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void PushWithResize(BufferSegment item)
		{
			Array.Resize(ref _array, 2 * _array.Length);
			_array[_size] = item;
			_size++;
		}
	}
	public sealed class Pipe
	{
		private sealed class DefaultPipeReader : PipeReader, IValueTaskSource<ReadResult>
		{
			private readonly Pipe _pipe;

			public DefaultPipeReader(Pipe pipe)
			{
				_pipe = pipe;
			}

			public override bool TryRead(out ReadResult result)
			{
				return _pipe.TryRead(out result);
			}

			public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
			{
				return _pipe.ReadAsync(cancellationToken);
			}

			protected override ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumBytes, CancellationToken cancellationToken)
			{
				return _pipe.ReadAtLeastAsync(minimumBytes, cancellationToken);
			}

			public override void AdvanceTo(SequencePosition consumed)
			{
				_pipe.AdvanceReader(in consumed);
			}

			public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
			{
				_pipe.AdvanceReader(in consumed, in examined);
			}

			public override void CancelPendingRead()
			{
				_pipe.CancelPendingRead();
			}

			public override void Complete(Exception exception = null)
			{
				_pipe.CompleteReader(exception);
			}

			public override void OnWriterCompleted(Action<Exception, object> callback, object state)
			{
				_pipe.OnWriterCompleted(callback, state);
			}

			public ValueTaskSourceStatus GetStatus(short token)
			{
				return _pipe.GetReadAsyncStatus();
			}

			public ReadResult GetResult(short token)
			{
				return _pipe.GetReadAsyncResult();
			}

			public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				_pipe.OnReadAsyncCompleted(continuation, state, flags);
			}
		}

		private sealed class DefaultPipeWriter : PipeWriter, IValueTaskSource<FlushResult>
		{
			private readonly Pipe _pipe;

			public override bool CanGetUnflushedBytes => true;

			public override long UnflushedBytes => _pipe.GetUnflushedBytes();

			public DefaultPipeWriter(Pipe pipe)
			{
				_pipe = pipe;
			}

			public override void Complete(Exception exception = null)
			{
				_pipe.CompleteWriter(exception);
			}

			public override void CancelPendingFlush()
			{
				_pipe.CancelPendingFlush();
			}

			public override void OnReaderCompleted(Action<Exception, object> callback, object state)
			{
				_pipe.OnReaderCompleted(callback, state);
			}

			public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
			{
				return _pipe.FlushAsync(cancellationToken);
			}

			public override void Advance(int bytes)
			{
				_pipe.Advance(bytes);
			}

			public override Memory<byte> GetMemory(int sizeHint = 0)
			{
				return _pipe.GetMemory(sizeHint);
			}

			public override Span<byte> GetSpan(int sizeHint = 0)
			{
				return _pipe.GetSpan(sizeHint);
			}

			public ValueTaskSourceStatus GetStatus(short token)
			{
				return _pipe.GetFlushAsyncStatus();
			}

			public FlushResult GetResult(short token)
			{
				return _pipe.GetFlushAsyncResult();
			}

			public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				_pipe.OnFlushAsyncCompleted(continuation, state, flags);
			}

			public override ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
			{
				return _pipe.WriteAsync(source, cancellationToken);
			}
		}

		private static readonly Action<object> s_signalReaderAwaitable = delegate(object state)
		{
			((Pipe)state).ReaderCancellationRequested();
		};

		private static readonly Action<object> s_signalWriterAwaitable = delegate(object state)
		{
			((Pipe)state).WriterCancellationRequested();
		};

		private static readonly Action<object> s_invokeCompletionCallbacks = delegate(object state)
		{
			((PipeCompletionCallbacks)state).Execute();
		};

		private static readonly ContextCallback s_executionContextRawCallback = ExecuteWithoutExecutionContext;

		private static readonly SendOrPostCallback s_syncContextExecutionContextCallback = ExecuteWithExecutionContext;

		private static readonly SendOrPostCallback s_syncContextExecuteWithoutExecutionContextCallback = ExecuteWithoutExecutionContext;

		private static readonly Action<object> s_scheduleWithExecutionContextCallback = ExecuteWithExecutionContext;

		private BufferSegmentStack _bufferSegmentPool;

		private readonly DefaultPipeReader _reader;

		private readonly DefaultPipeWriter _writer;

		private readonly PipeOptions _options;

		private readonly object _sync = new object();

		private long _unconsumedBytes;

		private long _unflushedBytes;

		private PipeAwaitable _readerAwaitable;

		private PipeAwaitable _writerAwaitable;

		private PipeCompletion _writerCompletion;

		private PipeCompletion _readerCompletion;

		private long _lastExaminedIndex = -1L;

		private BufferSegment _readHead;

		private int _readHeadIndex;

		private bool _disposed;

		private BufferSegment _readTail;

		private int _readTailIndex;

		private int _minimumReadBytes;

		private BufferSegment _writingHead;

		private Memory<byte> _writingHeadMemory;

		private int _writingHeadBytesBuffered;

		private PipeOperationState _operationState;

		private bool UseSynchronizationContext => _options.UseSynchronizationContext;

		private int MinimumSegmentSize => _options.MinimumSegmentSize;

		private long PauseWriterThreshold => _options.PauseWriterThreshold;

		private long ResumeWriterThreshold => _options.ResumeWriterThreshold;

		private PipeScheduler ReaderScheduler => _options.ReaderScheduler;

		private PipeScheduler WriterScheduler => _options.WriterScheduler;

		private object SyncObj => _sync;

		internal long Length => _unconsumedBytes;

		public PipeReader Reader => _reader;

		public PipeWriter Writer => _writer;

		public Pipe()
			: this(PipeOptions.Default)
		{
		}

		public Pipe(PipeOptions options)
		{
			if (options == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
			}
			_bufferSegmentPool = new BufferSegmentStack(options.InitialSegmentPoolSize);
			_operationState = default(PipeOperationState);
			_readerCompletion = default(PipeCompletion);
			_writerCompletion = default(PipeCompletion);
			_options = options;
			_readerAwaitable = new PipeAwaitable(completed: false, UseSynchronizationContext);
			_writerAwaitable = new PipeAwaitable(completed: true, UseSynchronizationContext);
			_reader = new DefaultPipeReader(this);
			_writer = new DefaultPipeWriter(this);
		}

		private void ResetState()
		{
			_readerCompletion.Reset();
			_writerCompletion.Reset();
			_readerAwaitable = new PipeAwaitable(completed: false, UseSynchronizationContext);
			_writerAwaitable = new PipeAwaitable(completed: true, UseSynchronizationContext);
			_readTailIndex = 0;
			_readHeadIndex = 0;
			_lastExaminedIndex = -1L;
			_unflushedBytes = 0L;
			_unconsumedBytes = 0L;
		}

		internal Memory<byte> GetMemory(int sizeHint)
		{
			if (_writerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateWriteHeadIfNeeded(sizeHint);
			return _writingHeadMemory;
		}

		internal Span<byte> GetSpan(int sizeHint)
		{
			if (_writerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateWriteHeadIfNeeded(sizeHint);
			return _writingHeadMemory.Span;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AllocateWriteHeadIfNeeded(int sizeHint)
		{
			if (!_operationState.IsWritingActive || _writingHeadMemory.Length == 0 || _writingHeadMemory.Length < sizeHint)
			{
				AllocateWriteHeadSynchronized(sizeHint);
			}
		}

		private void AllocateWriteHeadSynchronized(int sizeHint)
		{
			lock (SyncObj)
			{
				_operationState.BeginWrite();
				if (_writingHead == null)
				{
					BufferSegment readTail = AllocateSegment(sizeHint);
					_writingHead = (_readHead = (_readTail = readTail));
					_lastExaminedIndex = 0L;
					return;
				}
				int length = _writingHeadMemory.Length;
				if (length == 0 || length < sizeHint)
				{
					if (_writingHeadBytesBuffered > 0)
					{
						_writingHead.End += _writingHeadBytesBuffered;
						_writingHeadBytesBuffered = 0;
					}
					if (_writingHead.Length == 0)
					{
						_writingHead.ResetMemory();
						RentMemory(_writingHead, sizeHint);
					}
					else
					{
						BufferSegment bufferSegment = AllocateSegment(sizeHint);
						_writingHead.SetNext(bufferSegment);
						_writingHead = bufferSegment;
					}
				}
			}
		}

		private BufferSegment AllocateSegment(int sizeHint)
		{
			BufferSegment bufferSegment = CreateSegmentUnsynchronized();
			RentMemory(bufferSegment, sizeHint);
			return bufferSegment;
		}

		private void RentMemory(BufferSegment segment, int sizeHint)
		{
			MemoryPool<byte> memoryPool = null;
			int num = -1;
			if (!_options.IsDefaultSharedMemoryPool)
			{
				memoryPool = _options.Pool;
				num = memoryPool.MaxBufferSize;
			}
			if (sizeHint <= num)
			{
				segment.SetOwnedMemory(memoryPool.Rent(GetSegmentSize(sizeHint, num)));
			}
			else
			{
				int segmentSize = GetSegmentSize(sizeHint);
				segment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize));
			}
			_writingHeadMemory = segment.AvailableMemory;
		}

		private int GetSegmentSize(int sizeHint, int maxBufferSize = int.MaxValue)
		{
			sizeHint = Math.Max(MinimumSegmentSize, sizeHint);
			return Math.Min(maxBufferSize, sizeHint);
		}

		private BufferSegment CreateSegmentUnsynchronized()
		{
			if (_bufferSegmentPool.TryPop(out BufferSegment result))
			{
				return result;
			}
			return new BufferSegment();
		}

		private void ReturnSegmentUnsynchronized(BufferSegment segment)
		{
			if (_bufferSegmentPool.Count < _options.MaxSegmentPoolSize)
			{
				_bufferSegmentPool.Push(segment);
			}
		}

		internal bool CommitUnsynchronized()
		{
			_operationState.EndWrite();
			if (_unflushedBytes == 0L)
			{
				return false;
			}
			_writingHead.End += _writingHeadBytesBuffered;
			_readTail = _writingHead;
			_readTailIndex = _writingHead.End;
			long unconsumedBytes = _unconsumedBytes;
			_unconsumedBytes += _unflushedBytes;
			bool result = true;
			if (_unconsumedBytes < _minimumReadBytes)
			{
				result = false;
			}
			else if (PauseWriterThreshold > 0 && unconsumedBytes < PauseWriterThreshold && _unconsumedBytes >= PauseWriterThreshold && !_readerCompletion.IsCompleted)
			{
				_writerAwaitable.SetUncompleted();
			}
			_unflushedBytes = 0L;
			_writingHeadBytesBuffered = 0;
			return result;
		}

		internal void Advance(int bytes)
		{
			lock (SyncObj)
			{
				if ((uint)bytes > (uint)_writingHeadMemory.Length)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes);
				}
				if (!_readerCompletion.IsCompleted)
				{
					AdvanceCore(bytes);
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AdvanceCore(int bytesWritten)
		{
			_unflushedBytes += bytesWritten;
			_writingHeadBytesBuffered += bytesWritten;
			_writingHeadMemory = _writingHeadMemory.Slice(bytesWritten);
		}

		internal ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken)
		{
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken));
			}
			CompletionData completionData;
			ValueTask<FlushResult> result;
			lock (SyncObj)
			{
				PrepareFlushUnsynchronized(out completionData, out result, cancellationToken);
			}
			TrySchedule(ReaderScheduler, in completionData);
			return result;
		}

		private void PrepareFlushUnsynchronized(out CompletionData completionData, out ValueTask<FlushResult> result, CancellationToken cancellationToken)
		{
			bool num = CommitUnsynchronized();
			_writerAwaitable.BeginOperation(cancellationToken, s_signalWriterAwaitable, this);
			if (_writerAwaitable.IsCompleted)
			{
				FlushResult result2 = default(FlushResult);
				GetFlushResult(ref result2);
				result = new ValueTask<FlushResult>(result2);
			}
			else
			{
				result = new ValueTask<FlushResult>(_writer, 0);
			}
			if (num)
			{
				_readerAwaitable.Complete(out completionData);
			}
			else
			{
				completionData = default(CompletionData);
			}
		}

		internal void CompleteWriter(Exception? exception)
		{
			PipeCompletionCallbacks pipeCompletionCallbacks;
			CompletionData completionData;
			bool isCompleted;
			lock (SyncObj)
			{
				CommitUnsynchronized();
				pipeCompletionCallbacks = _writerCompletion.TryComplete(exception);
				_readerAwaitable.Complete(out completionData);
				isCompleted = _readerCompletion.IsCompleted;
			}
			if (isCompleted)
			{
				CompletePipe();
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(ReaderScheduler, pipeCompletionCallbacks);
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		internal void AdvanceReader(in SequencePosition consumed)
		{
			AdvanceReader(in consumed, in consumed);
		}

		internal void AdvanceReader(in SequencePosition consumed, in SequencePosition examined)
		{
			if (_readerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
			AdvanceReader((BufferSegment)consumed.GetObject(), consumed.GetInteger(), (BufferSegment)examined.GetObject(), examined.GetInteger());
		}

		private void AdvanceReader(BufferSegment consumedSegment, int consumedIndex, BufferSegment examinedSegment, int examinedIndex)
		{
			if (consumedSegment != null && examinedSegment != null && BufferSegment.GetLength(consumedSegment, consumedIndex, examinedSegment, examinedIndex) < 0)
			{
				ThrowHelper.ThrowInvalidOperationException_InvalidExaminedOrConsumedPosition();
			}
			BufferSegment bufferSegment = null;
			BufferSegment returnEnd = null;
			CompletionData completionData = default(CompletionData);
			lock (SyncObj)
			{
				bool flag = false;
				if (examinedSegment == _readTail)
				{
					flag = examinedIndex == _readTailIndex;
				}
				if (examinedSegment != null && _lastExaminedIndex >= 0)
				{
					long length = BufferSegment.GetLength(_lastExaminedIndex, examinedSegment, examinedIndex);
					long unconsumedBytes = _unconsumedBytes;
					if (length < 0)
					{
						ThrowHelper.ThrowInvalidOperationException_InvalidExaminedPosition();
					}
					_unconsumedBytes -= length;
					_lastExaminedIndex = examinedSegment.RunningIndex + examinedIndex;
					if (unconsumedBytes >= ResumeWriterThreshold && _unconsumedBytes < ResumeWriterThreshold)
					{
						_writerAwaitable.Complete(out completionData);
					}
				}
				if (consumedSegment != null)
				{
					if (_readHead == null)
					{
						ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor();
						return;
					}
					bufferSegment = _readHead;
					returnEnd = consumedSegment;
					if (consumedIndex == returnEnd.Length)
					{
						if (_writingHead != returnEnd)
						{
							MoveReturnEndToNextBlock();
						}
						else if (_writingHeadBytesBuffered == 0 && !_operationState.IsWritingActive)
						{
							_writingHead = null;
							_writingHeadMemory = default(Memory<byte>);
							MoveReturnEndToNextBlock();
						}
						else
						{
							_readHead = consumedSegment;
							_readHeadIndex = consumedIndex;
						}
					}
					else
					{
						_readHead = consumedSegment;
						_readHeadIndex = consumedIndex;
					}
				}
				if (flag && !_writerCompletion.IsCompleted)
				{
					_readerAwaitable.SetUncompleted();
				}
				while (bufferSegment != null && bufferSegment != returnEnd)
				{
					BufferSegment? nextSegment = bufferSegment.NextSegment;
					bufferSegment.Reset();
					ReturnSegmentUnsynchronized(bufferSegment);
					bufferSegment = nextSegment;
				}
				_operationState.EndRead();
			}
			TrySchedule(WriterScheduler, in completionData);
			void MoveReturnEndToNextBlock()
			{
				BufferSegment nextSegment2 = returnEnd.NextSegment;
				if (_readTail == returnEnd)
				{
					_readTail = nextSegment2;
					_readTailIndex = 0;
				}
				_readHead = nextSegment2;
				_readHeadIndex = 0;
				returnEnd = nextSegment2;
			}
		}

		internal void CompleteReader(Exception? exception)
		{
			PipeCompletionCallbacks pipeCompletionCallbacks;
			CompletionData completionData;
			bool isCompleted;
			lock (SyncObj)
			{
				if (_operationState.IsReadingActive)
				{
					_operationState.EndRead();
				}
				pipeCompletionCallbacks = _readerCompletion.TryComplete(exception);
				_writerAwaitable.Complete(out completionData);
				isCompleted = _writerCompletion.IsCompleted;
			}
			if (isCompleted)
			{
				CompletePipe();
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(WriterScheduler, pipeCompletionCallbacks);
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		internal void OnWriterCompleted(Action<Exception?, object?> callback, object? state)
		{
			if (callback == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback);
			}
			PipeCompletionCallbacks pipeCompletionCallbacks;
			lock (SyncObj)
			{
				pipeCompletionCallbacks = _writerCompletion.AddCallback(callback, state);
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(ReaderScheduler, pipeCompletionCallbacks);
			}
		}

		internal void CancelPendingRead()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_readerAwaitable.Cancel(out completionData);
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		internal void CancelPendingFlush()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_writerAwaitable.Cancel(out completionData);
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		internal void OnReaderCompleted(Action<Exception?, object?> callback, object? state)
		{
			if (callback == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback);
			}
			PipeCompletionCallbacks pipeCompletionCallbacks;
			lock (SyncObj)
			{
				pipeCompletionCallbacks = _readerCompletion.AddCallback(callback, state);
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(WriterScheduler, pipeCompletionCallbacks);
			}
		}

		internal ValueTask<ReadResult> ReadAtLeastAsync(int minimumBytes, CancellationToken token)
		{
			if (_readerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
			if (token.IsCancellationRequested)
			{
				return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(token));
			}
			CompletionData completionData = default(CompletionData);
			ValueTask<ReadResult> result2;
			lock (SyncObj)
			{
				_readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this);
				if (_readerAwaitable.IsCompleted)
				{
					GetReadResult(out var result);
					if (_unconsumedBytes >= minimumBytes || result.IsCanceled || result.IsCompleted)
					{
						return new ValueTask<ReadResult>(result);
					}
					_readerAwaitable.SetUncompleted();
					_operationState.EndRead();
					_readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this);
				}
				if (!_writerAwaitable.IsCompleted)
				{
					_writerAwaitable.Complete(out completionData);
				}
				_minimumReadBytes = minimumBytes;
				result2 = new ValueTask<ReadResult>(_reader, 0);
			}
			TrySchedule(WriterScheduler, in completionData);
			return result2;
		}

		internal ValueTask<ReadResult> ReadAsync(CancellationToken token)
		{
			if (_readerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
			if (token.IsCancellationRequested)
			{
				return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(token));
			}
			lock (SyncObj)
			{
				_readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this);
				if (_readerAwaitable.IsCompleted)
				{
					GetReadResult(out var result);
					return new ValueTask<ReadResult>(result);
				}
				return new ValueTask<ReadResult>(_reader, 0);
			}
		}

		internal bool TryRead(out ReadResult result)
		{
			lock (SyncObj)
			{
				if (_readerCompletion.IsCompleted)
				{
					ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
				}
				if (_unconsumedBytes > 0 || _readerAwaitable.IsCompleted)
				{
					GetReadResult(out result);
					return true;
				}
				if (_readerAwaitable.IsRunning)
				{
					ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
				}
				_operationState.BeginReadTentative();
				result = default(ReadResult);
				return false;
			}
		}

		private static void ScheduleCallbacks(PipeScheduler scheduler, PipeCompletionCallbacks completionCallbacks)
		{
			scheduler.UnsafeSchedule(s_invokeCompletionCallbacks, completionCallbacks);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static void TrySchedule(PipeScheduler scheduler, in CompletionData completionData)
		{
			Action<object> completion = completionData.Completion;
			if (completion != null)
			{
				if (completionData.SynchronizationContext == null && completionData.ExecutionContext == null)
				{
					scheduler.UnsafeSchedule(completion, completionData.CompletionState);
				}
				else
				{
					ScheduleWithContext(scheduler, in completionData);
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void ScheduleWithContext(PipeScheduler scheduler, in CompletionData completionData)
		{
			if (completionData.SynchronizationContext == null)
			{
				scheduler.UnsafeSchedule(s_scheduleWithExecutionContextCallback, completionData);
			}
			else if (completionData.ExecutionContext == null)
			{
				completionData.SynchronizationContext.Post(s_syncContextExecuteWithoutExecutionContextCallback, completionData);
			}
			else
			{
				completionData.SynchronizationContext.Post(s_syncContextExecutionContextCallback, completionData);
			}
		}

		private static void ExecuteWithoutExecutionContext(object state)
		{
			CompletionData completionData = (CompletionData)state;
			completionData.Completion(completionData.CompletionState);
		}

		private static void ExecuteWithExecutionContext(object state)
		{
			ExecutionContext.Run(((CompletionData)state).ExecutionContext, s_executionContextRawCallback, state);
		}

		private void CompletePipe()
		{
			lock (SyncObj)
			{
				if (!_disposed)
				{
					_disposed = true;
					BufferSegment bufferSegment = _readHead ?? _readTail;
					while (bufferSegment != null)
					{
						BufferSegment bufferSegment2 = bufferSegment;
						bufferSegment = bufferSegment.NextSegment;
						bufferSegment2.Reset();
					}
					_writingHead = null;
					_writingHeadMemory = default(Memory<byte>);
					_readHead = null;
					_readTail = null;
					_lastExaminedIndex = -1L;
				}
			}
		}

		internal ValueTaskSourceStatus GetReadAsyncStatus()
		{
			if (_readerAwaitable.IsCompleted)
			{
				if (_writerCompletion.IsFaulted)
				{
					return ValueTaskSourceStatus.Faulted;
				}
				return ValueTaskSourceStatus.Succeeded;
			}
			return ValueTaskSourceStatus.Pending;
		}

		internal void OnReadAsyncCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags)
		{
			CompletionData completionData;
			bool doubleCompletion;
			lock (SyncObj)
			{
				_readerAwaitable.OnCompleted(continuation, state, flags, out completionData, out doubleCompletion);
			}
			if (doubleCompletion)
			{
				Writer.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation());
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		internal ReadResult GetReadAsyncResult()
		{
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			CancellationToken cancellationToken = default(CancellationToken);
			ReadResult result;
			try
			{
				lock (SyncObj)
				{
					if (!_readerAwaitable.IsCompleted)
					{
						ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted();
					}
					cancellationTokenRegistration = _readerAwaitable.ReleaseCancellationTokenRegistration(out cancellationToken);
					GetReadResult(out result);
				}
			}
			finally
			{
				cancellationTokenRegistration.Dispose();
			}
			if (result.IsCanceled)
			{
				cancellationToken.ThrowIfCancellationRequested();
			}
			return result;
		}

		private void GetReadResult(out ReadResult result)
		{
			bool isCompleted = _writerCompletion.IsCompletedOrThrow();
			bool flag = _readerAwaitable.ObserveCancellation();
			BufferSegment readHead = _readHead;
			if (readHead != null)
			{
				ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(readHead, _readHeadIndex, _readTail, _readTailIndex);
				result = new ReadResult(buffer, flag, isCompleted);
			}
			else
			{
				result = new ReadResult(default(ReadOnlySequence<byte>), flag, isCompleted);
			}
			if (flag)
			{
				_operationState.BeginReadTentative();
			}
			else
			{
				_operationState.BeginRead();
			}
			_minimumReadBytes = 0;
		}

		internal ValueTaskSourceStatus GetFlushAsyncStatus()
		{
			if (_writerAwaitable.IsCompleted)
			{
				if (_readerCompletion.IsFaulted)
				{
					return ValueTaskSourceStatus.Faulted;
				}
				return ValueTaskSourceStatus.Succeeded;
			}
			return ValueTaskSourceStatus.Pending;
		}

		internal FlushResult GetFlushAsyncResult()
		{
			FlushResult result = default(FlushResult);
			CancellationToken cancellationToken = default(CancellationToken);
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			try
			{
				lock (SyncObj)
				{
					if (!_writerAwaitable.IsCompleted)
					{
						ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted();
					}
					GetFlushResult(ref result);
					cancellationTokenRegistration = _writerAwaitable.ReleaseCancellationTokenRegistration(out cancellationToken);
					return result;
				}
			}
			finally
			{
				cancellationTokenRegistration.Dispose();
				cancellationToken.ThrowIfCancellationRequested();
			}
		}

		internal long GetUnflushedBytes()
		{
			return _unflushedBytes;
		}

		private void GetFlushResult(ref FlushResult result)
		{
			if (_writerAwaitable.ObserveCancellation())
			{
				result._resultFlags |= ResultFlags.Canceled;
			}
			if (_readerCompletion.IsCompletedOrThrow())
			{
				result._resultFlags |= ResultFlags.Completed;
			}
		}

		internal ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
		{
			if (_writerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (_readerCompletion.IsCompletedOrThrow())
			{
				return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: true));
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken));
			}
			CompletionData completionData;
			ValueTask<FlushResult> result;
			lock (SyncObj)
			{
				AllocateWriteHeadIfNeeded(0);
				if (source.Length <= _writingHeadMemory.Length)
				{
					source.CopyTo(_writingHeadMemory);
					AdvanceCore(source.Length);
				}
				else
				{
					WriteMultiSegment(source.Span);
				}
				PrepareFlushUnsynchronized(out completionData, out result, cancellationToken);
			}
			TrySchedule(ReaderScheduler, in completionData);
			return result;
		}

		private void WriteMultiSegment(ReadOnlySpan<byte> source)
		{
			Span<byte> span = _writingHeadMemory.Span;
			while (true)
			{
				int num = Math.Min(span.Length, source.Length);
				source.Slice(0, num).CopyTo(span);
				source = source.Slice(num);
				AdvanceCore(num);
				if (source.Length != 0)
				{
					_writingHead.End += _writingHeadBytesBuffered;
					_writingHeadBytesBuffered = 0;
					BufferSegment bufferSegment = AllocateSegment(0);
					_writingHead.SetNext(bufferSegment);
					_writingHead = bufferSegment;
					span = _writingHeadMemory.Span;
					continue;
				}
				break;
			}
		}

		internal void OnFlushAsyncCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags)
		{
			CompletionData completionData;
			bool doubleCompletion;
			lock (SyncObj)
			{
				_writerAwaitable.OnCompleted(continuation, state, flags, out completionData, out doubleCompletion);
			}
			if (doubleCompletion)
			{
				Reader.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation());
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		private void ReaderCancellationRequested()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_readerAwaitable.CancellationTokenFired(out completionData);
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		private void WriterCancellationRequested()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_writerAwaitable.CancellationTokenFired(out completionData);
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		public void Reset()
		{
			lock (SyncObj)
			{
				if (!_disposed)
				{
					ThrowHelper.ThrowInvalidOperationException_ResetIncompleteReaderWriter();
				}
				_disposed = false;
				ResetState();
			}
		}
	}
	[DebuggerDisplay("CanceledState = {_awaitableState}, IsCompleted = {IsCompleted}")]
	internal struct PipeAwaitable
	{
		[Flags]
		private enum AwaitableState
		{
			None = 0,
			Completed = 1,
			Running = 2,
			Canceled = 4,
			UseSynchronizationContext = 8
		}

		private sealed class SchedulingContext
		{
			public SynchronizationContext SynchronizationContext { get; set; }

			public ExecutionContext ExecutionContext { get; set; }
		}

		private AwaitableState _awaitableState;

		private Action<object> _completion;

		private object _completionState;

		private SchedulingContext _schedulingContext;

		private CancellationTokenRegistration _cancellationTokenRegistration;

		private CancellationToken _cancellationToken;

		private CancellationToken CancellationToken => _cancellationToken;

		public bool IsCompleted => (_awaitableState & (AwaitableState.Completed | AwaitableState.Canceled)) != 0;

		public bool IsRunning => (_awaitableState & AwaitableState.Running) != 0;

		public PipeAwaitable(bool completed, bool useSynchronizationContext)
		{
			_awaitableState = (completed ? AwaitableState.Completed : AwaitableState.None) | (useSynchronizationContext ? AwaitableState.UseSynchronizationContext : AwaitableState.None);
			_completion = null;
			_completionState = null;
			_cancellationTokenRegistration = default(CancellationTokenRegistration);
			_schedulingContext = null;
			_cancellationToken = CancellationToken.None;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginOperation(CancellationToken cancellationToken, Action<object?> callback, object? state)
		{
			if (cancellationToken.CanBeCanceled && !IsCompleted)
			{
				_cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, callback, state);
				if (_cancellationTokenRegistration == default(CancellationTokenRegistration))
				{
					cancellationToken.ThrowIfCancellationRequested();
				}
				_cancellationToken = cancellationToken;
			}
			_awaitableState |= AwaitableState.Running;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Complete(out CompletionData completionData)
		{
			ExtractCompletion(out completionData);
			_awaitableState |= AwaitableState.Completed;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void ExtractCompletion(out CompletionData completionData)
		{
			Action<object> completion = _completion;
			object completionState = _completionState;
			SchedulingContext schedulingContext = _schedulingContext;
			ExecutionContext executionContext = schedulingContext?.ExecutionContext;
			SynchronizationContext synchronizationContext = schedulingContext?.SynchronizationContext;
			_completion = null;
			_completionState = null;
			_schedulingContext = null;
			completionData = ((completion != null) ? new CompletionData(completion, completionState, executionContext, synchronizationContext) : default(CompletionData));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void SetUncompleted()
		{
			_awaitableState &= ~AwaitableState.Completed;
		}

		public void OnCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags, out CompletionData completionData, out bool doubleCompletion)
		{
			completionData = default(CompletionData);
			doubleCompletion = _completion != null;
			if (IsCompleted | doubleCompletion)
			{
				completionData = new CompletionData(continuation, state, _schedulingContext?.ExecutionContext, _schedulingContext?.SynchronizationContext);
				return;
			}
			_completion = continuation;
			_completionState = state;
			if ((_awaitableState & AwaitableState.UseSynchronizationContext) != 0 && (flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
			{
				SynchronizationContext current = SynchronizationContext.Current;
				if (current != null && current.GetType() != typeof(SynchronizationContext))
				{
					if (_schedulingContext == null)
					{
						_schedulingContext = new SchedulingContext();
					}
					_schedulingContext.SynchronizationContext = current;
				}
			}
			if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0)
			{
				if (_schedulingContext == null)
				{
					_schedulingContext = new SchedulingContext();
				}
				_schedulingContext.ExecutionContext = ExecutionContext.Capture();
			}
		}

		public void Cancel(out CompletionData completionData)
		{
			ExtractCompletion(out completionData);
			_awaitableState |= AwaitableState.Canceled;
		}

		public void CancellationTokenFired(out CompletionData completionData)
		{
			if (CancellationToken.IsCancellationRequested)
			{
				Cancel(out completionData);
			}
			else
			{
				completionData = default(CompletionData);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool ObserveCancellation()
		{
			bool result = (_awaitableState & AwaitableState.Canceled) == AwaitableState.Canceled;
			_awaitableState &= ~(AwaitableState.Running | AwaitableState.Canceled);
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public CancellationTokenRegistration ReleaseCancellationTokenRegistration(out CancellationToken cancellationToken)
		{
			cancellationToken = CancellationToken;
			CancellationTokenRegistration cancellationTokenRegistration = _cancellationTokenRegistration;
			_cancellationToken = default(CancellationToken);
			_cancellationTokenRegistration = default(CancellationTokenRegistration);
			return cancellationTokenRegistration;
		}
	}
	[DebuggerDisplay("IsCompleted = {IsCompleted}")]
	internal struct PipeCompletion
	{
		private static readonly object s_completedSuccessfully = new object();

		private object _state;

		private List<PipeCompletionCallback> _callbacks;

		public bool IsCompleted => _state != null;

		public bool IsFaulted => _state is ExceptionDispatchInfo;

		public PipeCompletionCallbacks? TryComplete(Exception? exception = null)
		{
			if (_state == null)
			{
				if (exception != null)
				{
					_state = ExceptionDispatchInfo.Capture(exception);
				}
				else
				{
					_state = s_completedSuccessfully;
				}
			}
			return GetCallbacks();
		}

		public PipeCompletionCallbacks? AddCallback(Action<Exception?, object?> callback, object? state)
		{
			if (_callbacks == null)
			{
				_callbacks = new List<PipeCompletionCallback>();
			}
			_callbacks.Add(new PipeCompletionCallback(callback, state));
			if (IsCompleted)
			{
				return GetCallbacks();
			}
			return null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool IsCompletedOrThrow()
		{
			if (!IsCompleted)
			{
				return false;
			}
			if (_state is ExceptionDispatchInfo exceptionDispatchInfo)
			{
				exceptionDispatchInfo.Throw();
			}
			return true;
		}

		private PipeCompletionCallbacks GetCallbacks()
		{
			List<PipeCompletionCallback> callbacks = _callbacks;
			if (callbacks == null)
			{
				return null;
			}
			_callbacks = null;
			return new PipeCompletionCallbacks(callbacks, _state as ExceptionDispatchInfo);
		}

		public void Reset()
		{
			_state = null;
		}

		public override string ToString()
		{
			return string.Format("{0}: {1}", "IsCompleted", IsCompleted);
		}
	}
	internal readonly struct PipeCompletionCallback
	{
		public readonly Action<Exception?, object?> Callback;

		public readonly object? State;

		public PipeCompletionCallback(Action<Exception?, object?> callback, object? state)
		{
			Callback = callback;
			State = state;
		}
	}
	internal sealed class PipeCompletionCallbacks
	{
		private readonly List<PipeCompletionCallback> _callbacks;

		private readonly Exception _exception;

		public PipeCompletionCallbacks(List<PipeCompletionCallback> callbacks, ExceptionDispatchInfo? edi)
		{
			_callbacks = callbacks;
			_exception = edi?.SourceException;
		}

		public void Execute()
		{
			int count = _callbacks.Count;
			if (count != 0)
			{
				List<Exception> exceptions = null;
				for (int i = 0; i < count; i++)
				{
					PipeCompletionCallback callback = _callbacks[i];
					Execute(callback, ref exceptions);
				}
				if (exceptions != null)
				{
					throw new AggregateException(exceptions);
				}
			}
		}

		private void Execute(PipeCompletionCallback callback, ref List<Exception> exceptions)
		{
			try
			{
				callback.Callback(_exception, callback.State);
			}
			catch (Exception item)
			{
				if (exceptions == null)
				{
					exceptions = new List<Exception>();
				}
				exceptions.Add(item);
			}
		}
	}
	public class PipeOptions
	{
		private const int DefaultMinimumSegmentSize = 4096;

		public static PipeOptions Default { get; } = new PipeOptions(null, null, null, -1L, -1L);


		public bool UseSynchronizationContext { get; }

		public long PauseWriterThreshold { get; }

		public long ResumeWriterThreshold { get; }

		public int MinimumSegmentSize { get; }

		public PipeScheduler WriterScheduler { get; }

		public PipeScheduler ReaderScheduler { get; }

		public MemoryPool<byte> Pool { get; }

		internal bool IsDefaultSharedMemoryPool { get; }

		internal int InitialSegmentPoolSize { get; }

		internal int MaxSegmentPoolSize { get; }

		public PipeOptions(MemoryPool<byte>? pool = null, PipeScheduler? readerScheduler = null, PipeScheduler? writerScheduler = null, long pauseWriterThreshold = -1L, long resumeWriterThreshold = -1L, int minimumSegmentSize = -1, bool useSynchronizationContext = true)
		{
			MinimumSegmentSize = ((minimumSegmentSize == -1) ? 4096 : minimumSegmentSize);
			InitialSegmentPoolSize = 4;
			MaxSegmentPoolSize = 256;
			if (pauseWriterThreshold == -1)
			{
				pauseWriterThreshold = 65536L;
			}
			else if (pauseWriterThreshold < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.pauseWriterThreshold);
			}
			switch (resumeWriterThreshold)
			{
			case -1L:
				resumeWriterThreshold = 32768L;
				break;
			case 0L:
				resumeWriterThreshold = 1L;
				break;
			}
			if (resumeWriterThreshold < 0 || (pauseWriterThreshold > 0 && resumeWriterThreshold > pauseWriterThreshold))
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.resumeWriterThreshold);
			}
			Pool = pool ?? MemoryPool<byte>.Shared;
			IsDefaultSharedMemoryPool = Pool == MemoryPool<byte>.Shared;
			ReaderScheduler = readerScheduler ?? PipeScheduler.ThreadPool;
			WriterScheduler = writerScheduler ?? PipeScheduler.ThreadPool;
			PauseWriterThreshold = pauseWriterThreshold;
			ResumeWriterThreshold = resumeWriterThreshold;
			UseSynchronizationContext = useSynchronizationContext;
		}
	}
	public abstract class PipeReader
	{
		private PipeReaderStream _stream;

		public abstract bool TryRead(out ReadResult result);

		public abstract ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken));

		public ValueTask<ReadResult> ReadAtLeastAsync(int minimumSize, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (minimumSize < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.minimumSize);
			}
			return ReadAtLeastAsyncCore(minimumSize, cancellationToken);
		}

		protected virtual async ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken)
		{
			ReadResult result;
			while (true)
			{
				result = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				ReadOnlySequence<byte> buffer = result.Buffer;
				if (buffer.Length >= minimumSize || result.IsCompleted || result.IsCanceled)
				{
					break;
				}
				AdvanceTo(buffer.Start, buffer.End);
			}
			return result;
		}

		public abstract void AdvanceTo(SequencePosition consumed);

		public abstract void AdvanceTo(SequencePosition consumed, SequencePosition examined);

		public virtual Stream AsStream(bool leaveOpen = false)
		{
			if (_stream == null)
			{
				_stream = new PipeReaderStream(this, leaveOpen);
			}
			else if (leaveOpen)
			{
				_stream.LeaveOpen = leaveOpen;
			}
			return _stream;
		}

		public abstract void CancelPendingRead();

		public abstract void Complete(Exception? exception = null);

		public virtual ValueTask CompleteAsync(Exception? exception = null)
		{
			try
			{
				Complete(exception);
				return default(ValueTask);
			}
			catch (Exception exception2)
			{
				return new ValueTask(Task.FromException(exception2));
			}
		}

		[Obsolete("OnWriterCompleted has been deprecated and may not be invoked on all implementations of PipeReader.")]
		public virtual void OnWriterCompleted(Action<Exception?, object?> callback, object? state)
		{
		}

		public static PipeReader Create(Stream stream, StreamPipeReaderOptions? readerOptions = null)
		{
			return new StreamPipeReader(stream, readerOptions ?? StreamPipeReaderOptions.s_default);
		}

		public static PipeReader Create(ReadOnlySequence<byte> sequence)
		{
			return new SequencePipeReader(sequence);
		}

		public virtual Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (destination == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return CopyToAsyncCore(destination, (PipeWriter destination, ReadOnlyMemory<byte> memory, CancellationToken cancellationToken) => destination.WriteAsync(memory, cancellationToken), cancellationToken);
		}

		public virtual Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (destination == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return CopyToAsyncCore(destination, delegate(Stream destination, ReadOnlyMemory<byte> memory, CancellationToken cancellationToken)
			{
				ValueTask writeTask2 = StreamExtensions.WriteAsync(destination, memory, cancellationToken);
				if (writeTask2.IsCompletedSuccessfully)
				{
					writeTask2.GetAwaiter().GetResult();
					return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: false));
				}
				return Awaited(writeTask2);
			}, cancellationToken);
			static async ValueTask<FlushResult> Awaited(ValueTask writeTask)
			{
				await writeTask.ConfigureAwait(continueOnCapturedContext: false);
				return new FlushResult(isCanceled: false, isCompleted: false);
			}
		}

		private async Task CopyToAsyncCore<TStream>(TStream destination, Func<TStream, ReadOnlyMemory<byte>, CancellationToken, ValueTask<FlushResult>> writeAsync, CancellationToken cancellationToken)
		{
			while (true)
			{
				ReadResult result = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				ReadOnlySequence<byte> buffer = result.Buffer;
				SequencePosition position = buffer.Start;
				SequencePosition consumed = position;
				try
				{
					if (result.IsCanceled)
					{
						ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
					}
					ReadOnlyMemory<byte> memory;
					while (buffer.TryGet(ref position, out memory))
					{
						if (memory.IsEmpty)
						{
							consumed = position;
							continue;
						}
						FlushResult flushResult = await writeAsync(destination, memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						if (flushResult.IsCanceled)
						{
							ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
						}
						consumed = position;
						if (!flushResult.IsCompleted)
						{
							continue;
						}
						return;
					}
					consumed = buffer.End;
					if (result.IsCompleted)
					{
						break;
					}
				}
				finally
				{
					AdvanceTo(consumed);
				}
			}
		}
	}
	[DebuggerDisplay("State = {_state}")]
	internal struct PipeOperationState
	{
		[Flags]
		internal enum State : byte
		{
			Reading = 1,
			ReadingTentative = 2,
			Writing = 4
		}

		private State _state;

		public bool IsWritingActive => (_state & State.Writing) == State.Writing;

		public bool IsReadingActive => (_state & State.Reading) == State.Reading;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginRead()
		{
			if ((_state & State.Reading) == State.Reading)
			{
				ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
			}
			_state |= State.Reading;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginReadTentative()
		{
			if ((_state & State.Reading) == State.Reading)
			{
				ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
			}
			_state |= State.ReadingTentative;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void EndRead()
		{
			if ((_state & State.Reading) != State.Reading && (_state & State.ReadingTentative) != State.ReadingTentative)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadToComplete();
			}
			_state &= ~(State.Reading | State.ReadingTentative);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginWrite()
		{
			_state |= State.Writing;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void EndWrite()
		{
			_state &= ~State.Writing;
		}
	}
	internal sealed class PipeReaderStream : Stream
	{
		private readonly PipeReader _pipeReader;

		public override bool CanRead => true;

		public override bool CanSeek => false;

		public override bool CanWrite => false;

		public override long Length
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public override long Position
		{
			get
			{
				throw new NotSupportedException();
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		internal bool LeaveOpen { get; set; }

		public PipeReaderStream(PipeReader pipeReader, bool leaveOpen)
		{
			_pipeReader = pipeReader;
			LeaveOpen = leaveOpen;
		}

		protected override void Dispose(bool disposing)
		{
			if (!LeaveOpen)
			{
				_pipeReader.Complete();
			}
			base.Dispose(disposing);
		}

		public override void Flush()
		{
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			if (buffer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
			}
			return ReadInternal(new Span<byte>(buffer, offset, count));
		}

		public override int ReadByte()
		{
			Span<byte> buffer = stackalloc byte[1];
			if (ReadInternal(buffer) != 0)
			{
				return buffer[0];
			}
			return -1;
		}

		private int ReadInternal(Span<byte> buffer)
		{
			ValueTask<ReadResult> valueTask = _pipeReader.ReadAsync();
			ReadResult result = (valueTask.IsCompletedSuccessfully ? valueTask.Result : valueTask.AsTask().GetAwaiter().GetResult());
			return HandleReadResult(result, buffer);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException();
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		public sealed override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
		{
			return TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count, default(CancellationToken)), callback, state);
		}

		public sealed override int EndRead(IAsyncResult asyncResult)
		{
			return TaskToAsyncResult.End<int>(asyncResult);
		}

		public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			if (buffer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
			}
			return ReadAsyncInternal(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();
		}

		private async ValueTask<int> ReadAsyncInternal(Memory<byte> buffer, CancellationToken cancellationToken)
		{
			return HandleReadResult(await _pipeReader.ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false), buffer.Span);
		}

		private int HandleReadResult(ReadResult result, Span<byte> buffer)
		{
			if (result.IsCanceled)
			{
				ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
			}
			ReadOnlySequence<byte> buffer2 = result.Buffer;
			long length = buffer2.Length;
			SequencePosition consumed = buffer2.Start;
			try
			{
				if (length != 0L)
				{
					int num = (int)Math.Min(length, buffer.Length);
					ReadOnlySequence<byte> source = ((num == length) ? buffer2 : buffer2.Slice(0, num));
					consumed = source.End;
					source.CopyTo(buffer);
					return num;
				}
				if (result.IsCompleted)
				{
					return 0;
				}
			}
			finally
			{
				_pipeReader.AdvanceTo(consumed);
			}
			ThrowHelper.ThrowInvalidOperationException_InvalidZeroByteRead();
			return 0;
		}

		public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
		{
			StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
			return _pipeReader.CopyToAsync(destination, cancellationToken);
		}
	}
	public abstract class PipeScheduler
	{
		private static readonly ThreadPoolScheduler s_threadPoolScheduler = new ThreadPoolScheduler();

		private static readonly InlineScheduler s_inlineScheduler = new InlineScheduler();

		public static PipeScheduler ThreadPool => s_threadPoolScheduler;

		public static PipeScheduler Inline => s_inlineScheduler;

		public abstract void Schedule(Action<object?> action, object? state);

		internal virtual void UnsafeSchedule(Action<object?> action, object? state)
		{
			Schedule(action, state);
		}
	}
	public abstract class PipeWriter : IBufferWriter<byte>
	{
		private PipeWriterStream _stream;

		public virtual bool CanGetUnflushedBytes => false;

		public virtual long UnflushedBytes
		{
			get
			{
				throw ThrowHelper.CreateNotSupportedException_UnflushedBytes();
			}
		}

		public abstract void Complete(Exception? exception = null);

		public virtual ValueTask CompleteAsync(Exception? exception = null)
		{
			try
			{
				Complete(exception);
				return default(ValueTask);
			}
			catch (Exception exception2)
			{
				return new ValueTask(Task.FromException(exception2));
			}
		}

		public abstract void CancelPendingFlush();

		[Obsolete("OnReaderCompleted has been deprecated and may not be invoked on all implementations of PipeWriter.")]
		public virtual void OnReaderCompleted(Action<Exception?, object?> callback, object? state)
		{
		}

		public abstract ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken));

		public abstract void Advance(int bytes);

		public abstract Memory<byte> GetMemory(int sizeHint = 0);

		public abstract Span<byte> GetSpan(int sizeHint = 0);

		public virtual Stream AsStream(bool leaveOpen = false)
		{
			if (_stream == null)
			{
				_stream = new PipeWriterStream(this, leaveOpen);
			}
			else if (leaveOpen)
			{
				_stream.LeaveOpen = leaveOpen;
			}
			return _stream;
		}

		public static PipeWriter Create(Stream stream, StreamPipeWriterOptions? writerOptions = null)
		{
			return new StreamPipeWriter(stream, writerOptions ?? StreamPipeWriterOptions.s_default);
		}

		public virtual ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
		{
			this.Write(source.Span);
			return FlushAsync(cancellationToken);
		}

		protected internal virtual async Task CopyFromAsync(Stream source, CancellationToken cancellationToken = default(CancellationToken))
		{
			FlushResult flushResult;
			do
			{
				Memory<byte> memory = GetMemory();
				int num = await StreamExtensions.ReadAsync(source, memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				if (num != 0)
				{
					Advance(num);
					flushResult = await FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					if (flushResult.IsCanceled)
					{
						ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
					}
					continue;
				}
				break;
			}
			while (!flushResult.IsCompleted);
		}
	}
	internal sealed class PipeWriterStream : Stream
	{
		private readonly PipeWriter _pipeWriter;

		internal bool LeaveOpen { get; set; }

		public override bool CanRead => false;

		public override bool CanSeek => false;

		public override bool CanWrite => true;

		public override long Length
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public override long Position
		{
			get
			{
				throw new NotSupportedException();
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public PipeWriterStream(PipeWriter pipeWriter, bool leaveOpen)
		{
			_pipeWriter = pipeWriter;
			LeaveOpen = leaveOpen;
		}

		protected override void Dispose(bool disposing)
		{
			if (!LeaveOpen)
			{
				_pipeWriter.Complete();
			}
		}

		public override void Flush()
		{
			FlushAsync().GetAwaiter().GetResult();
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException();
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public sealed override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
		{
			return TaskToAsyncResult.Begin(WriteAsync(buffer, offset, count, default(CancellationToken)), callback, state);
		}

		public sealed override void EndWrite(IAsyncResult asyncResult)
		{
			TaskToAsyncResult.End(asyncResult);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
		}

		public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			if (buffer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
			}
			return GetFlushResultAsTask(_pipeWriter.WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken));
		}

		public override Task FlushAsync(CancellationToken cancellationToken)
		{
			return GetFlushResultAsTask(_pipeWriter.FlushAsync(cancellationToken));
		}

		private static Task GetFlushResultAsTask(ValueTask<FlushResult> valueTask)
		{
			if (valueTask.IsCompletedSuccessfully)
			{
				if (valueTask.Result.IsCanceled)
				{
					ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
				}
				return Task.CompletedTask;
			}
			return AwaitTask(valueTask);
			static async Task AwaitTask(ValueTask<FlushResult> valueTask)
			{
				if ((await valueTask.ConfigureAwait(continueOnCapturedContext: false)).IsCanceled)
				{
					ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
				}
			}
		}
	}
	public readonly struct ReadResult
	{
		internal readonly ReadOnlySequence<byte> _resultBuffer;

		internal readonly ResultFlags _resultFlags;

		public ReadOnlySequence<byte> Buffer => _resultBuffer;

		public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0;

		public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0;

		public ReadResult(ReadOnlySequence<byte> buffer, bool isCanceled, bool isCompleted)
		{
			_resultBuffer = buffer;
			_resultFlags = ResultFlags.None;
			if (isCompleted)
			{
				_resultFlags |= ResultFlags.Completed;
			}
			if (isCanceled)
			{
				_resultFlags |= ResultFlags.Canceled;
			}
		}
	}
	[Flags]
	internal enum ResultFlags : byte
	{
		None = 0,
		Canceled = 1,
		Completed = 2
	}
	internal sealed class SequencePipeReader : PipeReader
	{
		private ReadOnlySequence<byte> _sequence;

		private bool _isReaderCompleted;

		private int _cancelNext;

		public SequencePipeReader(ReadOnlySequence<byte> sequence)
		{
			_sequence = sequence;
		}

		public override void AdvanceTo(SequencePosition consumed)
		{
			AdvanceTo(consumed, consumed);
		}

		public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
		{
			ThrowIfCompleted();
			if (consumed.Equals(_sequence.End))
			{
				_sequence = ReadOnlySequence<byte>.Empty;
			}
			else
			{
				_sequence = _sequence.Slice(consumed);
			}
		}

		public override void CancelPendingRead()
		{
			Interlocked.Exchange(ref _cancelNext, 1);
		}

		public override void Complete(Exception? exception = null)
		{
			if (!_isReaderCompleted)
			{
				_isReaderCompleted = true;
				_sequence = ReadOnlySequence<byte>.Empty;
			}
		}

		public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TryRead(out var result))
			{
				return new ValueTask<ReadResult>(result);
			}
			result = new ReadResult(ReadOnlySequence<byte>.Empty, isCanceled: false, isCompleted: true);
			return new ValueTask<ReadResult>(result);
		}

		public override bool TryRead(out ReadResult result)
		{
			ThrowIfCompleted();
			bool flag = Interlocked.Exchange(ref _cancelNext, 0) == 1;
			if (flag || _sequence.Length > 0)
			{
				result = new ReadResult(_sequence, flag, isCompleted: true);
				return true;
			}
			result = default(ReadResult);
			return false;
		}

		private void ThrowIfCompleted()
		{
			if (_isReaderCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
		}
	}
	public static class StreamPipeExtensions
	{
		public static Task CopyToAsync(this Stream source, PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
			}
			if (destination == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return destination.CopyFromAsync(source, cancellationToken);
		}
	}
	internal sealed class StreamPipeReader : PipeReader
	{
		internal const int InitialSegmentPoolSize = 4;

		internal const int MaxSegmentPoolSize = 256;

		private CancellationTokenSource _internalTokenSource;

		private bool _isReaderCompleted;

		private bool _isStreamCompleted;

		private BufferSegment _readHead;

		private int _readIndex;

		private BufferSegment _readTail;

		private long _bufferedBytes;

		private bool _examinedEverything;

		private readonly object _lock = new object();

		private BufferSegmentStack _bufferSegmentPool;

		private readonly StreamPipeReaderOptions _options;

		private bool LeaveOpen => _options.LeaveOpen;

		private bool UseZeroByteReads => _options.UseZeroByteReads;

		private int BufferSize => _options.BufferSize;

		private int MaxBufferSize => _options.MaxBufferSize;

		private int MinimumReadThreshold => _options.MinimumReadSize;

		private MemoryPool<byte> Pool => _options.Pool;

		public Stream InnerStream { get; }

		private CancellationTokenSource InternalTokenSource
		{
			get
			{
				lock (_lock)
				{
					return _internalTokenSource ?? (_internalTokenSource = new CancellationTokenSource());
				}
			}
		}

		public StreamPipeReader(Stream readingStream, StreamPipeReaderOptions options)
		{
			if (readingStream == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.readingStream);
			}
			if (options == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
			}
			InnerStream = readingStream;
			_options = options;
			_bufferSegmentPool = new BufferSegmentStack(4);
		}

		public override void AdvanceTo(SequencePosition consumed)
		{
			AdvanceTo(consumed, consumed);
		}

		public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
		{
			ThrowIfCompleted();
			AdvanceTo((BufferSegment)consumed.GetObject(), consumed.GetInteger(), (BufferSegment)examined.GetObject(), examined.GetInteger());
		}

		private void AdvanceTo(BufferSegment consumedSegment, int consumedIndex, BufferSegment examinedSegment, int examinedIndex)
		{
			if (consumedSegment != null && examinedSegment != null)
			{
				if (_readHead == null)
				{
					ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor();
				}
				BufferSegment bufferSegment = _readHead;
				BufferSegment bufferSegment2 = consumedSegment;
				long length = BufferSegment.GetLength(bufferSegment, _readIndex, consumedSegment, consumedIndex);
				_bufferedBytes -= length;
				_examinedEverything = false;
				if (examinedSegment == _readTail)
				{
					_examinedEverything = examinedIndex == _readTail.End;
				}
				if (_bufferedBytes == 0L)
				{
					bufferSegment2 = null;
					_readHead = null;
					_readTail = null;
					_readIndex = 0;
				}
				else if (consumedIndex == bufferSegment2.Length)
				{
					BufferSegment bufferSegment3 = (_readHead = bufferSegment2.NextSegment);
					_readIndex = 0;
					bufferSegment2 = bufferSegment3;
				}
				else
				{
					_readHead = consumedSegment;
					_readIndex = consumedIndex;
				}
				while (bufferSegment != bufferSegment2)
				{
					BufferSegment? nextSegment = bufferSegment.NextSegment;
					ReturnSegmentUnsynchronized(bufferSegment);
					bufferSegment = nextSegment;
				}
			}
		}

		public override void CancelPendingRead()
		{
			InternalTokenSource.Cancel();
		}

		public override void Complete(Exception? exception = null)
		{
			if (CompleteAndGetNeedsDispose())
			{
				InnerStream.Dispose();
			}
		}

		private bool CompleteAndGetNeedsDispose()
		{
			if (_isReaderCompleted)
			{
				return false;
			}
			_isReaderCompleted = true;
			BufferSegment bufferSegment = _readHead;
			while (bufferSegment != null)
			{
				BufferSegment bufferSegment2 = bufferSegment;
				bufferSegment = bufferSegment.NextSegment;
				bufferSegment2.Reset();
			}
			return !LeaveOpen;
		}

		public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return ReadInternalAsync(null, cancellationToken);
		}

		protected override ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken)
		{
			return ReadInternalAsync(minimumSize, cancellationToken);
		}

		private ValueTask<ReadResult> ReadInternalAsync(int? minimumSize, CancellationToken cancellationToken)
		{
			ThrowIfCompleted();
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(cancellationToken));
			}
			CancellationTokenSource internalTokenSource = InternalTokenSource;
			if (TryReadInternal(internalTokenSource, out var result) && (!minimumSize.HasValue || result.Buffer.Length >= minimumSize || result.IsCompleted || result.IsCanceled))
			{
				return new ValueTask<ReadResult>(result);
			}
			if (_isStreamCompleted)
			{
				return new ValueTask<ReadResult>(new ReadResult(default(ReadOnlySequence<byte>), isCanceled: false, isCompleted: true));
			}
			return Core(this, minimumSize, internalTokenSource, cancellationToken);
			static async ValueTask<ReadResult> Core(StreamPipeReader reader, int? minimumSize, CancellationTokenSource tokenSource, CancellationToken cancellationToken)
			{
				CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
				if (cancellationToken.CanBeCanceled)
				{
					cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
					{
						((StreamPipeReader)state).Cancel();
					}, reader);
				}
				using (cancellationTokenRegistration)
				{
					bool isCanceled = false;
					try
					{
						if (reader.UseZeroByteReads && reader._bufferedBytes == 0L)
						{
							await StreamExtensions.ReadAsync(reader.InnerStream, Memory<byte>.Empty, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
						}
						do
						{
							reader.AllocateReadTail(minimumSize);
							Memory<byte> buffer = reader._readTail.AvailableMemory.Slice(reader._readTail.End);
							int num = await StreamExtensions.ReadAsync(reader.InnerStream, buffer, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
							reader._readTail.End += num;
							reader._bufferedBytes += num;
							if (num == 0)
							{
								reader._isStreamCompleted = true;
								break;
							}
						}
						while (minimumSize.HasValue && reader._bufferedBytes < minimumSize);
					}
					catch (OperationCanceledException ex)
					{
						reader.ClearCancellationToken();
						if (cancellationToken.IsCancellationRequested)
						{
							throw new OperationCanceledException(ex.Message, ex, cancellationToken);
						}
						if (!tokenSource.IsCancellationRequested)
						{
							throw;
						}
						isCanceled = true;
					}
					return new ReadResult(reader.GetCurrentReadOnlySequence(), isCanceled, reader._isStreamCompleted);
				}
			}
		}

		public override async Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			ThrowIfCompleted();
			CancellationTokenSource tokenSource = InternalTokenSource;
			if (tokenSource.IsCancellationRequested)
			{
				ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
			}
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
				{
					((StreamPipeReader)state).Cancel();
				}, this);
			}
			using (cancellationTokenRegistration)
			{
				_ = 1;
				try
				{
					BufferSegment segment = _readHead;
					int start = _readIndex;
					try
					{
						while (segment != null)
						{
							FlushResult flushResult = await destination.WriteAsync(segment.Memory.Slice(start), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
							if (flushResult.IsCanceled)
							{
								ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
							}
							segment = segment.NextSegment;
							start = 0;
							if (flushResult.IsCompleted)
							{
								return;
							}
						}
					}
					finally
					{
						if (segment != null)
						{
							AdvanceTo(segment, segment.End, segment, segment.End);
						}
					}
					if (_isStreamCompleted)
					{
						return;
					}
					await InnerStream.CopyToAsync(destination, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (OperationCanceledException)
				{
					ClearCancellationToken();
					throw;
				}
			}
		}

		public override async Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			ThrowIfCompleted();
			CancellationTokenSource tokenSource = InternalTokenSource;
			if (tokenSource.IsCancellationRequested)
			{
				ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
			}
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
				{
					((StreamPipeReader)state).Cancel();
				}, this);
			}
			using (cancellationTokenRegistration)
			{
				_ = 1;
				try
				{
					BufferSegment segment = _readHead;
					int start = _readIndex;
					try
					{
						while (segment != null)
						{
							await StreamExtensions.WriteAsync(destination, segment.Memory.Slice(start), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
							segment = segment.NextSegment;
							start = 0;
						}
					}
					finally
					{
						if (segment != null)
						{
							AdvanceTo(segment, segment.End, segment, segment.End);
						}
					}
					if (_isStreamCompleted)
					{
						return;
					}
					await StreamExtensions.CopyToAsync(InnerStream, destination, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (OperationCanceledException)
				{
					ClearCancellationToken();
					throw;
				}
			}
		}

		private void ClearCancellationToken()
		{
			lock (_lock)
			{
				_internalTokenSource = null;
			}
		}

		private void ThrowIfCompleted()
		{
			if (_isReaderCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
		}

		public override bool TryRead(out ReadResult result)
		{
			ThrowIfCompleted();
			return TryReadInternal(InternalTokenSource, out result);
		}

		private bool TryReadInternal(CancellationTokenSource source, out ReadResult result)
		{
			bool isCancellationRequested = source.IsCancellationRequested;
			if (isCancellationRequested || (_bufferedBytes > 0 && (!_examinedEverything || _isStreamCompleted)))
			{
				if (isCancellationRequested)
				{
					ClearCancellationToken();
				}
				ReadOnlySequence<byte> currentReadOnlySequence = GetCurrentReadOnlySequence();
				result = new ReadResult(currentReadOnlySequence, isCancellationRequested, _isStreamCompleted);
				return true;
			}
			result = default(ReadResult);
			return false;
		}

		private ReadOnlySequence<byte> GetCurrentReadOnlySequence()
		{
			if (_readHead != null)
			{
				return new ReadOnlySequence<byte>(_readHead, _readIndex, _readTail, _readTail.End);
			}
			return default(ReadOnlySequence<byte>);
		}

		private void AllocateReadTail(int? minimumSize = null)
		{
			if (_readHead == null)
			{
				_readHead = AllocateSegment(minimumSize);
				_readTail = _readHead;
			}
			else if (_readTail.WritableBytes < MinimumReadThreshold)
			{
				BufferSegment bufferSegment = AllocateSegment(minimumSize);
				_readTail.SetNext(bufferSegment);
				_readTail = bufferSegment;
			}
		}

		private BufferSegment AllocateSegment(int? minimumSize = null)
		{
			BufferSegment bufferSegment = CreateSegmentUnsynchronized();
			int num = minimumSize ?? BufferSize;
			int num2 = ((!_options.IsDefaultSharedMemoryPool) ? _options.Pool.MaxBufferSize : (-1));
			if (num <= num2)
			{
				int segmentSize = GetSegmentSize(num, num2);
				bufferSegment.SetOwnedMemory(_options.Pool.Rent(segmentSize));
			}
			else
			{
				int segmentSize2 = GetSegmentSize(num, MaxBufferSize);
				bufferSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize2));
			}
			return bufferSegment;
		}

		private int GetSegmentSize(int sizeHint, int maxBufferSize)
		{
			sizeHint = Math.Max(BufferSize, sizeHint);
			return Math.Min(maxBufferSize, sizeHint);
		}

		private BufferSegment CreateSegmentUnsynchronized()
		{
			if (_bufferSegmentPool.TryPop(out BufferSegment result))
			{
				return result;
			}
			return new BufferSegment();
		}

		private void ReturnSegmentUnsynchronized(BufferSegment segment)
		{
			segment.Reset();
			if (_bufferSegmentPool.Count < 256)
			{
				_bufferSegmentPool.Push(segment);
			}
		}

		private void Cancel()
		{
			InternalTokenSource.Cancel();
		}
	}
	public class StreamPipeReaderOptions
	{
		private const int DefaultBufferSize = 4096;

		internal const int DefaultMaxBufferSize = 2097152;

		private const int DefaultMinimumReadSize = 1024;

		internal static readonly StreamPipeReaderOptions s_default = new StreamPipeReaderOptions();

		public int BufferSize { get; }

		internal int MaxBufferSize { get; } = 2097152;


		public int MinimumReadSize { get; }

		public MemoryPool<byte> Pool { get; }

		public bool LeaveOpen { get; }

		public bool UseZeroByteReads { get; }

		internal bool IsDefaultSharedMemoryPool { get; }

		public StreamPipeReaderOptions(MemoryPool<byte>? pool, int bufferSize, int minimumReadSize, bool leaveOpen)
			: this(pool, bufferSize, minimumReadSize, leaveOpen, useZeroByteReads: false)
		{
		}

		public StreamPipeReaderOptions(MemoryPool<byte>? pool = null, int bufferSize = -1, int minimumReadSize = -1, bool leaveOpen = false, bool useZeroByteReads = false)
		{
			Pool = pool ?? MemoryPool<byte>.Shared;
			IsDefaultSharedMemoryPool = Pool == MemoryPool<byte>.Shared;
			int num;
			if (bufferSize != -1)
			{
				if (bufferSize <= 0)
				{
					throw new ArgumentOutOfRangeException("bufferSize");
				}
				num = bufferSize;
			}
			else
			{
				num = 4096;
			}
			BufferSize = num;
			int num2;
			if (minimumReadSize != -1)
			{
				if (minimumReadSize <= 0)
				{
					throw new ArgumentOutOfRangeException("minimumReadSize");
				}
				num2 = minimumReadSize;
			}
			else
			{
				num2 = 1024;
			}
			MinimumReadSize = num2;
			LeaveOpen = leaveOpen;
			UseZeroByteReads = useZeroByteReads;
		}
	}
	internal sealed class StreamPipeWriter : PipeWriter
	{
		internal const int InitialSegmentPoolSize = 4;

		internal const int MaxSegmentPoolSize = 256;

		private readonly int _minimumBufferSize;

		private BufferSegment _head;

		private BufferSegment _tail;

		private Memory<byte> _tailMemory;

		private int _tailBytesBuffered;

		private int _bytesBuffered;

		private readonly MemoryPool<byte> _pool;

		private readonly int _maxPooledBufferSize;

		private CancellationTokenSource _internalTokenSource;

		private bool _isCompleted;

		private readonly object _lockObject = new object();

		private BufferSegmentStack _bufferSegmentPool;

		private readonly bool _leaveOpen;

		private CancellationTokenSource InternalTokenSource
		{
			get
			{
				lock (_lockObject)
				{
					return _internalTokenSource ?? (_internalTokenSource = new CancellationTokenSource());
				}
			}
		}

		public Stream InnerStream { get; }

		public override bool CanGetUnflushedBytes => true;

		public override long UnflushedBytes => _bytesBuffered;

		public StreamPipeWriter(Stream writingStream, StreamPipeWriterOptions options)
		{
			if (writingStream == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.writingStream);
			}
			if (options == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
			}
			InnerStream = writingStream;
			_minimumBufferSize = options.MinimumBufferSize;
			_pool = ((options.Pool == MemoryPool<byte>.Shared) ? null : options.Pool);
			_maxPooledBufferSize = _pool?.MaxBufferSize ?? (-1);
			_bufferSegmentPool = new BufferSegmentStack(4);
			_leaveOpen = options.LeaveOpen;
		}

		public override void Advance(int bytes)
		{
			if ((uint)bytes > (uint)_tailMemory.Length)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes);
			}
			_tailBytesBuffered += bytes;
			_bytesBuffered += bytes;
			_tailMemory = _tailMemory.Slice(bytes);
		}

		public override Memory<byte> GetMemory(int sizeHint = 0)
		{
			if (_isCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateMemory(sizeHint);
			return _tailMemory;
		}

		public override Span<byte> GetSpan(int sizeHint = 0)
		{
			if (_isCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateMemory(sizeHint);
			return _tailMemory.Span;
		}

		private void AllocateMemory(int sizeHint)
		{
			if (_head == null)
			{
				BufferSegment tail = AllocateSegment(sizeHint);
				_head = (_tail = tail);
				_tailBytesBuffered = 0;
				return;
			}
			int length = _tailMemory.Length;
			if (length == 0 || length < sizeHint)
			{
				if (_tailBytesBuffered > 0)
				{
					_tail.End += _tailBytesBuffered;
					_tailBytesBuffered = 0;
				}
				BufferSegment bufferSegment = AllocateSegment(sizeHint);
				_tail.SetNext(bufferSegment);
				_tail = bufferSegment;
			}
		}

		private BufferSegment AllocateSegment(int sizeHint)
		{
			BufferSegment bufferSegment = CreateSegmentUnsynchronized();
			int maxPooledBufferSize = _maxPooledBufferSize;
			if (sizeHint <= maxPooledBufferSize)
			{
				bufferSegment.SetOwnedMemory(_pool.Rent(GetSegmentSize(sizeHint, maxPooledBufferSize)));
			}
			else
			{
				int segmentSize = GetSegmentSize(sizeHint);
				bufferSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize));
			}
			_tailMemory = bufferSegment.AvailableMemory;
			return bufferSegment;
		}

		private int GetSegmentSize(int sizeHint, int maxBufferSize = int.MaxValue)
		{
			sizeHint = Math.Max(_minimumBufferSize, sizeHint);
			return Math.Min(maxBufferSize, sizeHint);
		}

		private BufferSegment CreateSegmentUnsynchronized()
		{
			if (_bufferSegmentPool.TryPop(out BufferSegment result))
			{
				return result;
			}
			return new BufferSegment();
		}

		private void ReturnSegmentUnsynchronized(BufferSegment segment)
		{
			segment.Reset();
			if (_bufferSegmentPool.Count < 256)
			{
				_bufferSegmentPool.Push(segment);
			}
		}

		public override void CancelPendingFlush()
		{
			Cancel();
		}

		public override void Complete(Exception? exception = null)
		{
			if (_isCompleted)
			{
				return;
			}
			_isCompleted = true;
			try
			{
				FlushInternal(exception == null);
			}
			finally
			{
				_internalTokenSource?.Dispose();
				if (!_leaveOpen)
				{
					InnerStream.Dispose();
				}
			}
		}

		public override async ValueTask CompleteAsync(Exception? exception = null)
		{
			if (_isCompleted)
			{
				return;
			}
			_isCompleted = true;
			try
			{
				await FlushAsyncInternal(exception == null, Memory<byte>.Empty).ConfigureAwait(continueOnCapturedContext: false);
			}
			finally
			{
				_internalTokenSource?.Dispose();
				if (!_leaveOpen)
				{
					InnerStream.Dispose();
				}
			}
		}

		public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (_bytesBuffered == 0)
			{
				return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: false));
			}
			return FlushAsyncInternal(writeToStream: true, Memory<byte>.Empty, cancellationToken);
		}

		public override ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return FlushAsyncInternal(writeToStream: true, source, cancellationToken);
		}

		private void Cancel()
		{
			InternalTokenSource.Cancel();
		}

		private async ValueTask<FlushResult> FlushAsyncInternal(bool writeToStream, ReadOnlyMemory<byte> data, CancellationToken cancellationToken = default(CancellationToken))
		{
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
				{
					((StreamPipeWriter)state).Cancel();
				}, this);
			}
			if (_tailBytesBuffered > 0)
			{
				_tail.End += _tailBytesBuffered;
				_tailBytesBuffered = 0;
			}
			using (cancellationTokenRegistration)
			{
				CancellationToken localToken = InternalTokenSource.Token;
				try
				{
					BufferSegment segment = _head;
					while (segment != null)
					{
						BufferSegment returnSegment = segment;
						segment = segment.NextSegment;
						if (returnSegment.Length > 0 && writeToStream)
						{
							await StreamExtensions.WriteAsync(InnerStream, returnSegment.Memory, localToken).ConfigureAwait(continueOnCapturedContext: false);
						}
						ReturnSegmentUnsynchronized(returnSegment);
						_head = segment;
					}
					if (writeToStream)
					{
						if (data.Length > 0)
						{
							await StreamExtensions.WriteAsync(InnerStream, data, localToken).ConfigureAwait(continueOnCapturedContext: false);
						}
						if (_bytesBuffered > 0 || data.Length > 0)
						{
							await InnerStream.FlushAsync(localToken).ConfigureAwait(continueOnCapturedContext: false);
						}
					}
					_head = null;
					_tail = null;
					_tailMemory =

System.Memory.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using FxResources.System.Memory;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Memory")]
[assembly: AssemblyDescription("System.Memory")]
[assembly: AssemblyDefaultAlias("System.Memory")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.31308.01")]
[assembly: AssemblyInformationalVersion("4.6.31308.01 @BuiltBy: cloudtest-841353dfc000000 @Branch: release/2.1-MSRC @SrcCode: https://github.com/dotnet/corefx/tree/32b491939fbd125f304031c35038b1e14b4e3958")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.1.2")]
[module: UnverifiableCode]
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]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
}
namespace FxResources.System.Memory
{
	internal static class SR
	{
	}
}
namespace System
{
	public readonly struct SequencePosition : IEquatable<SequencePosition>
	{
		private readonly object _object;

		private readonly int _integer;

		public SequencePosition(object @object, int integer)
		{
			_object = @object;
			_integer = integer;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public object GetObject()
		{
			return _object;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public int GetInteger()
		{
			return _integer;
		}

		public bool Equals(SequencePosition other)
		{
			if (_integer == other._integer)
			{
				return object.Equals(_object, other._object);
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			if (obj is SequencePosition other)
			{
				return Equals(other);
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return HashHelpers.Combine(_object?.GetHashCode() ?? 0, _integer);
		}
	}
	internal static class ThrowHelper
	{
		internal static void ThrowArgumentNullException(System.ExceptionArgument argument)
		{
			throw CreateArgumentNullException(argument);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentNullException(System.ExceptionArgument argument)
		{
			return new ArgumentNullException(argument.ToString());
		}

		internal static void ThrowArrayTypeMismatchException()
		{
			throw CreateArrayTypeMismatchException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArrayTypeMismatchException()
		{
			return new ArrayTypeMismatchException();
		}

		internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type)
		{
			throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type)
		{
			return new ArgumentException(System.SR.Format(System.SR.Argument_InvalidTypeWithPointersNotSupported, type));
		}

		internal static void ThrowArgumentException_DestinationTooShort()
		{
			throw CreateArgumentException_DestinationTooShort();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_DestinationTooShort()
		{
			return new ArgumentException(System.SR.Argument_DestinationTooShort);
		}

		internal static void ThrowIndexOutOfRangeException()
		{
			throw CreateIndexOutOfRangeException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateIndexOutOfRangeException()
		{
			return new IndexOutOfRangeException();
		}

		internal static void ThrowArgumentOutOfRangeException()
		{
			throw CreateArgumentOutOfRangeException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException()
		{
			return new ArgumentOutOfRangeException();
		}

		internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			throw CreateArgumentOutOfRangeException(argument);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			return new ArgumentOutOfRangeException(argument.ToString());
		}

		internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge()
		{
			throw CreateArgumentOutOfRangeException_PrecisionTooLarge();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge()
		{
			return new ArgumentOutOfRangeException("precision", System.SR.Format(System.SR.Argument_PrecisionTooLarge, (byte)99));
		}

		internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit()
		{
			throw CreateArgumentOutOfRangeException_SymbolDoesNotFit();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit()
		{
			return new ArgumentOutOfRangeException("symbol", System.SR.Argument_BadFormatSpecifier);
		}

		internal static void ThrowInvalidOperationException()
		{
			throw CreateInvalidOperationException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException()
		{
			return new InvalidOperationException();
		}

		internal static void ThrowInvalidOperationException_OutstandingReferences()
		{
			throw CreateInvalidOperationException_OutstandingReferences();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_OutstandingReferences()
		{
			return new InvalidOperationException(System.SR.OutstandingReferences);
		}

		internal static void ThrowInvalidOperationException_UnexpectedSegmentType()
		{
			throw CreateInvalidOperationException_UnexpectedSegmentType();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_UnexpectedSegmentType()
		{
			return new InvalidOperationException(System.SR.UnexpectedSegmentType);
		}

		internal static void ThrowInvalidOperationException_EndPositionNotReached()
		{
			throw CreateInvalidOperationException_EndPositionNotReached();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_EndPositionNotReached()
		{
			return new InvalidOperationException(System.SR.EndPositionNotReached);
		}

		internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange()
		{
			throw CreateArgumentOutOfRangeException_PositionOutOfRange();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange()
		{
			return new ArgumentOutOfRangeException("position");
		}

		internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange()
		{
			throw CreateArgumentOutOfRangeException_OffsetOutOfRange();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange()
		{
			return new ArgumentOutOfRangeException("offset");
		}

		internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer()
		{
			throw CreateObjectDisposedException_ArrayMemoryPoolBuffer();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer()
		{
			return new ObjectDisposedException("ArrayMemoryPoolBuffer");
		}

		internal static void ThrowFormatException_BadFormatSpecifier()
		{
			throw CreateFormatException_BadFormatSpecifier();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateFormatException_BadFormatSpecifier()
		{
			return new FormatException(System.SR.Argument_BadFormatSpecifier);
		}

		internal static void ThrowArgumentException_OverlapAlignmentMismatch()
		{
			throw CreateArgumentException_OverlapAlignmentMismatch();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_OverlapAlignmentMismatch()
		{
			return new ArgumentException(System.SR.Argument_OverlapAlignmentMismatch);
		}

		internal static void ThrowNotSupportedException()
		{
			throw CreateThrowNotSupportedException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateThrowNotSupportedException()
		{
			return new NotSupportedException();
		}

		public static bool TryFormatThrowFormatException(out int bytesWritten)
		{
			bytesWritten = 0;
			ThrowFormatException_BadFormatSpecifier();
			return false;
		}

		public static bool TryParseThrowFormatException<T>(out T value, out int bytesConsumed)
		{
			value = default(T);
			bytesConsumed = 0;
			ThrowFormatException_BadFormatSpecifier();
			return false;
		}

		public static void ThrowArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment)
		{
			throw CreateArgumentValidationException(startSegment, startIndex, endSegment);
		}

		private static Exception CreateArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment)
		{
			if (startSegment == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.startSegment);
			}
			if (endSegment == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.endSegment);
			}
			if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.endSegment);
			}
			if ((uint)startSegment.Memory.Length < (uint)startIndex)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.startIndex);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.endIndex);
		}

		public static void ThrowArgumentValidationException(Array array, int start)
		{
			throw CreateArgumentValidationException(array, start);
		}

		private static Exception CreateArgumentValidationException(Array array, int start)
		{
			if (array == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.array);
			}
			if ((uint)start > (uint)array.Length)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.length);
		}

		public static void ThrowStartOrEndArgumentValidationException(long start)
		{
			throw CreateStartOrEndArgumentValidationException(start);
		}

		private static Exception CreateStartOrEndArgumentValidationException(long start)
		{
			if (start < 0)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.length);
		}
	}
	internal enum ExceptionArgument
	{
		length,
		start,
		minimumBufferSize,
		elementIndex,
		comparable,
		comparer,
		destination,
		offset,
		startSegment,
		endSegment,
		startIndex,
		endIndex,
		array,
		culture,
		manager
	}
	internal static class DecimalDecCalc
	{
		private static uint D32DivMod1E9(uint hi32, ref uint lo32)
		{
			ulong num = ((ulong)hi32 << 32) | lo32;
			lo32 = (uint)(num / 1000000000);
			return (uint)(num % 1000000000);
		}

		internal static uint DecDivMod1E9(ref MutableDecimal value)
		{
			return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0u, ref value.High), ref value.Mid), ref value.Low);
		}

		internal static void DecAddInt32(ref MutableDecimal value, uint i)
		{
			if (D32AddCarry(ref value.Low, i) && D32AddCarry(ref value.Mid, 1u))
			{
				D32AddCarry(ref value.High, 1u);
			}
		}

		private static bool D32AddCarry(ref uint value, uint i)
		{
			uint num = value;
			uint num2 = (value = num + i);
			if (num2 >= num)
			{
				return num2 < i;
			}
			return true;
		}

		internal static void DecMul10(ref MutableDecimal value)
		{
			MutableDecimal d = value;
			DecShiftLeft(ref value);
			DecShiftLeft(ref value);
			DecAdd(ref value, d);
			DecShiftLeft(ref value);
		}

		private static void DecShiftLeft(ref MutableDecimal value)
		{
			uint num = (((value.Low & 0x80000000u) != 0) ? 1u : 0u);
			uint num2 = (((value.Mid & 0x80000000u) != 0) ? 1u : 0u);
			value.Low <<= 1;
			value.Mid = (value.Mid << 1) | num;
			value.High = (value.High << 1) | num2;
		}

		private static void DecAdd(ref MutableDecimal value, MutableDecimal d)
		{
			if (D32AddCarry(ref value.Low, d.Low) && D32AddCarry(ref value.Mid, 1u))
			{
				D32AddCarry(ref value.High, 1u);
			}
			if (D32AddCarry(ref value.Mid, d.Mid))
			{
				D32AddCarry(ref value.High, 1u);
			}
			D32AddCarry(ref value.High, d.High);
		}
	}
	internal static class Number
	{
		private static class DoubleHelper
		{
			public unsafe static uint Exponent(double d)
			{
				return (*(uint*)((byte*)(&d) + 4) >> 20) & 0x7FFu;
			}

			public unsafe static ulong Mantissa(double d)
			{
				return *(uint*)(&d) | ((ulong)(uint)(*(int*)((byte*)(&d) + 4) & 0xFFFFF) << 32);
			}

			public unsafe static bool Sign(double d)
			{
				return *(uint*)((byte*)(&d) + 4) >> 31 != 0;
			}
		}

		internal const int DECIMAL_PRECISION = 29;

		private static readonly ulong[] s_rgval64Power10 = new ulong[30]
		{
			11529215046068469760uL, 14411518807585587200uL, 18014398509481984000uL, 11258999068426240000uL, 14073748835532800000uL, 17592186044416000000uL, 10995116277760000000uL, 13743895347200000000uL, 17179869184000000000uL, 10737418240000000000uL,
			13421772800000000000uL, 16777216000000000000uL, 10485760000000000000uL, 13107200000000000000uL, 16384000000000000000uL, 14757395258967641293uL, 11805916207174113035uL, 9444732965739290428uL, 15111572745182864686uL, 12089258196146291749uL,
			9671406556917033399uL, 15474250491067253438uL, 12379400392853802751uL, 9903520314283042201uL, 15845632502852867522uL, 12676506002282294018uL, 10141204801825835215uL, 16225927682921336344uL, 12980742146337069075uL, 10384593717069655260uL
		};

		private static readonly sbyte[] s_rgexp64Power10 = new sbyte[15]
		{
			4, 7, 10, 14, 17, 20, 24, 27, 30, 34,
			37, 40, 44, 47, 50
		};

		private static readonly ulong[] s_rgval64Power10By16 = new ulong[42]
		{
			10240000000000000000uL, 11368683772161602974uL, 12621774483536188886uL, 14012984643248170708uL, 15557538194652854266uL, 17272337110188889248uL, 9588073174409622172uL, 10644899600020376798uL, 11818212630765741798uL, 13120851772591970216uL,
			14567071740625403792uL, 16172698447808779622uL, 17955302187076837696uL, 9967194951097567532uL, 11065809325636130658uL, 12285516299433008778uL, 13639663065038175358uL, 15143067982934716296uL, 16812182738118149112uL, 9332636185032188787uL,
			10361307573072618722uL, 16615349947311448416uL, 14965776766268445891uL, 13479973333575319909uL, 12141680576410806707uL, 10936253623915059637uL, 9850501549098619819uL, 17745086042373215136uL, 15983352577617880260uL, 14396524142538228461uL,
			12967236152753103031uL, 11679847981112819795uL, 10520271803096747049uL, 9475818434452569218uL, 17070116948172427008uL, 15375394465392026135uL, 13848924157002783096uL, 12474001934591998882uL, 11235582092889474480uL, 10120112665365530972uL,
			18230774251475056952uL, 16420821625123739930uL
		};

		private static readonly short[] s_rgexp64Power10By16 = new short[21]
		{
			54, 107, 160, 213, 266, 319, 373, 426, 479, 532,
			585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064,
			1117
		};

		public static void RoundNumber(ref NumberBuffer number, int pos)
		{
			Span<byte> digits = number.Digits;
			int i;
			for (i = 0; i < pos && digits[i] != 0; i++)
			{
			}
			if (i == pos && digits[i] >= 53)
			{
				while (i > 0 && digits[i - 1] == 57)
				{
					i--;
				}
				if (i > 0)
				{
					digits[i - 1]++;
				}
				else
				{
					number.Scale++;
					digits[0] = 49;
					i = 1;
				}
			}
			else
			{
				while (i > 0 && digits[i - 1] == 48)
				{
					i--;
				}
			}
			if (i == 0)
			{
				number.Scale = 0;
				number.IsNegative = false;
			}
			digits[i] = 0;
		}

		internal static bool NumberBufferToDouble(ref NumberBuffer number, out double value)
		{
			double num = NumberToDouble(ref number);
			uint num2 = DoubleHelper.Exponent(num);
			ulong num3 = DoubleHelper.Mantissa(num);
			switch (num2)
			{
			case 2047u:
				value = 0.0;
				return false;
			case 0u:
				if (num3 == 0L)
				{
					num = 0.0;
				}
				break;
			}
			value = num;
			return true;
		}

		public unsafe static bool NumberBufferToDecimal(ref NumberBuffer number, ref decimal value)
		{
			MutableDecimal source = default(MutableDecimal);
			byte* ptr = number.UnsafeDigits;
			int num = number.Scale;
			if (*ptr == 0)
			{
				if (num > 0)
				{
					num = 0;
				}
			}
			else
			{
				if (num > 29)
				{
					return false;
				}
				while ((num > 0 || (*ptr != 0 && num > -28)) && (source.High < 429496729 || (source.High == 429496729 && (source.Mid < 2576980377u || (source.Mid == 2576980377u && (source.Low < 2576980377u || (source.Low == 2576980377u && *ptr <= 53)))))))
				{
					DecimalDecCalc.DecMul10(ref source);
					if (*ptr != 0)
					{
						DecimalDecCalc.DecAddInt32(ref source, (uint)(*(ptr++) - 48));
					}
					num--;
				}
				if (*(ptr++) >= 53)
				{
					bool flag = true;
					if (*(ptr - 1) == 53 && *(ptr - 2) % 2 == 0)
					{
						int num2 = 20;
						while (*ptr == 48 && num2 != 0)
						{
							ptr++;
							num2--;
						}
						if (*ptr == 0 || num2 == 0)
						{
							flag = false;
						}
					}
					if (flag)
					{
						DecimalDecCalc.DecAddInt32(ref source, 1u);
						if ((source.High | source.Mid | source.Low) == 0)
						{
							source.High = 429496729u;
							source.Mid = 2576980377u;
							source.Low = 2576980378u;
							num++;
						}
					}
				}
			}
			if (num > 0)
			{
				return false;
			}
			if (num <= -29)
			{
				source.High = 0u;
				source.Low = 0u;
				source.Mid = 0u;
				source.Scale = 28;
			}
			else
			{
				source.Scale = -num;
			}
			source.IsNegative = number.IsNegative;
			value = Unsafe.As<MutableDecimal, decimal>(ref source);
			return true;
		}

		public static void DecimalToNumber(decimal value, ref NumberBuffer number)
		{
			ref MutableDecimal reference = ref Unsafe.As<decimal, MutableDecimal>(ref value);
			Span<byte> digits = number.Digits;
			number.IsNegative = reference.IsNegative;
			int num = 29;
			while ((reference.Mid != 0) | (reference.High != 0))
			{
				uint num2 = DecimalDecCalc.DecDivMod1E9(ref reference);
				for (int i = 0; i < 9; i++)
				{
					digits[--num] = (byte)(num2 % 10 + 48);
					num2 /= 10;
				}
			}
			for (uint num3 = reference.Low; num3 != 0; num3 /= 10)
			{
				digits[--num] = (byte)(num3 % 10 + 48);
			}
			int num4 = 29 - num;
			number.Scale = num4 - reference.Scale;
			Span<byte> digits2 = number.Digits;
			int index = 0;
			while (--num4 >= 0)
			{
				digits2[index++] = digits[num++];
			}
			digits2[index] = 0;
		}

		private static uint DigitsToInt(ReadOnlySpan<byte> digits, int count)
		{
			uint value;
			int bytesConsumed;
			bool flag = Utf8Parser.TryParse(digits.Slice(0, count), out value, out bytesConsumed, 'D');
			return value;
		}

		private static ulong Mul32x32To64(uint a, uint b)
		{
			return (ulong)a * (ulong)b;
		}

		private static ulong Mul64Lossy(ulong a, ulong b, ref int pexp)
		{
			ulong num = Mul32x32To64((uint)(a >> 32), (uint)(b >> 32)) + (Mul32x32To64((uint)(a >> 32), (uint)b) >> 32) + (Mul32x32To64((uint)a, (uint)(b >> 32)) >> 32);
			if ((num & 0x8000000000000000uL) == 0L)
			{
				num <<= 1;
				pexp--;
			}
			return num;
		}

		private static int abs(int value)
		{
			if (value < 0)
			{
				return -value;
			}
			return value;
		}

		private unsafe static double NumberToDouble(ref NumberBuffer number)
		{
			ReadOnlySpan<byte> digits = number.Digits;
			int i = 0;
			int numDigits = number.NumDigits;
			int num = numDigits;
			for (; digits[i] == 48; i++)
			{
				num--;
			}
			if (num == 0)
			{
				return 0.0;
			}
			int num2 = Math.Min(num, 9);
			num -= num2;
			ulong num3 = DigitsToInt(digits, num2);
			if (num > 0)
			{
				num2 = Math.Min(num, 9);
				num -= num2;
				uint b = (uint)(s_rgval64Power10[num2 - 1] >> 64 - s_rgexp64Power10[num2 - 1]);
				num3 = Mul32x32To64((uint)num3, b) + DigitsToInt(digits.Slice(9), num2);
			}
			int num4 = number.Scale - (numDigits - num);
			int num5 = abs(num4);
			if (num5 >= 352)
			{
				ulong num6 = ((num4 > 0) ? 9218868437227405312uL : 0);
				if (number.IsNegative)
				{
					num6 |= 0x8000000000000000uL;
				}
				return *(double*)(&num6);
			}
			int pexp = 64;
			if ((num3 & 0xFFFFFFFF00000000uL) == 0L)
			{
				num3 <<= 32;
				pexp -= 32;
			}
			if ((num3 & 0xFFFF000000000000uL) == 0L)
			{
				num3 <<= 16;
				pexp -= 16;
			}
			if ((num3 & 0xFF00000000000000uL) == 0L)
			{
				num3 <<= 8;
				pexp -= 8;
			}
			if ((num3 & 0xF000000000000000uL) == 0L)
			{
				num3 <<= 4;
				pexp -= 4;
			}
			if ((num3 & 0xC000000000000000uL) == 0L)
			{
				num3 <<= 2;
				pexp -= 2;
			}
			if ((num3 & 0x8000000000000000uL) == 0L)
			{
				num3 <<= 1;
				pexp--;
			}
			int num7 = num5 & 0xF;
			if (num7 != 0)
			{
				int num8 = s_rgexp64Power10[num7 - 1];
				pexp += ((num4 < 0) ? (-num8 + 1) : num8);
				ulong b2 = s_rgval64Power10[num7 + ((num4 < 0) ? 15 : 0) - 1];
				num3 = Mul64Lossy(num3, b2, ref pexp);
			}
			num7 = num5 >> 4;
			if (num7 != 0)
			{
				int num9 = s_rgexp64Power10By16[num7 - 1];
				pexp += ((num4 < 0) ? (-num9 + 1) : num9);
				ulong b3 = s_rgval64Power10By16[num7 + ((num4 < 0) ? 21 : 0) - 1];
				num3 = Mul64Lossy(num3, b3, ref pexp);
			}
			if (((uint)(int)num3 & 0x400u) != 0)
			{
				ulong num10 = num3 + 1023 + (ulong)(((int)num3 >> 11) & 1);
				if (num10 < num3)
				{
					num10 = (num10 >> 1) | 0x8000000000000000uL;
					pexp++;
				}
				num3 = num10;
			}
			pexp += 1022;
			num3 = ((pexp <= 0) ? ((pexp == -52 && num3 >= 9223372036854775896uL) ? 1 : ((pexp > -52) ? (num3 >> -pexp + 11 + 1) : 0)) : ((pexp < 2047) ? ((ulong)((long)pexp << 52) + ((num3 >> 11) & 0xFFFFFFFFFFFFFL)) : 9218868437227405312uL));
			if (number.IsNegative)
			{
				num3 |= 0x8000000000000000uL;
			}
			return *(double*)(&num3);
		}
	}
	internal ref struct NumberBuffer
	{
		public int Scale;

		public bool IsNegative;

		public const int BufferSize = 51;

		private byte _b0;

		private byte _b1;

		private byte _b2;

		private byte _b3;

		private byte _b4;

		private byte _b5;

		private byte _b6;

		private byte _b7;

		private byte _b8;

		private byte _b9;

		private byte _b10;

		private byte _b11;

		private byte _b12;

		private byte _b13;

		private byte _b14;

		private byte _b15;

		private byte _b16;

		private byte _b17;

		private byte _b18;

		private byte _b19;

		private byte _b20;

		private byte _b21;

		private byte _b22;

		private byte _b23;

		private byte _b24;

		private byte _b25;

		private byte _b26;

		private byte _b27;

		private byte _b28;

		private byte _b29;

		private byte _b30;

		private byte _b31;

		private byte _b32;

		private byte _b33;

		private byte _b34;

		private byte _b35;

		private byte _b36;

		private byte _b37;

		private byte _b38;

		private byte _b39;

		private byte _b40;

		private byte _b41;

		private byte _b42;

		private byte _b43;

		private byte _b44;

		private byte _b45;

		private byte _b46;

		private byte _b47;

		private byte _b48;

		private byte _b49;

		private byte _b50;

		public unsafe Span<byte> Digits => new Span<byte>(Unsafe.AsPointer(ref _b0), 51);

		public unsafe byte* UnsafeDigits => (byte*)Unsafe.AsPointer(ref _b0);

		public int NumDigits => Digits.IndexOf<byte>(0);

		[Conditional("DEBUG")]
		public void CheckConsistency()
		{
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append('[');
			stringBuilder.Append('"');
			Span<byte> digits = Digits;
			for (int i = 0; i < 51; i++)
			{
				byte b = digits[i];
				if (b == 0)
				{
					break;
				}
				stringBuilder.Append((char)b);
			}
			stringBuilder.Append('"');
			stringBuilder.Append(", Scale = " + Scale);
			stringBuilder.Append(", IsNegative   = " + IsNegative);
			stringBuilder.Append(']');
			return stringBuilder.ToString();
		}
	}
	[DebuggerTypeProxy(typeof(System.MemoryDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly struct Memory<T>
	{
		private readonly object _object;

		private readonly int _index;

		private readonly int _length;

		private const int RemoveFlagsBitMask = int.MaxValue;

		public static Memory<T> Empty => default(Memory<T>);

		public int Length => _length & 0x7FFFFFFF;

		public bool IsEmpty => (_length & 0x7FFFFFFF) == 0;

		public Span<T> Span
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				Span<T> result;
				if (_index < 0)
				{
					result = ((MemoryManager<T>)_object).GetSpan();
					return result.Slice(_index & 0x7FFFFFFF, _length);
				}
				if (typeof(T) == typeof(char) && _object is string text)
				{
					result = new Span<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length);
					return result.Slice(_index, _length);
				}
				if (_object != null)
				{
					return new Span<T>((T[])_object, _index, _length & 0x7FFFFFFF);
				}
				result = default(Span<T>);
				return result;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory(T[] array)
		{
			if (array == null)
			{
				this = default(Memory<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			_object = array;
			_index = 0;
			_length = array.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(T[] array, int start)
		{
			if (array == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException();
				}
				this = default(Memory<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = array;
			_index = start;
			_length = array.Length - start;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException();
				}
				this = default(Memory<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = array;
			_index = start;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(MemoryManager<T> manager, int length)
		{
			if (length < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = manager;
			_index = int.MinValue;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(MemoryManager<T> manager, int start, int length)
		{
			if (length < 0 || start < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = manager;
			_index = start | int.MinValue;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(object obj, int start, int length)
		{
			_object = obj;
			_index = start;
			_length = length;
		}

		public static implicit operator Memory<T>(T[] array)
		{
			return new Memory<T>(array);
		}

		public static implicit operator Memory<T>(ArraySegment<T> segment)
		{
			return new Memory<T>(segment.Array, segment.Offset, segment.Count);
		}

		public static implicit operator ReadOnlyMemory<T>(Memory<T> memory)
		{
			return Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
		}

		public override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (!(_object is string text))
				{
					return Span.ToString();
				}
				return text.Substring(_index, _length & 0x7FFFFFFF);
			}
			return $"System.Memory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory<T> Slice(int start)
		{
			int length = _length;
			int num = length & 0x7FFFFFFF;
			if ((uint)start > (uint)num)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new Memory<T>(_object, _index + start, length - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory<T> Slice(int start, int length)
		{
			int length2 = _length;
			int num = length2 & 0x7FFFFFFF;
			if ((uint)start > (uint)num || (uint)length > (uint)(num - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			return new Memory<T>(_object, _index + start, length | (length2 & int.MinValue));
		}

		public void CopyTo(Memory<T> destination)
		{
			Span.CopyTo(destination.Span);
		}

		public bool TryCopyTo(Memory<T> destination)
		{
			return Span.TryCopyTo(destination.Span);
		}

		public unsafe MemoryHandle Pin()
		{
			if (_index < 0)
			{
				return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF);
			}
			if (typeof(T) == typeof(char) && _object is string value)
			{
				GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned);
				void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer, handle);
			}
			if (_object is T[] array)
			{
				if (_length < 0)
				{
					void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index);
					return new MemoryHandle(pointer2);
				}
				GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned);
				void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer3, handle2);
			}
			return default(MemoryHandle);
		}

		public T[] ToArray()
		{
			return Span.ToArray();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			if (obj is ReadOnlyMemory<T> readOnlyMemory)
			{
				return readOnlyMemory.Equals(this);
			}
			if (obj is Memory<T> other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(Memory<T> other)
		{
			if (_object == other._object && _index == other._index)
			{
				return _length == other._length;
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			if (_object == null)
			{
				return 0;
			}
			int hashCode = _object.GetHashCode();
			int index = _index;
			int hashCode2 = index.GetHashCode();
			index = _length;
			return CombineHashCodes(hashCode, hashCode2, index.GetHashCode());
		}

		private static int CombineHashCodes(int left, int right)
		{
			return ((left << 5) + left) ^ right;
		}

		private static int CombineHashCodes(int h1, int h2, int h3)
		{
			return CombineHashCodes(CombineHashCodes(h1, h2), h3);
		}
	}
	internal sealed class MemoryDebugView<T>
	{
		private readonly ReadOnlyMemory<T> _memory;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public T[] Items => _memory.ToArray();

		public MemoryDebugView(Memory<T> memory)
		{
			_memory = memory;
		}

		public MemoryDebugView(ReadOnlyMemory<T> memory)
		{
			_memory = memory;
		}
	}
	public static class MemoryExtensions
	{
		internal static readonly IntPtr StringAdjustment = MeasureStringAdjustment();

		public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span)
		{
			return span.TrimStart().TrimEnd();
		}

		public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span)
		{
			int i;
			for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++)
			{
			}
			return span.Slice(i);
		}

		public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span)
		{
			int num = span.Length - 1;
			while (num >= 0 && char.IsWhiteSpace(span[num]))
			{
				num--;
			}
			return span.Slice(0, num + 1);
		}

		public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, char trimChar)
		{
			return span.TrimStart(trimChar).TrimEnd(trimChar);
		}

		public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, char trimChar)
		{
			int i;
			for (i = 0; i < span.Length && span[i] == trimChar; i++)
			{
			}
			return span.Slice(i);
		}

		public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, char trimChar)
		{
			int num = span.Length - 1;
			while (num >= 0 && span[num] == trimChar)
			{
				num--;
			}
			return span.Slice(0, num + 1);
		}

		public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars)
		{
			return span.TrimStart(trimChars).TrimEnd(trimChars);
		}

		public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars)
		{
			if (trimChars.IsEmpty)
			{
				return span.TrimStart();
			}
			int i;
			for (i = 0; i < span.Length; i++)
			{
				int num = 0;
				while (num < trimChars.Length)
				{
					if (span[i] != trimChars[num])
					{
						num++;
						continue;
					}
					goto IL_003c;
				}
				break;
				IL_003c:;
			}
			return span.Slice(i);
		}

		public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars)
		{
			if (trimChars.IsEmpty)
			{
				return span.TrimEnd();
			}
			int num;
			for (num = span.Length - 1; num >= 0; num--)
			{
				int num2 = 0;
				while (num2 < trimChars.Length)
				{
					if (span[num] != trimChars[num2])
					{
						num2++;
						continue;
					}
					goto IL_0044;
				}
				break;
				IL_0044:;
			}
			return span.Slice(0, num + 1);
		}

		public static bool IsWhiteSpace(this ReadOnlySpan<char> span)
		{
			for (int i = 0; i < span.Length; i++)
			{
				if (!char.IsWhiteSpace(span[i]))
				{
					return false;
				}
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this Span<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this Span<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool SequenceEqual<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IEquatable<T>
		{
			int length = span.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length == other.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size);
				}
				return false;
			}
			if (length == other.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length);
			}
			return false;
		}

		public static int SequenceCompareTo<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IComparable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool SequenceEqual<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IEquatable<T>
		{
			int length = span.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length == other.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size);
				}
				return false;
			}
			if (length == other.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int SequenceCompareTo<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IComparable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length <= span.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size);
				}
				return false;
			}
			if (length <= span.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length <= span.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size);
				}
				return false;
			}
			if (length <= span.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool EndsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = span.Length;
			int length2 = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length2 <= length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size);
				}
				return false;
			}
			if (length2 <= length)
			{
				return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool EndsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = span.Length;
			int length2 = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length2 <= length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size);
				}
				return false;
			}
			if (length2 <= length)
			{
				return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2);
			}
			return false;
		}

		public static void Reverse<T>(this Span<T> span)
		{
			ref T reference = ref MemoryMarshal.GetReference(span);
			int num = 0;
			int num2 = span.Length - 1;
			while (num < num2)
			{
				T val = Unsafe.Add(ref reference, num);
				Unsafe.Add(ref reference, num) = Unsafe.Add(ref reference, num2);
				Unsafe.Add(ref reference, num2) = val;
				num++;
				num2--;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this T[] array)
		{
			return new Span<T>(array);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this T[] array, int start, int length)
		{
			return new Span<T>(array, start, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this ArraySegment<T> segment)
		{
			return new Span<T>(segment.Array, segment.Offset, segment.Count);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new Span<T>(segment.Array, segment.Offset + start, segment.Count - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start, int length)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			if ((uint)length > segment.Count - start)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length);
			}
			return new Span<T>(segment.Array, segment.Offset + start, length);
		}

		public static Memory<T> AsMemory<T>(this T[] array)
		{
			return new Memory<T>(array);
		}

		public static Memory<T> AsMemory<T>(this T[] array, int start)
		{
			return new Memory<T>(array, start);
		}

		public static Memory<T> AsMemory<T>(this T[] array, int start, int length)
		{
			return new Memory<T>(array, start, length);
		}

		public static Memory<T> AsMemory<T>(this ArraySegment<T> segment)
		{
			return new Memory<T>(segment.Array, segment.Offset, segment.Count);
		}

		public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new Memory<T>(segment.Array, segment.Offset + start, segment.Count - start);
		}

		public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start, int length)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			if ((uint)length > segment.Count - start)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length);
			}
			return new Memory<T>(segment.Array, segment.Offset + start, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void CopyTo<T>(this T[] source, Span<T> destination)
		{
			new ReadOnlySpan<T>(source).CopyTo(destination);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void CopyTo<T>(this T[] source, Memory<T> destination)
		{
			source.CopyTo(destination.Span);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other)
		{
			return ((ReadOnlySpan<T>)span).Overlaps(other);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other, out int elementOffset)
		{
			return ((ReadOnlySpan<T>)span).Overlaps(other, out elementOffset);
		}

		public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other)
		{
			if (span.IsEmpty || other.IsEmpty)
			{
				return false;
			}
			IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other));
			if (Unsafe.SizeOf<IntPtr>() == 4)
			{
				if ((uint)(int)intPtr >= (uint)(span.Length * Unsafe.SizeOf<T>()))
				{
					return (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>()));
				}
				return true;
			}
			if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()))
			{
				return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>()));
			}
			return true;
		}

		public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other, out int elementOffset)
		{
			if (span.IsEmpty || other.IsEmpty)
			{
				elementOffset = 0;
				return false;
			}
			IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other));
			if (Unsafe.SizeOf<IntPtr>() == 4)
			{
				if ((uint)(int)intPtr < (uint)(span.Length * Unsafe.SizeOf<T>()) || (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>())))
				{
					if ((int)intPtr % Unsafe.SizeOf<T>() != 0)
					{
						System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch();
					}
					elementOffset = (int)intPtr / Unsafe.SizeOf<T>();
					return true;
				}
				elementOffset = 0;
				return false;
			}
			if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>())))
			{
				if ((long)intPtr % Unsafe.SizeOf<T>() != 0L)
				{
					System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch();
				}
				elementOffset = (int)((long)intPtr / Unsafe.SizeOf<T>());
				return true;
			}
			elementOffset = 0;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T>(this Span<T> span, IComparable<T> comparable)
		{
			return span.BinarySearch<T, IComparable<T>>(comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparable>(this Span<T> span, TComparable comparable) where TComparable : IComparable<T>
		{
			return BinarySearch((ReadOnlySpan<T>)span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparer>(this Span<T> span, T value, TComparer comparer) where TComparer : IComparer<T>
		{
			return ((ReadOnlySpan<T>)span).BinarySearch(value, comparer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T>(this ReadOnlySpan<T> span, IComparable<T> comparable)
		{
			return MemoryExtensions.BinarySearch<T, IComparable<T>>(span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T>
		{
			return System.SpanHelpers.BinarySearch(span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparer>(this ReadOnlySpan<T> span, T value, TComparer comparer) where TComparer : IComparer<T>
		{
			if (comparer == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparer);
			}
			System.SpanHelpers.ComparerComparable<T, TComparer> comparable = new System.SpanHelpers.ComparerComparable<T, TComparer>(value, comparer);
			return BinarySearch(span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static bool IsTypeComparableAsBytes<T>(out NUInt size)
		{
			if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte))
			{
				size = (NUInt)1;
				return true;
			}
			if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort))
			{
				size = (NUInt)2;
				return true;
			}
			if (typeof(T) == typeof(int) || typeof(T) == typeof(uint))
			{
				size = (NUInt)4;
				return true;
			}
			if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong))
			{
				size = (NUInt)8;
				return true;
			}
			size = default(NUInt);
			return false;
		}

		public static Span<T> AsSpan<T>(this T[] array, int start)
		{
			return Span<T>.Create(array, start);
		}

		public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			return span.IndexOf(value, comparisonType) >= 0;
		}

		public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
		{
			switch (comparisonType)
			{
			case StringComparison.Ordinal:
				return span.SequenceEqual(other);
			case StringComparison.OrdinalIgnoreCase:
				if (span.Length != other.Length)
				{
					return false;
				}
				return EqualsOrdinalIgnoreCase(span, other);
			default:
				return span.ToString().Equals(other.ToString(), comparisonType);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static bool EqualsOrdinalIgnoreCase(ReadOnlySpan<char> span, ReadOnlySpan<char> other)
		{
			if (other.Length == 0)
			{
				return true;
			}
			return CompareToOrdinalIgnoreCase(span, other) == 0;
		}

		public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
		{
			return comparisonType switch
			{
				StringComparison.Ordinal => span.SequenceCompareTo(other), 
				StringComparison.OrdinalIgnoreCase => CompareToOrdinalIgnoreCase(span, other), 
				_ => string.Compare(span.ToString(), other.ToString(), comparisonType), 
			};
		}

		private unsafe static int CompareToOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
		{
			int num = Math.Min(strA.Length, strB.Length);
			int num2 = num;
			fixed (char* ptr = &MemoryMarshal.GetReference(strA))
			{
				fixed (char* ptr3 = &MemoryMarshal.GetReference(strB))
				{
					char* ptr2 = ptr;
					char* ptr4 = ptr3;
					while (num != 0 && *ptr2 <= '\u007f' && *ptr4 <= '\u007f')
					{
						int num3 = *ptr2;
						int num4 = *ptr4;
						if (num3 == num4)
						{
							ptr2++;
							ptr4++;
							num--;
							continue;
						}
						if ((uint)(num3 - 97) <= 25u)
						{
							num3 -= 32;
						}
						if ((uint)(num4 - 97) <= 25u)
						{
							num4 -= 32;
						}
						if (num3 != num4)
						{
							return num3 - num4;
						}
						ptr2++;
						ptr4++;
						num--;
					}
					if (num == 0)
					{
						return strA.Length - strB.Length;
					}
					num2 -= num;
					return string.Compare(strA.Slice(num2).ToString(), strB.Slice(num2).ToString(), StringComparison.OrdinalIgnoreCase);
				}
			}
		}

		public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			if (comparisonType == StringComparison.Ordinal)
			{
				return span.IndexOf(value);
			}
			return span.ToString().IndexOf(value.ToString(), comparisonType);
		}

		public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
		{
			if (culture == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture);
			}
			if (destination.Length < source.Length)
			{
				return -1;
			}
			string text = source.ToString();
			string text2 = text.ToLower(culture);
			AsSpan(text2).CopyTo(destination);
			return source.Length;
		}

		public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination)
		{
			return source.ToLower(destination, CultureInfo.InvariantCulture);
		}

		public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
		{
			if (culture == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture);
			}
			if (destination.Length < source.Length)
			{
				return -1;
			}
			string text = source.ToString();
			string text2 = text.ToUpper(culture);
			AsSpan(text2).CopyTo(destination);
			return source.Length;
		}

		public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination)
		{
			return source.ToUpper(destination, CultureInfo.InvariantCulture);
		}

		public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			switch (comparisonType)
			{
			case StringComparison.Ordinal:
				return span.EndsWith(value);
			case StringComparison.OrdinalIgnoreCase:
				if (value.Length <= span.Length)
				{
					return EqualsOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value);
				}
				return false;
			default:
			{
				string text = span.ToString();
				string value2 = value.ToString();
				return text.EndsWith(value2, comparisonType);
			}
			}
		}

		public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			switch (comparisonType)
			{
			case StringComparison.Ordinal:
				return span.StartsWith(value);
			case StringComparison.OrdinalIgnoreCase:
				if (value.Length <= span.Length)
				{
					return EqualsOrdinalIgnoreCase(span.Slice(0, value.Length), value);
				}
				return false;
			default:
			{
				string text = span.ToString();
				string value2 = value.ToString();
				return text.StartsWith(value2, comparisonType);
			}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ReadOnlySpan<char> AsSpan(this string text)
		{
			if (text == null)
			{
				return default(ReadOnlySpan<char>);
			}
			return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment, text.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ReadOnlySpan<char> AsSpan(this string text, int start)
		{
			if (text == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlySpan<char>);
			}
			if ((uint)start > (uint)text.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, text.Length - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ReadOnlySpan<char> AsSpan(this string text, int start, int length)
		{
			if (text == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlySpan<char>);
			}
			if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, length);
		}

		public static ReadOnlyMemory<char> AsMemory(this string text)
		{
			if (text == null)
			{
				return default(ReadOnlyMemory<char>);
			}
			return new ReadOnlyMemory<char>(text, 0, text.Length);
		}

		public static ReadOnlyMemory<char> AsMemory(this string text, int start)
		{
			if (text == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlyMemory<char>);
			}
			if ((uint)start > (uint)text.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<char>(text, start, text.Length - start);
		}

		public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length)
		{
			if (text == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlyMemory<char>);
			}
			if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<char>(text, start, length);
		}

		private unsafe static IntPtr MeasureStringAdjustment()
		{
			string text = "a";
			fixed (char* source = text)
			{
				return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<char>>(text).Data, ref Unsafe.AsRef<char>(source));
			}
		}
	}
	[DebuggerTypeProxy(typeof(System.MemoryDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly struct ReadOnlyMemory<T>
	{
		private readonly object _object;

		private readonly int _index;

		private readonly int _length;

		internal const int RemoveFlagsBitMask = int.MaxValue;

		public static ReadOnlyMemory<T> Empty => default(ReadOnlyMemory<T>);

		public int Length => _length & 0x7FFFFFFF;

		public bool IsEmpty => (_length & 0x7FFFFFFF) == 0;

		public ReadOnlySpan<T> Span
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if (_index < 0)
				{
					return ((MemoryManager<T>)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length);
				}
				ReadOnlySpan<T> result;
				if (typeof(T) == typeof(char) && _object is string text)
				{
					result = new ReadOnlySpan<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length);
					return result.Slice(_index, _length);
				}
				if (_object != null)
				{
					return new ReadOnlySpan<T>((T[])_object, _index, _length & 0x7FFFFFFF);
				}
				result = default(ReadOnlySpan<T>);
				return result;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory(T[] array)
		{
			if (array == null)
			{
				this = default(ReadOnlyMemory<T>);
				return;
			}
			_object = array;
			_index = 0;
			_length = array.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException();
				}
				this = default(ReadOnlyMemory<T>);
				return;
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = array;
			_index = start;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ReadOnlyMemory(object obj, int start, int length)
		{
			_object = obj;
			_index = start;
			_length = length;
		}

		public static implicit operator ReadOnlyMemory<T>(T[] array)
		{
			return new ReadOnlyMemory<T>(array);
		}

		public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment)
		{
			return new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count);
		}

		public override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (!(_object is string text))
				{
					return Span.ToString();
				}
				return text.Substring(_index, _length & 0x7FFFFFFF);
			}
			return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory<T> Slice(int start)
		{
			int length = _length;
			int num = length & 0x7FFFFFFF;
			if ((uint)start > (uint)num)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<T>(_object, _index + start, length - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory<T> Slice(int start, int length)
		{
			int length2 = _length;
			int num = _length & 0x7FFFFFFF;
			if ((uint)start > (uint)num || (uint)length > (uint)(num - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<T>(_object, _index + start, length | (length2 & int.MinValue));
		}

		public void CopyTo(Memory<T> destination)
		{
			Span.CopyTo(destination.Span);
		}

		public bool TryCopyTo(Memory<T> destination)
		{
			return Span.TryCopyTo(destination.Span);
		}

		public unsafe MemoryHandle Pin()
		{
			if (_index < 0)
			{
				return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF);
			}
			if (typeof(T) == typeof(char) && _object is string value)
			{
				GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned);
				void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer, handle);
			}
			if (_object is T[] array)
			{
				if (_length < 0)
				{
					void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index);
					return new MemoryHandle(pointer2);
				}
				GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned);
				void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer3, handle2);
			}
			return default(MemoryHandle);
		}

		public T[] ToArray()
		{
			return Span.ToArray();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			if (obj is ReadOnlyMemory<T> other)
			{
				return Equals(other);
			}
			if (obj is Memory<T> memory)
			{
				return Equals(memory);
			}
			return false;
		}

		public bool Equals(ReadOnlyMemory<T> other)
		{
			if (_object == other._object && _index == other._index)
			{
				return _length == other._length;
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			if (_object == null)
			{
				return 0;
			}
			int hashCode = _object.GetHashCode();
			int index = _index;
			int hashCode2 = index.GetHashCode();
			index = _length;
			return CombineHashCodes(hashCode, hashCode2, index.GetHashCode());
		}

		private static int CombineHashCodes(int left, int right)
		{
			return ((left << 5) + left) ^ right;
		}

		private static int CombineHashCodes(int h1, int h2, int h3)
		{
			return CombineHashCodes(CombineHashCodes(h1, h2), h3);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal object GetObjectStartLength(out int start, out int length)
		{
			start = _index;
			length = _length;
			return _object;
		}
	}
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly ref struct ReadOnlySpan<T>
	{
		public ref struct Enumerator
		{
			private readonly ReadOnlySpan<T> _span;

			private int _index;

			public ref readonly T Current
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return ref _span[_index];
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal Enumerator(ReadOnlySpan<T> span)
			{
				_span = span;
				_index = -1;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public bool MoveNext()
			{
				int num = _index + 1;
				if (num < _span.Length)
				{
					_index = num;
					return true;
				}
				return false;
			}
		}

		private readonly Pinnable<T> _pinnable;

		private readonly IntPtr _byteOffset;

		private readonly int _length;

		public int Length => _length;

		public bool IsEmpty => _length == 0;

		public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);

		public unsafe ref readonly T this[int index]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if ((uint)index >= (uint)_length)
				{
					System.ThrowHelper.ThrowIndexOutOfRangeException();
				}
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index);
				}
				return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index);
			}
		}

		internal Pinnable<T> Pinnable => _pinnable;

		internal IntPtr ByteOffset => _byteOffset;

		public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
		{
			return !(left == right);
		}

		[Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan);
		}

		[Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan);
		}

		public static implicit operator ReadOnlySpan<T>(T[] array)
		{
			return new ReadOnlySpan<T>(array);
		}

		public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment)
		{
			return new ReadOnlySpan<T>(segment.Array, segment.Offset, segment.Count);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan(T[] array)
		{
			if (array == null)
			{
				this = default(ReadOnlySpan<T>);
				return;
			}
			_length = array.Length;
			_pinnable = Unsafe.As<Pinnable<T>>(array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				this = default(ReadOnlySpan<T>);
				return;
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = Unsafe.As<Pinnable<T>>(array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public unsafe ReadOnlySpan(void* pointer, int length)
		{
			if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
			}
			if (length < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = null;
			_byteOffset = new IntPtr(pointer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ReadOnlySpan(Pinnable<T> pinnable, IntPtr byteOffset, int length)
		{
			_length = length;
			_pinnable = pinnable;
			_byteOffset = byteOffset;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public unsafe ref readonly T GetPinnableReference()
		{
			if (_length != 0)
			{
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref Unsafe.AsRef<T>(byteOffset.ToPointer());
				}
				return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
			}
			return ref Unsafe.AsRef<T>(null);
		}

		public void CopyTo(Span<T> destination)
		{
			if (!TryCopyTo(destination))
			{
				System.ThrowHelper.ThrowArgumentException_DestinationTooShort();
			}
		}

		public bool TryCopyTo(Span<T> destination)
		{
			int length = _length;
			int length2 = destination.Length;
			if (length == 0)
			{
				return true;
			}
			if ((uint)length > (uint)length2)
			{
				return false;
			}
			ref T src = ref DangerousGetPinnableReference();
			System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length);
			return true;
		}

		public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
		{
			if (left._length == right._length)
			{
				return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
			}
			return false;
		}

		public unsafe override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (_byteOffset == MemoryExtensions.StringAdjustment)
				{
					object obj = Unsafe.As<object>(_pinnable);
					if (obj is string text && _length == text.Length)
					{
						return text;
					}
				}
				fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference()))
				{
					return new string(value, 0, _length);
				}
			}
			return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan<T> Slice(int start)
		{
			if ((uint)start > (uint)_length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			int length = _length - start;
			return new ReadOnlySpan<T>(_pinnable, byteOffset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan<T> Slice(int start, int length)
		{
			if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			return new ReadOnlySpan<T>(_pinnable, byteOffset, length);
		}

		public T[] ToArray()
		{
			if (_length == 0)
			{
				return System.SpanHelpers.PerTypeValues<T>.EmptyArray;
			}
			T[] array = new T[_length];
			CopyTo(array);
			return array;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		internal unsafe ref T DangerousGetPinnableReference()
		{
			if (_pinnable == null)
			{
				IntPtr byteOffset = _byteOffset;
				return ref Unsafe.AsRef<T>(byteOffset.ToPointer());
			}
			return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
		}
	}
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly ref struct Span<T>
	{
		public ref struct Enumerator
		{
			private readonly Span<T> _span;

			private int _index;

			public ref T Current
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return ref _span[_index];
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal Enumerator(Span<T> span)
			{
				_span = span;
				_index = -1;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public bool MoveNext()
			{
				int num = _index + 1;
				if (num < _span.Length)
				{
					_index = num;
					return true;
				}
				return false;
			}
		}

		private readonly Pinnable<T> _pinnable;

		private readonly IntPtr _byteOffset;

		private readonly int _length;

		public int Length => _length;

		public bool IsEmpty => _length == 0;

		public static Span<T> Empty => default(Span<T>);

		public unsafe ref T this[int index]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if ((uint)index >= (uint)_length)
				{
					System.ThrowHelper.ThrowIndexOutOfRangeException();
				}
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index);
				}
				return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index);
			}
		}

		internal Pinnable<T> Pinnable => _pinnable;

		internal IntPtr ByteOffset => _byteOffset;

		public static bool operator !=(Span<T> left, Span<T> right)
		{
			return !(left == right);
		}

		[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan);
		}

		[Obsolete("GetHashCode() on Span will always throw an exception.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan);
		}

		public static implicit operator Span<T>(T[] array)
		{
			return new Span<T>(array);
		}

		public static implicit operator Span<T>(ArraySegment<T> segment)
		{
			return new Span<T>(segment.Array, segment.Offset, segment.Count);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span(T[] array)
		{
			if (array == null)
			{
				this = default(Span<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			_length = array.Length;
			_pinnable = Unsafe.As<Pinnable<T>>(array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static Span<T> Create(T[] array, int start)
		{
			if (array == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(Span<T>);
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
			int length = array.Length - start;
			return new Span<T>(Unsafe.As<Pinnable<T>>(array), byteOffset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				this = default(Span<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = Unsafe.As<Pinnable<T>>(array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public unsafe Span(void* pointer, int length)
		{
			if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
			}
			if (length < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = null;
			_byteOffset = new IntPtr(pointer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length)
		{
			_length = length;
			_pinnable = pinnable;
			_byteOffset = byteOffset;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public unsafe ref T GetPinnableReference()
		{
			if (_length != 0)
			{
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref Unsafe.AsRef<T>(byteOffset.ToPointer());
				}
				return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
			}
			return ref Unsafe.AsRef<T>(null);
		}

		public unsafe void Clear()
		{
			int length = _length;
			if (length == 0)
			{
				return;
			}
			UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * Unsafe.SizeOf<T>());
			if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0)
			{
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					byte* ptr = (byte*)byteOffset.ToPointer();
					System.SpanHelpers.ClearLessThanPointerSized(ptr, byteLength);
				}
				else
				{
					System.SpanHelpers.ClearLessThanPointerSized(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), byteLength);
				}
			}
			else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * Unsafe.SizeOf<T>() / sizeof(IntPtr));
				System.SpanHelpers.ClearPointerSizedWithReferences(ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength);
			}
			else
			{
				System.SpanHelpers.ClearPointerSizedWithoutReferences(ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength);
			}
		}

		public unsafe void Fill(T value)
		{
			int length = _length;
			if (length == 0)
			{
				return;
			}
			if (Unsafe.SizeOf<T>() == 1)
			{
				byte value2 = Unsafe.As<T, byte>(ref value);
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), value2, (uint)length);
				}
				else
				{
					Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), value2, (uint)length);
				}
				return;
			}
			ref T source = ref DangerousGetPinnableReference();
			int i;
			for (i = 0; i < (length & -8); i += 8)
			{
				Unsafe.Add(ref source, i) = value;
				Unsafe.Add(ref source, i + 1) = value;
				Unsafe.Add(ref source, i + 2) = value;
				Unsafe.Add(ref source, i + 3) = value;
				Unsafe.Add(ref source, i + 4) = value;
				Unsafe.Add(ref source, i + 5) = value;
				Unsafe.Add(ref source, i + 6) = value;
				Unsafe.Add(ref source, i + 7) = value;
			}
			if (i < (length & -4))
			{
				Unsafe.Add(ref source, i) = value;
				Unsafe.Add(ref source, i + 1) = value;
				Unsafe.Add(ref source, i + 2) = value;
				Unsafe.Add(ref source, i + 3) = value;
				i += 4;
			}
			for (; i < length; i++)
			{
				Unsafe.Add(ref source, i) = value;
			}
		}

		public void CopyTo(Span<T> destination)
		{
			if (!TryCopyTo(destination))
			{
				System.ThrowHelper.ThrowArgumentException_DestinationTooShort();
			}
		}

		public bool TryCopyTo(Span<T> destination)
		{
			int length = _length;
			int length2 = destination._length;
			if (length == 0)
			{
				return true;
			}
			if ((uint)length > (uint)length2)
			{
				return false;
			}
			ref T src = ref DangerousGetPinnableReference();
			System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length);
			return true;
		}

		public static bool operator ==(Span<T> left, Span<T> right)
		{
			if (left._length == right._length)
			{
				return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
			}
			return false;
		}

		public static implicit operator ReadOnlySpan<T>(Span<T> span)
		{
			return new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length);
		}

		public unsafe override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference()))
				{
					return new string(value, 0, _length);
				}
			}
			return $"System.Span<{typeof(T).Name}>[{_length}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<T> Slice(int start)
		{
			if ((uint)start > (uint)_length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			int length = _length - start;
			return new Span<T>(_pinnable, byteOffset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<T> Slice(int start, int length)
		{
			if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			return new Span<T>(_pinnable, byteOffset, length);
		}

		public T[] ToArray()
		{
			if (_length == 0)
			{
				return System.SpanHelpers.PerTypeValues<T>.EmptyArray;
			}
			T[] array = new T[_length];
			CopyTo(array);
			return array;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		internal unsafe ref T DangerousGetPinnableReference()
		{
			if (_pinnable == null)
			{
				IntPtr byteOffset = _byteOffset;
				return ref Unsafe.AsRef<T>(byteOffset.ToPointer());
			}
			return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
		}
	}
	internal sealed class SpanDebugView<T>
	{
		private readonly T[] _array;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public T[] Items => _array;

		public SpanDebugView(Span<T> span)
		{
			_array = span.ToArray();
		}

		public SpanDebugView(ReadOnlySpan<T> span)
		{
			_array = span.ToArray();
		}
	}
	internal static class SpanHelpers
	{
		internal struct ComparerComparable<T, TComparer> : IComparable<T> where TComparer : IComparer<T>
		{
			private readonly T _value;

			private readonly TComparer _comparer;

			public ComparerComparable(T value, TComparer comparer)
			{
				_value = value;
				_comparer = comparer;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int CompareTo(T other)
			{
				return _comparer.Compare(_value, other);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 64)]
		private struct Reg64
		{
		}

		[StructLayout(LayoutKind.Sequential, Size = 32)]
		private struct Reg32
		{
		}

		[StructLayout(LayoutKind.Sequential, Size = 16)]
		private struct Reg16
		{
		}

		public static class PerTypeValues<T>
		{
			public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferencesCore(typeof(T));

			public static readonly T[] EmptyArray = new T[0];

			public static readonly IntPtr ArrayAdjustment = MeasureArrayAdjustment();

			private static IntPtr MeasureArrayAdjustment()
			{
				T[] array = new T[1];
				return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<T>>(array).Data, ref array[0]);
			}
		}

		private const ulong XorPowerOfTwoToHighByte = 283686952306184uL;

		private const ulong XorPowerOfTwoToHighChar = 4295098372uL;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T>
		{
			if (comparable == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparable);
			}
			return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable);
		}

		public static int BinarySearch<T, TComparable>(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable<T>
		{
			int num = 0;
			int num2 = length - 1;
			while (num <= num2)
			{
				int num3 = num2 + num >>> 1;
				int num4 = comparable.CompareTo(Unsafe.Add(ref spanStart, num3));
				if (num4 == 0)
				{
					return num3;
				}
				if (num4 > 0)
				{
					num = num3 + 1;
				}
				else
				{
					num2 = num3 - 1;
				}
			}
			return ~num;
		}

		public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			byte value2 = value;
			ref byte second = ref Unsafe.Add(ref value, 1);
			int num = valueLength - 1;
			int num2 = 0;
			while (true)
			{
				int num3 = searchSpaceLength - num2 - num;
				if (num3 <= 0)
				{
					break;
				}
				int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num2), value2, num3);
				if (num4 == -1)
				{
					break;
				}
				num2 += num4;
				if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num2 + 1), ref second, num))
				{
					return num2;
				}
				num2++;
			}
			return -1;
		}

		public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			int num = -1;
			for (int i = 0; i < valueLength; i++)
			{
				int num2 = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
				if ((uint)num2 < (uint)num)
				{
					num = num2;
					searchSpaceLength = num2;
					if (num == 0)
					{
						break;
					}
				}
			}
			return num;
		}

		public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			int num = -1;
			for (int i = 0; i < valueLength; i++)
			{
				int num2 = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
				if (num2 > num)
				{
					num = num2;
				}
			}
			return num;
		}

		public unsafe static int IndexOf(ref byte searchSpace, byte value, int length)
		{
			IntPtr intPtr = (IntPtr)0;
			IntPtr intPtr2 = (IntPtr)length;
			if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
			{
				int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
				intPtr2 = (IntPtr)((Vector<byte>.Count - num) & (Vector<byte>.Count - 1));
			}
			while (true)
			{
				if ((nuint)(void*)intPtr2 >= (nuint)8u)
				{
					intPtr2 -= 8;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						goto IL_0242;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
					{
						goto IL_024a;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
					{
						goto IL_0258;
					}
					if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
					{
						if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4))
						{
							if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5))
							{
								if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6))
								{
									if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7))
									{
										break;
									}
									intPtr += 8;
									continue;
								}
								return (int)(void*)(intPtr + 6);
							}
							return (int)(void*)(intPtr + 5);
						}
						return (int)(void*)(intPtr + 4);
					}
					goto IL_0266;
				}
				if ((nuint)(void*)intPtr2 >= (nuint)4u)
				{
					intPtr2 -= 4;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						goto IL_0242;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
					{
						goto IL_024a;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
					{
						goto IL_0258;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
					{
						goto IL_0266;
					}
					intPtr += 4;
				}
				while ((void*)intPtr2 != null)
				{
					intPtr2 -= 1;
					if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						intPtr += 1;
						continue;
					}
					goto IL_0242;
				}
				if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length)
				{
					intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector<byte>.Count - 1));
					Vector<byte> vector = GetVector(value);
					for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector<byte>.Count)
					{
						Vector<byte> vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr)));
						if (!Vector<byte>.Zero.Equals(vector2))
						{
							return (int)(void*)intPtr + LocateFirstFoundByte(vector2);
						}
					}
					if ((int)(void*)intPtr < length)
					{
						intPtr2 = (IntPtr)(length - (int)(void*)intPtr);
						continue;
					}
				}
				return -1;
				IL_0266:
				return (int)(void*)(intPtr + 3);
				IL_0242:
				return (int)(void*)intPtr;
				IL_0258:
				return (int)(void*)(intPtr + 2);
				IL_024a:
				return (int)(void*)(intPtr + 1);
			}
			return (int)(void*)(intPtr + 7);
		}

		public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			byte value2 = value;
			ref byte second = ref Unsafe.Add(ref value, 1);
			int num = valueLength - 1;
			int num2 = 0;
			while (true)
			{
				int num3 = searchSpaceLength - num2 - num;
				if (num3 <= 0)
				{
					break;
				}
				int num4 = LastIndexOf(ref searchSpace, value2, num3);
				if (num4 == -1)
				{
					break;
				}
				if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num))
				{
					return num4;
				}
				num2 += num3 - num4;
			}
			return -1;
		}

		public unsafe static int LastIndexOf(ref byte searchSpace, byte value, int length)
		{
			IntPtr intPtr = (IntPtr)length;
			IntPtr intPtr2 = (IntPtr)length;
			if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
			{
				int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
				intPtr2 = (IntPtr)(((length & (Vector<byte>.Count - 1)) + num) & (Vector<byte>.Count - 1));
			}
			while (true)
			{
				if ((nuint)(void*)intPtr2 >= (nuint)8u)
				{
					intPtr2 -= 8;
					intPtr -= 8;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7))
					{
						break;
					}
					if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6))
					{
						if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5))
						{
							if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4))
							{
								if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
								{
									if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
									{
										if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
										{
											if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr))
											{
												continue;
											}
											goto IL_0254;
										}
										goto IL_025c;
									}
									goto IL_026a;
								}
								goto IL_0278;
							}
							return (int)(void*)(intPtr + 4);
						}
						return (int)(void*)(intPtr + 5);
					}
					return (int)(void*)(intPtr + 6);
				}
				if ((nuint)(void*)intPtr2 >= (nuint)4u)
				{
					intPtr2 -= 4;
					intPtr -= 4;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
					{
						goto IL_0278;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
					{
						goto IL_026a;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
					{
						goto IL_025c;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						goto IL_0254;
					}
				}
				while ((void*)intPtr2 != null)
				{
					intPtr2 -= 1;
					intPtr -= 1;
					if (val

System.Numerics.Vectors.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Globalization;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using FxResources.System.Numerics.Vectors;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Numerics.Vectors")]
[assembly: AssemblyDescription("System.Numerics.Vectors")]
[assembly: AssemblyDefaultAlias("System.Numerics.Vectors")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.25519.03")]
[assembly: AssemblyInformationalVersion("4.6.25519.03 built by: dlab-DDVSOWINAGE013. Commit Hash: 8321c729934c0f8be754953439b88e6e1c120c24")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.1.3.0")]
[module: UnverifiableCode]
namespace FxResources.System.Numerics.Vectors
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class MathF
	{
		public const float PI = 3.1415927f;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Abs(float x)
		{
			return Math.Abs(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Acos(float x)
		{
			return (float)Math.Acos(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Cos(float x)
		{
			return (float)Math.Cos(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float IEEERemainder(float x, float y)
		{
			return (float)Math.IEEERemainder(x, y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Sin(float x)
		{
			return (float)Math.Sin(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Sqrt(float x)
		{
			return (float)Math.Sqrt(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Tan(float x)
		{
			return (float)Math.Tan(x);
		}
	}
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		private const string s_resourcesName = "FxResources.System.Numerics.Vectors.SR";

		private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType));

		internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException", null);

		internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination", null);

		internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef", null);

		internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported", null);

		internal static Type ResourceType => typeof(SR);

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool UsingResourceKeys()
		{
			return false;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal))
			{
				return defaultString;
			}
			return text;
		}

		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(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);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.All)]
	internal class __BlockReflectionAttribute : Attribute
	{
	}
}
namespace System.Numerics
{
	internal class ConstantHelper
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static byte GetByteWithAllBitsSet()
		{
			byte result = 0;
			result = byte.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static sbyte GetSByteWithAllBitsSet()
		{
			sbyte result = 0;
			result = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ushort GetUInt16WithAllBitsSet()
		{
			ushort result = 0;
			result = ushort.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static short GetInt16WithAllBitsSet()
		{
			short result = 0;
			result = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint GetUInt32WithAllBitsSet()
		{
			uint result = 0u;
			result = uint.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetInt32WithAllBitsSet()
		{
			int result = 0;
			result = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ulong GetUInt64WithAllBitsSet()
		{
			ulong result = 0uL;
			result = ulong.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static long GetInt64WithAllBitsSet()
		{
			long result = 0L;
			result = -1L;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static float GetSingleWithAllBitsSet()
		{
			float result = 0f;
			*(int*)(&result) = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static double GetDoubleWithAllBitsSet()
		{
			double result = 0.0;
			*(long*)(&result) = -1L;
			return result;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)]
	internal class JitIntrinsicAttribute : Attribute
	{
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct Register
	{
		[FieldOffset(0)]
		internal byte byte_0;

		[FieldOffset(1)]
		internal byte byte_1;

		[FieldOffset(2)]
		internal byte byte_2;

		[FieldOffset(3)]
		internal byte byte_3;

		[FieldOffset(4)]
		internal byte byte_4;

		[FieldOffset(5)]
		internal byte byte_5;

		[FieldOffset(6)]
		internal byte byte_6;

		[FieldOffset(7)]
		internal byte byte_7;

		[FieldOffset(8)]
		internal byte byte_8;

		[FieldOffset(9)]
		internal byte byte_9;

		[FieldOffset(10)]
		internal byte byte_10;

		[FieldOffset(11)]
		internal byte byte_11;

		[FieldOffset(12)]
		internal byte byte_12;

		[FieldOffset(13)]
		internal byte byte_13;

		[FieldOffset(14)]
		internal byte byte_14;

		[FieldOffset(15)]
		internal byte byte_15;

		[FieldOffset(0)]
		internal sbyte sbyte_0;

		[FieldOffset(1)]
		internal sbyte sbyte_1;

		[FieldOffset(2)]
		internal sbyte sbyte_2;

		[FieldOffset(3)]
		internal sbyte sbyte_3;

		[FieldOffset(4)]
		internal sbyte sbyte_4;

		[FieldOffset(5)]
		internal sbyte sbyte_5;

		[FieldOffset(6)]
		internal sbyte sbyte_6;

		[FieldOffset(7)]
		internal sbyte sbyte_7;

		[FieldOffset(8)]
		internal sbyte sbyte_8;

		[FieldOffset(9)]
		internal sbyte sbyte_9;

		[FieldOffset(10)]
		internal sbyte sbyte_10;

		[FieldOffset(11)]
		internal sbyte sbyte_11;

		[FieldOffset(12)]
		internal sbyte sbyte_12;

		[FieldOffset(13)]
		internal sbyte sbyte_13;

		[FieldOffset(14)]
		internal sbyte sbyte_14;

		[FieldOffset(15)]
		internal sbyte sbyte_15;

		[FieldOffset(0)]
		internal ushort uint16_0;

		[FieldOffset(2)]
		internal ushort uint16_1;

		[FieldOffset(4)]
		internal ushort uint16_2;

		[FieldOffset(6)]
		internal ushort uint16_3;

		[FieldOffset(8)]
		internal ushort uint16_4;

		[FieldOffset(10)]
		internal ushort uint16_5;

		[FieldOffset(12)]
		internal ushort uint16_6;

		[FieldOffset(14)]
		internal ushort uint16_7;

		[FieldOffset(0)]
		internal short int16_0;

		[FieldOffset(2)]
		internal short int16_1;

		[FieldOffset(4)]
		internal short int16_2;

		[FieldOffset(6)]
		internal short int16_3;

		[FieldOffset(8)]
		internal short int16_4;

		[FieldOffset(10)]
		internal short int16_5;

		[FieldOffset(12)]
		internal short int16_6;

		[FieldOffset(14)]
		internal short int16_7;

		[FieldOffset(0)]
		internal uint uint32_0;

		[FieldOffset(4)]
		internal uint uint32_1;

		[FieldOffset(8)]
		internal uint uint32_2;

		[FieldOffset(12)]
		internal uint uint32_3;

		[FieldOffset(0)]
		internal int int32_0;

		[FieldOffset(4)]
		internal int int32_1;

		[FieldOffset(8)]
		internal int int32_2;

		[FieldOffset(12)]
		internal int int32_3;

		[FieldOffset(0)]
		internal ulong uint64_0;

		[FieldOffset(8)]
		internal ulong uint64_1;

		[FieldOffset(0)]
		internal long int64_0;

		[FieldOffset(8)]
		internal long int64_1;

		[FieldOffset(0)]
		internal float single_0;

		[FieldOffset(4)]
		internal float single_1;

		[FieldOffset(8)]
		internal float single_2;

		[FieldOffset(12)]
		internal float single_3;

		[FieldOffset(0)]
		internal double double_0;

		[FieldOffset(8)]
		internal double double_1;
	}
	public struct Vector<T> : IEquatable<Vector<T>>, IFormattable where T : struct
	{
		private struct VectorSizeHelper
		{
			internal Vector<T> _placeholder;

			internal byte _byte;
		}

		private System.Numerics.Register register;

		private static readonly int s_count = InitializeCount();

		private static readonly Vector<T> zero = new Vector<T>(GetZeroValue());

		private static readonly Vector<T> one = new Vector<T>(GetOneValue());

		private static readonly Vector<T> allOnes = new Vector<T>(GetAllBitsSetValue());

		[JitIntrinsic]
		public static int Count => s_count;

		[JitIntrinsic]
		public static Vector<T> Zero => zero;

		[JitIntrinsic]
		public static Vector<T> One => one;

		internal static Vector<T> AllOnes => allOnes;

		[JitIntrinsic]
		public unsafe T this[int index]
		{
			get
			{
				if (index >= Count || index < 0)
				{
					throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, index));
				}
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						return (T)(object)ptr[index];
					}
				}
				if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						return (T)(object)ptr2[index];
					}
				}
				if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						return (T)(object)ptr3[index];
					}
				}
				if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						return (T)(object)ptr4[index];
					}
				}
				if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						return (T)(object)ptr5[index];
					}
				}
				if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						return (T)(object)ptr6[index];
					}
				}
				if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						return (T)(object)ptr7[index];
					}
				}
				if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						return (T)(object)ptr8[index];
					}
				}
				if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						return (T)(object)ptr9[index];
					}
				}
				if (typeof(T) == typeof(double))
				{
					fixed (double* ptr10 = &register.double_0)
					{
						return (T)(object)ptr10[index];
					}
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
		}

		private unsafe static int InitializeCount()
		{
			VectorSizeHelper vectorSizeHelper = default(VectorSizeHelper);
			byte* ptr = &vectorSizeHelper._placeholder.register.byte_0;
			byte* ptr2 = &vectorSizeHelper._byte;
			int num = (int)(ptr2 - ptr);
			int num2 = -1;
			if (typeof(T) == typeof(byte))
			{
				num2 = 1;
			}
			else if (typeof(T) == typeof(sbyte))
			{
				num2 = 1;
			}
			else if (typeof(T) == typeof(ushort))
			{
				num2 = 2;
			}
			else if (typeof(T) == typeof(short))
			{
				num2 = 2;
			}
			else if (typeof(T) == typeof(uint))
			{
				num2 = 4;
			}
			else if (typeof(T) == typeof(int))
			{
				num2 = 4;
			}
			else if (typeof(T) == typeof(ulong))
			{
				num2 = 8;
			}
			else if (typeof(T) == typeof(long))
			{
				num2 = 8;
			}
			else if (typeof(T) == typeof(float))
			{
				num2 = 4;
			}
			else
			{
				if (!(typeof(T) == typeof(double)))
				{
					throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
				}
				num2 = 8;
			}
			return num / num2;
		}

		[JitIntrinsic]
		public unsafe Vector(T value)
		{
			this = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[i] = (byte)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[j] = (sbyte)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[k] = (ushort)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[l] = (short)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[m] = (uint)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[n] = (int)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[num] = (ulong)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[num2] = (long)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[num3] = (float)(object)value;
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = &register.double_0)
					{
						for (int num4 = 0; num4 < Count; num4++)
						{
							ptr10[num4] = (double)(object)value;
						}
					}
				}
			}
			else if (typeof(T) == typeof(byte))
			{
				register.byte_0 = (byte)(object)value;
				register.byte_1 = (byte)(object)value;
				register.byte_2 = (byte)(object)value;
				register.byte_3 = (byte)(object)value;
				register.byte_4 = (byte)(object)value;
				register.byte_5 = (byte)(object)value;
				register.byte_6 = (byte)(object)value;
				register.byte_7 = (byte)(object)value;
				register.byte_8 = (byte)(object)value;
				register.byte_9 = (byte)(object)value;
				register.byte_10 = (byte)(object)value;
				register.byte_11 = (byte)(object)value;
				register.byte_12 = (byte)(object)value;
				register.byte_13 = (byte)(object)value;
				register.byte_14 = (byte)(object)value;
				register.byte_15 = (byte)(object)value;
			}
			else if (typeof(T) == typeof(sbyte))
			{
				register.sbyte_0 = (sbyte)(object)value;
				register.sbyte_1 = (sbyte)(object)value;
				register.sbyte_2 = (sbyte)(object)value;
				register.sbyte_3 = (sbyte)(object)value;
				register.sbyte_4 = (sbyte)(object)value;
				register.sbyte_5 = (sbyte)(object)value;
				register.sbyte_6 = (sbyte)(object)value;
				register.sbyte_7 = (sbyte)(object)value;
				register.sbyte_8 = (sbyte)(object)value;
				register.sbyte_9 = (sbyte)(object)value;
				register.sbyte_10 = (sbyte)(object)value;
				register.sbyte_11 = (sbyte)(object)value;
				register.sbyte_12 = (sbyte)(object)value;
				register.sbyte_13 = (sbyte)(object)value;
				register.sbyte_14 = (sbyte)(object)value;
				register.sbyte_15 = (sbyte)(object)value;
			}
			else if (typeof(T) == typeof(ushort))
			{
				register.uint16_0 = (ushort)(object)value;
				register.uint16_1 = (ushort)(object)value;
				register.uint16_2 = (ushort)(object)value;
				register.uint16_3 = (ushort)(object)value;
				register.uint16_4 = (ushort)(object)value;
				register.uint16_5 = (ushort)(object)value;
				register.uint16_6 = (ushort)(object)value;
				register.uint16_7 = (ushort)(object)value;
			}
			else if (typeof(T) == typeof(short))
			{
				register.int16_0 = (short)(object)value;
				register.int16_1 = (short)(object)value;
				register.int16_2 = (short)(object)value;
				register.int16_3 = (short)(object)value;
				register.int16_4 = (short)(object)value;
				register.int16_5 = (short)(object)value;
				register.int16_6 = (short)(object)value;
				register.int16_7 = (short)(object)value;
			}
			else if (typeof(T) == typeof(uint))
			{
				register.uint32_0 = (uint)(object)value;
				register.uint32_1 = (uint)(object)value;
				register.uint32_2 = (uint)(object)value;
				register.uint32_3 = (uint)(object)value;
			}
			else if (typeof(T) == typeof(int))
			{
				register.int32_0 = (int)(object)value;
				register.int32_1 = (int)(object)value;
				register.int32_2 = (int)(object)value;
				register.int32_3 = (int)(object)value;
			}
			else if (typeof(T) == typeof(ulong))
			{
				register.uint64_0 = (ulong)(object)value;
				register.uint64_1 = (ulong)(object)value;
			}
			else if (typeof(T) == typeof(long))
			{
				register.int64_0 = (long)(object)value;
				register.int64_1 = (long)(object)value;
			}
			else if (typeof(T) == typeof(float))
			{
				register.single_0 = (float)(object)value;
				register.single_1 = (float)(object)value;
				register.single_2 = (float)(object)value;
				register.single_3 = (float)(object)value;
			}
			else if (typeof(T) == typeof(double))
			{
				register.double_0 = (double)(object)value;
				register.double_1 = (double)(object)value;
			}
		}

		[JitIntrinsic]
		public Vector(T[] values)
			: this(values, 0)
		{
		}

		public unsafe Vector(T[] values, int index)
		{
			this = default(Vector<T>);
			if (values == null)
			{
				throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef);
			}
			if (index < 0 || values.Length - index < Count)
			{
				throw new IndexOutOfRangeException();
			}
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[i] = (byte)(object)values[i + index];
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[j] = (sbyte)(object)values[j + index];
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[k] = (ushort)(object)values[k + index];
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[l] = (short)(object)values[l + index];
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[m] = (uint)(object)values[m + index];
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[n] = (int)(object)values[n + index];
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[num] = (ulong)(object)values[num + index];
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[num2] = (long)(object)values[num2 + index];
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[num3] = (float)(object)values[num3 + index];
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = &register.double_0)
					{
						for (int num4 = 0; num4 < Count; num4++)
						{
							ptr10[num4] = (double)(object)values[num4 + index];
						}
					}
				}
			}
			else if (typeof(T) == typeof(byte))
			{
				fixed (byte* ptr11 = &register.byte_0)
				{
					*ptr11 = (byte)(object)values[index];
					ptr11[1] = (byte)(object)values[1 + index];
					ptr11[2] = (byte)(object)values[2 + index];
					ptr11[3] = (byte)(object)values[3 + index];
					ptr11[4] = (byte)(object)values[4 + index];
					ptr11[5] = (byte)(object)values[5 + index];
					ptr11[6] = (byte)(object)values[6 + index];
					ptr11[7] = (byte)(object)values[7 + index];
					ptr11[8] = (byte)(object)values[8 + index];
					ptr11[9] = (byte)(object)values[9 + index];
					ptr11[10] = (byte)(object)values[10 + index];
					ptr11[11] = (byte)(object)values[11 + index];
					ptr11[12] = (byte)(object)values[12 + index];
					ptr11[13] = (byte)(object)values[13 + index];
					ptr11[14] = (byte)(object)values[14 + index];
					ptr11[15] = (byte)(object)values[15 + index];
				}
			}
			else if (typeof(T) == typeof(sbyte))
			{
				fixed (sbyte* ptr12 = &register.sbyte_0)
				{
					*ptr12 = (sbyte)(object)values[index];
					ptr12[1] = (sbyte)(object)values[1 + index];
					ptr12[2] = (sbyte)(object)values[2 + index];
					ptr12[3] = (sbyte)(object)values[3 + index];
					ptr12[4] = (sbyte)(object)values[4 + index];
					ptr12[5] = (sbyte)(object)values[5 + index];
					ptr12[6] = (sbyte)(object)values[6 + index];
					ptr12[7] = (sbyte)(object)values[7 + index];
					ptr12[8] = (sbyte)(object)values[8 + index];
					ptr12[9] = (sbyte)(object)values[9 + index];
					ptr12[10] = (sbyte)(object)values[10 + index];
					ptr12[11] = (sbyte)(object)values[11 + index];
					ptr12[12] = (sbyte)(object)values[12 + index];
					ptr12[13] = (sbyte)(object)values[13 + index];
					ptr12[14] = (sbyte)(object)values[14 + index];
					ptr12[15] = (sbyte)(object)values[15 + index];
				}
			}
			else if (typeof(T) == typeof(ushort))
			{
				fixed (ushort* ptr13 = &register.uint16_0)
				{
					*ptr13 = (ushort)(object)values[index];
					ptr13[1] = (ushort)(object)values[1 + index];
					ptr13[2] = (ushort)(object)values[2 + index];
					ptr13[3] = (ushort)(object)values[3 + index];
					ptr13[4] = (ushort)(object)values[4 + index];
					ptr13[5] = (ushort)(object)values[5 + index];
					ptr13[6] = (ushort)(object)values[6 + index];
					ptr13[7] = (ushort)(object)values[7 + index];
				}
			}
			else if (typeof(T) == typeof(short))
			{
				fixed (short* ptr14 = &register.int16_0)
				{
					*ptr14 = (short)(object)values[index];
					ptr14[1] = (short)(object)values[1 + index];
					ptr14[2] = (short)(object)values[2 + index];
					ptr14[3] = (short)(object)values[3 + index];
					ptr14[4] = (short)(object)values[4 + index];
					ptr14[5] = (short)(object)values[5 + index];
					ptr14[6] = (short)(object)values[6 + index];
					ptr14[7] = (short)(object)values[7 + index];
				}
			}
			else if (typeof(T) == typeof(uint))
			{
				fixed (uint* ptr15 = &register.uint32_0)
				{
					*ptr15 = (uint)(object)values[index];
					ptr15[1] = (uint)(object)values[1 + index];
					ptr15[2] = (uint)(object)values[2 + index];
					ptr15[3] = (uint)(object)values[3 + index];
				}
			}
			else if (typeof(T) == typeof(int))
			{
				fixed (int* ptr16 = &register.int32_0)
				{
					*ptr16 = (int)(object)values[index];
					ptr16[1] = (int)(object)values[1 + index];
					ptr16[2] = (int)(object)values[2 + index];
					ptr16[3] = (int)(object)values[3 + index];
				}
			}
			else if (typeof(T) == typeof(ulong))
			{
				fixed (ulong* ptr17 = &register.uint64_0)
				{
					*ptr17 = (ulong)(object)values[index];
					ptr17[1] = (ulong)(object)values[1 + index];
				}
			}
			else if (typeof(T) == typeof(long))
			{
				fixed (long* ptr18 = &register.int64_0)
				{
					*ptr18 = (long)(object)values[index];
					ptr18[1] = (long)(object)values[1 + index];
				}
			}
			else if (typeof(T) == typeof(float))
			{
				fixed (float* ptr19 = &register.single_0)
				{
					*ptr19 = (float)(object)values[index];
					ptr19[1] = (float)(object)values[1 + index];
					ptr19[2] = (float)(object)values[2 + index];
					ptr19[3] = (float)(object)values[3 + index];
				}
			}
			else if (typeof(T) == typeof(double))
			{
				fixed (double* ptr20 = &register.double_0)
				{
					*ptr20 = (double)(object)values[index];
					ptr20[1] = (double)(object)values[1 + index];
				}
			}
		}

		internal unsafe Vector(void* dataPointer)
			: this(dataPointer, 0)
		{
		}

		internal unsafe Vector(void* dataPointer, int offset)
		{
			this = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				byte* ptr = (byte*)dataPointer;
				ptr += offset;
				fixed (byte* ptr2 = &register.byte_0)
				{
					for (int i = 0; i < Count; i++)
					{
						ptr2[i] = ptr[i];
					}
				}
				return;
			}
			if (typeof(T) == typeof(sbyte))
			{
				sbyte* ptr3 = (sbyte*)dataPointer;
				ptr3 += offset;
				fixed (sbyte* ptr4 = &register.sbyte_0)
				{
					for (int j = 0; j < Count; j++)
					{
						ptr4[j] = ptr3[j];
					}
				}
				return;
			}
			if (typeof(T) == typeof(ushort))
			{
				ushort* ptr5 = (ushort*)dataPointer;
				ptr5 += offset;
				fixed (ushort* ptr6 = &register.uint16_0)
				{
					for (int k = 0; k < Count; k++)
					{
						ptr6[k] = ptr5[k];
					}
				}
				return;
			}
			if (typeof(T) == typeof(short))
			{
				short* ptr7 = (short*)dataPointer;
				ptr7 += offset;
				fixed (short* ptr8 = &register.int16_0)
				{
					for (int l = 0; l < Count; l++)
					{
						ptr8[l] = ptr7[l];
					}
				}
				return;
			}
			if (typeof(T) == typeof(uint))
			{
				uint* ptr9 = (uint*)dataPointer;
				ptr9 += offset;
				fixed (uint* ptr10 = &register.uint32_0)
				{
					for (int m = 0; m < Count; m++)
					{
						ptr10[m] = ptr9[m];
					}
				}
				return;
			}
			if (typeof(T) == typeof(int))
			{
				int* ptr11 = (int*)dataPointer;
				ptr11 += offset;
				fixed (int* ptr12 = &register.int32_0)
				{
					for (int n = 0; n < Count; n++)
					{
						ptr12[n] = ptr11[n];
					}
				}
				return;
			}
			if (typeof(T) == typeof(ulong))
			{
				ulong* ptr13 = (ulong*)dataPointer;
				ptr13 += offset;
				fixed (ulong* ptr14 = &register.uint64_0)
				{
					for (int num = 0; num < Count; num++)
					{
						ptr14[num] = ptr13[num];
					}
				}
				return;
			}
			if (typeof(T) == typeof(long))
			{
				long* ptr15 = (long*)dataPointer;
				ptr15 += offset;
				fixed (long* ptr16 = &register.int64_0)
				{
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr16[num2] = ptr15[num2];
					}
				}
				return;
			}
			if (typeof(T) == typeof(float))
			{
				float* ptr17 = (float*)dataPointer;
				ptr17 += offset;
				fixed (float* ptr18 = &register.single_0)
				{
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr18[num3] = ptr17[num3];
					}
				}
				return;
			}
			if (typeof(T) == typeof(double))
			{
				double* ptr19 = (double*)dataPointer;
				ptr19 += offset;
				fixed (double* ptr20 = &register.double_0)
				{
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr20[num4] = ptr19[num4];
					}
				}
				return;
			}
			throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
		}

		private Vector(ref System.Numerics.Register existingRegister)
		{
			register = existingRegister;
		}

		[JitIntrinsic]
		public void CopyTo(T[] destination)
		{
			CopyTo(destination, 0);
		}

		[JitIntrinsic]
		public unsafe void CopyTo(T[] destination, int startIndex)
		{
			if (destination == null)
			{
				throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef);
			}
			if (startIndex < 0 || startIndex >= destination.Length)
			{
				throw new ArgumentOutOfRangeException("startIndex", System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, startIndex));
			}
			if (destination.Length - startIndex < Count)
			{
				throw new ArgumentException(System.SR.Format(System.SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex));
			}
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = (byte[])(object)destination)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[startIndex + i] = (byte)(object)this[i];
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = (sbyte[])(object)destination)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[startIndex + j] = (sbyte)(object)this[j];
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = (ushort[])(object)destination)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[startIndex + k] = (ushort)(object)this[k];
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = (short[])(object)destination)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[startIndex + l] = (short)(object)this[l];
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = (uint[])(object)destination)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[startIndex + m] = (uint)(object)this[m];
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = (int[])(object)destination)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[startIndex + n] = (int)(object)this[n];
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = (ulong[])(object)destination)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[startIndex + num] = (ulong)(object)this[num];
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = (long[])(object)destination)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[startIndex + num2] = (long)(object)this[num2];
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = (float[])(object)destination)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[startIndex + num3] = (float)(object)this[num3];
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = (double[])(object)destination)
					{
						for (int num4 = 0; num4 < Count; num4++)
						{
							ptr10[startIndex + num4] = (double)(object)this[num4];
						}
					}
				}
			}
			else if (typeof(T) == typeof(byte))
			{
				fixed (byte* ptr11 = (byte[])(object)destination)
				{
					ptr11[startIndex] = register.byte_0;
					ptr11[startIndex + 1] = register.byte_1;
					ptr11[startIndex + 2] = register.byte_2;
					ptr11[startIndex + 3] = register.byte_3;
					ptr11[startIndex + 4] = register.byte_4;
					ptr11[startIndex + 5] = register.byte_5;
					ptr11[startIndex + 6] = register.byte_6;
					ptr11[startIndex + 7] = register.byte_7;
					ptr11[startIndex + 8] = register.byte_8;
					ptr11[startIndex + 9] = register.byte_9;
					ptr11[startIndex + 10] = register.byte_10;
					ptr11[startIndex + 11] = register.byte_11;
					ptr11[startIndex + 12] = register.byte_12;
					ptr11[startIndex + 13] = register.byte_13;
					ptr11[startIndex + 14] = register.byte_14;
					ptr11[startIndex + 15] = register.byte_15;
				}
			}
			else if (typeof(T) == typeof(sbyte))
			{
				fixed (sbyte* ptr12 = (sbyte[])(object)destination)
				{
					ptr12[startIndex] = register.sbyte_0;
					ptr12[startIndex + 1] = register.sbyte_1;
					ptr12[startIndex + 2] = register.sbyte_2;
					ptr12[startIndex + 3] = register.sbyte_3;
					ptr12[startIndex + 4] = register.sbyte_4;
					ptr12[startIndex + 5] = register.sbyte_5;
					ptr12[startIndex + 6] = register.sbyte_6;
					ptr12[startIndex + 7] = register.sbyte_7;
					ptr12[startIndex + 8] = register.sbyte_8;
					ptr12[startIndex + 9] = register.sbyte_9;
					ptr12[startIndex + 10] = register.sbyte_10;
					ptr12[startIndex + 11] = register.sbyte_11;
					ptr12[startIndex + 12] = register.sbyte_12;
					ptr12[startIndex + 13] = register.sbyte_13;
					ptr12[startIndex + 14] = register.sbyte_14;
					ptr12[startIndex + 15] = register.sbyte_15;
				}
			}
			else if (typeof(T) == typeof(ushort))
			{
				fixed (ushort* ptr13 = (ushort[])(object)destination)
				{
					ptr13[startIndex] = register.uint16_0;
					ptr13[startIndex + 1] = register.uint16_1;
					ptr13[startIndex + 2] = register.uint16_2;
					ptr13[startIndex + 3] = register.uint16_3;
					ptr13[startIndex + 4] = register.uint16_4;
					ptr13[startIndex + 5] = register.uint16_5;
					ptr13[startIndex + 6] = register.uint16_6;
					ptr13[startIndex + 7] = register.uint16_7;
				}
			}
			else if (typeof(T) == typeof(short))
			{
				fixed (short* ptr14 = (short[])(object)destination)
				{
					ptr14[startIndex] = register.int16_0;
					ptr14[startIndex + 1] = register.int16_1;
					ptr14[startIndex + 2] = register.int16_2;
					ptr14[startIndex + 3] = register.int16_3;
					ptr14[startIndex + 4] = register.int16_4;
					ptr14[startIndex + 5] = register.int16_5;
					ptr14[startIndex + 6] = register.int16_6;
					ptr14[startIndex + 7] = register.int16_7;
				}
			}
			else if (typeof(T) == typeof(uint))
			{
				fixed (uint* ptr15 = (uint[])(object)destination)
				{
					ptr15[startIndex] = register.uint32_0;
					ptr15[startIndex + 1] = register.uint32_1;
					ptr15[startIndex + 2] = register.uint32_2;
					ptr15[startIndex + 3] = register.uint32_3;
				}
			}
			else if (typeof(T) == typeof(int))
			{
				fixed (int* ptr16 = (int[])(object)destination)
				{
					ptr16[startIndex] = register.int32_0;
					ptr16[startIndex + 1] = register.int32_1;
					ptr16[startIndex + 2] = register.int32_2;
					ptr16[startIndex + 3] = register.int32_3;
				}
			}
			else if (typeof(T) == typeof(ulong))
			{
				fixed (ulong* ptr17 = (ulong[])(object)destination)
				{
					ptr17[startIndex] = register.uint64_0;
					ptr17[startIndex + 1] = register.uint64_1;
				}
			}
			else if (typeof(T) == typeof(long))
			{
				fixed (long* ptr18 = (long[])(object)destination)
				{
					ptr18[startIndex] = register.int64_0;
					ptr18[startIndex + 1] = register.int64_1;
				}
			}
			else if (typeof(T) == typeof(float))
			{
				fixed (float* ptr19 = (float[])(object)destination)
				{
					ptr19[startIndex] = register.single_0;
					ptr19[startIndex + 1] = register.single_1;
					ptr19[startIndex + 2] = register.single_2;
					ptr19[startIndex + 3] = register.single_3;
				}
			}
			else if (typeof(T) == typeof(double))
			{
				fixed (double* ptr20 = (double[])(object)destination)
				{
					ptr20[startIndex] = register.double_0;
					ptr20[startIndex + 1] = register.double_1;
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override bool Equals(object obj)
		{
			if (!(obj is Vector<T>))
			{
				return false;
			}
			return Equals((Vector<T>)obj);
		}

		[JitIntrinsic]
		public bool Equals(Vector<T> other)
		{
			if (Vector.IsHardwareAccelerated)
			{
				for (int i = 0; i < Count; i++)
				{
					if (!ScalarEquals(this[i], other[i]))
					{
						return false;
					}
				}
				return true;
			}
			if (typeof(T) == typeof(byte))
			{
				if (register.byte_0 == other.register.byte_0 && register.byte_1 == other.register.byte_1 && register.byte_2 == other.register.byte_2 && register.byte_3 == other.register.byte_3 && register.byte_4 == other.register.byte_4 && register.byte_5 == other.register.byte_5 && register.byte_6 == other.register.byte_6 && register.byte_7 == other.register.byte_7 && register.byte_8 == other.register.byte_8 && register.byte_9 == other.register.byte_9 && register.byte_10 == other.register.byte_10 && register.byte_11 == other.register.byte_11 && register.byte_12 == other.register.byte_12 && register.byte_13 == other.register.byte_13 && register.byte_14 == other.register.byte_14)
				{
					return register.byte_15 == other.register.byte_15;
				}
				return false;
			}
			if (typeof(T) == typeof(sbyte))
			{
				if (register.sbyte_0 == other.register.sbyte_0 && register.sbyte_1 == other.register.sbyte_1 && register.sbyte_2 == other.register.sbyte_2 && register.sbyte_3 == other.register.sbyte_3 && register.sbyte_4 == other.register.sbyte_4 && register.sbyte_5 == other.register.sbyte_5 && register.sbyte_6 == other.register.sbyte_6 && register.sbyte_7 == other.register.sbyte_7 && register.sbyte_8 == other.register.sbyte_8 && register.sbyte_9 == other.register.sbyte_9 && register.sbyte_10 == other.register.sbyte_10 && register.sbyte_11 == other.register.sbyte_11 && register.sbyte_12 == other.register.sbyte_12 && register.sbyte_13 == other.register.sbyte_13 && register.sbyte_14 == other.register.sbyte_14)
				{
					return register.sbyte_15 == other.register.sbyte_15;
				}
				return false;
			}
			if (typeof(T) == typeof(ushort))
			{
				if (register.uint16_0 == other.register.uint16_0 && register.uint16_1 == other.register.uint16_1 && register.uint16_2 == other.register.uint16_2 && register.uint16_3 == other.register.uint16_3 && register.uint16_4 == other.register.uint16_4 && register.uint16_5 == other.register.uint16_5 && register.uint16_6 == other.register.uint16_6)
				{
					return register.uint16_7 == other.register.uint16_7;
				}
				return false;
			}
			if (typeof(T) == typeof(short))
			{
				if (register.int16_0 == other.register.int16_0 && register.int16_1 == other.register.int16_1 && register.int16_2 == other.register.int16_2 && register.int16_3 == other.register.int16_3 && register.int16_4 == other.register.int16_4 && register.int16_5 == other.register.int16_5 && register.int16_6 == other.register.int16_6)
				{
					return register.int16_7 == other.register.int16_7;
				}
				return false;
			}
			if (typeof(T) == typeof(uint))
			{
				if (register.uint32_0 == other.register.uint32_0 && register.uint32_1 == other.register.uint32_1 && register.uint32_2 == other.register.uint32_2)
				{
					return register.uint32_3 == other.register.uint32_3;
				}
				return false;
			}
			if (typeof(T) == typeof(int))
			{
				if (register.int32_0 == other.register.int32_0 && register.int32_1 == other.register.int32_1 && register.int32_2 == other.register.int32_2)
				{
					return register.int32_3 == other.register.int32_3;
				}
				return false;
			}
			if (typeof(T) == typeof(ulong))
			{
				if (register.uint64_0 == other.register.uint64_0)
				{
					return register.uint64_1 == other.register.uint64_1;
				}
				return false;
			}
			if (typeof(T) == typeof(long))
			{
				if (register.int64_0 == other.register.int64_0)
				{
					return register.int64_1 == other.register.int64_1;
				}
				return false;
			}
			if (typeof(T) == typeof(float))
			{
				if (register.single_0 == other.register.single_0 && register.single_1 == other.register.single_1 && register.single_2 == other.register.single_2)
				{
					return register.single_3 == other.register.single_3;
				}
				return false;
			}
			if (typeof(T) == typeof(double))
			{
				if (register.double_0 == other.register.double_0)
				{
					return register.double_1 == other.register.double_1;
				}
				return false;
			}
			throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
		}

		public override int GetHashCode()
		{
			int num = 0;
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					for (int i = 0; i < Count; i++)
					{
						num = HashHelpers.Combine(num, ((byte)(object)this[i]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(sbyte))
				{
					for (int j = 0; j < Count; j++)
					{
						num = HashHelpers.Combine(num, ((sbyte)(object)this[j]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(ushort))
				{
					for (int k = 0; k < Count; k++)
					{
						num = HashHelpers.Combine(num, ((ushort)(object)this[k]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(short))
				{
					for (int l = 0; l < Count; l++)
					{
						num = HashHelpers.Combine(num, ((short)(object)this[l]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(uint))
				{
					for (int m = 0; m < Count; m++)
					{
						num = HashHelpers.Combine(num, ((uint)(object)this[m]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(int))
				{
					for (int n = 0; n < Count; n++)
					{
						num = HashHelpers.Combine(num, ((int)(object)this[n]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(ulong))
				{
					for (int num2 = 0; num2 < Count; num2++)
					{
						num = HashHelpers.Combine(num, ((ulong)(object)this[num2]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(long))
				{
					for (int num3 = 0; num3 < Count; num3++)
					{
						num = HashHelpers.Combine(num, ((long)(object)this[num3]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(float))
				{
					for (int num4 = 0; num4 < Count; num4++)
					{
						num = HashHelpers.Combine(num, ((float)(object)this[num4]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(double))
				{
					for (int num5 = 0; num5 < Count; num5++)
					{
						num = HashHelpers.Combine(num, ((double)(object)this[num5]).GetHashCode());
					}
					return num;
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			if (typeof(T) == typeof(byte))
			{
				num = HashHelpers.Combine(num, register.byte_0.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_1.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_2.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_3.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_4.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_5.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_6.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_7.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_8.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_9.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_10.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_11.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_12.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_13.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_14.GetHashCode());
				return HashHelpers.Combine(num, register.byte_15.GetHashCode());
			}
			if (typeof(T) == typeof(sbyte))
			{
				num = HashHelpers.Combine(num, register.sbyte_0.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_1.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_2.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_3.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_4.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_5.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_6.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_7.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_8.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_9.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_10.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_11.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_12.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_13.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_14.GetHashCode());
				return HashHelpers.Combine(num, register.sbyte_15.GetHashCode());
			}
			if (typeof(T) == typeof(ushort))
			{
				num = HashHelpers.Combine(num, register.uint16_0.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_1.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_2.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_3.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_4.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_5.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_6.GetHashCode());
				return HashHelpers.Combine(num, register.uint16_7.GetHashCode());
			}
			if (typeof(T) == typeof(short))
			{
				num = HashHelpers.Combine(num, register.int16_0.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_1.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_2.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_3.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_4.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_5.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_6.GetHashCode());
				return HashHelpers.Combine(num, register.int16_7.GetHashCode());
			}
			if (typeof(T) == typeof(uint))
			{
				num = HashHelpers.Combine(num, register.uint32_0.GetHashCode());
				num = HashHelpers.Combine(num, register.uint32_1.GetHashCode());
				num = HashHelpers.Combine(num, register.uint32_2.GetHashCode());
				return HashHelpers.Combine(num, register.uint32_3.GetHashCode());
			}
			if (typeof(T) == typeof(int))
			{
				num = HashHelpers.Combine(num, register.int32_0.GetHashCode());
				num = HashHelpers.Combine(num, register.int32_1.GetHashCode());
				num = HashHelpers.Combine(num, register.int32_2.GetHashCode());
				return HashHelpers.Combine(num, register.int32_3.GetHashCode());
			}
			if (typeof(T) == typeof(ulong))
			{
				num = HashHelpers.Combine(num, register.uint64_0.GetHashCode());
				return HashHelpers.Combine(num, register.uint64_1.GetHashCode());
			}
			if (typeof(T) == typeof(long))
			{
				num = HashHelpers.Combine(num, register.int64_0.GetHashCode());
				return HashHelpers.Combine(num, register.int64_1.GetHashCode());
			}
			if (typeof(T) == typeof(float))
			{
				num = HashHelpers.Combine(num, register.single_0.GetHashCode());
				num = HashHelpers.Combine(num, register.single_1.GetHashCode());
				num = HashHelpers.Combine(num, register.single_2.GetHashCode());
				return HashHelpers.Combine(num, register.single_3.GetHashCode());
			}
			if (typeof(T) == typeof(double))
			{
				num = HashHelpers.Combine(num, register.double_0.GetHashCode());
				return HashHelpers.Combine(num, register.double_1.GetHashCode());
			}
			throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
		}

		public override string ToString()
		{
			return ToString("G", CultureInfo.CurrentCulture);
		}

		public string ToString(string format)
		{
			return ToString(format, CultureInfo.CurrentCulture);
		}

		public string ToString(string format, IFormatProvider formatProvider)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
			stringBuilder.Append('<');
			for (int i = 0; i < Count - 1; i++)
			{
				stringBuilder.Append(((IFormattable)(object)this[i]).ToString(format, formatProvider));
				stringBuilder.Append(numberGroupSeparator);
				stringBuilder.Append(' ');
			}
			stringBuilder.Append(((IFormattable)(object)this[Count - 1]).ToString(format, formatProvider));
			stringBuilder.Append('>');
			return stringBuilder.ToString();
		}

		public unsafe static Vector<T>operator +(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarAdd(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarAdd(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarAdd(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarAdd(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarAdd(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarAdd(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarAdd(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarAdd(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 + right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 + right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 + right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 + right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 + right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 + right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 + right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 + right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 + right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 + right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 + right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 + right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 + right.register.single_0;
				result.register.single_1 = left.register.single_1 + right.register.single_1;
				result.register.single_2 = left.register.single_2 + right.register.single_2;
				result.register.single_3 = left.register.single_3 + right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 + right.register.double_0;
				result.register.double_1 = left.register.double_1 + right.register.double_1;
			}
			return result;
		}

		public unsafe static Vector<T>operator -(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarSubtract(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarSubtract(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarSubtract(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarSubtract(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarSubtract(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarSubtract(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarSubtract(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarSubtract(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 - right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 - right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 - right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 - right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 - right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 - right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 - right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 - right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 - right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 - right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 - right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 - right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 - right.register.single_0;
				result.register.single_1 = left.register.single_1 - right.register.single_1;
				result.register.single_2 = left.register.single_2 - right.register.single_2;
				result.register.single_3 = left.register.single_3 - right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 - right.register.double_0;
				result.register.double_1 = left.register.double_1 - right.register.double_1;
			}
			return result;
		}

		public unsafe static Vector<T>operator *(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarMultiply(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarMultiply(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarMultiply(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarMultiply(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarMultiply(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarMultiply(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarMultiply(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarMultiply(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 * right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 * right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 * right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 * right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 * right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 * right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 * right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 * right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 * right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 * right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 * right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 * right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 * right.register.single_0;
				result.register.single_1 = left.register.single_1 * right.register.single_1;
				result.register.single_2 = left.register.single_2 * right.register.single_2;
				result.register.single_3 = left.register.single_3 * right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 * right.register.double_0;
				result.register.double_1 = left.register.double_1 * right.register.double_1;
			}
			return result;
		}

		public static Vector<T>operator *(Vector<T> value, T factor)
		{
			if (Vector.IsHardwareAccelerated)
			{
				return new Vector<T>(factor) * value;
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor);
				result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor);
				result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor);
				result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor);
				result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor);
				result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor);
				result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor);
				result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor);
				result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor);
				result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor);
				result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor);
				result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor);
				result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor);
				result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor);
				result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor);
				result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor);
				result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor);
				result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor);
				result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor);
				result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor);
				result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor);
				result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor);
				result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor);
				result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor);
				result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor);
				result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor);
				result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor);
				result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor);
				result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor);
				result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor);
				result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor);
				result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor);
				result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor);
				result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor);
				result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor);
				result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor);
				result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor);
				result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor);
				result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor);
				result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor);
				result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor);
				result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor);
				result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor);
				result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor);
				result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor;
				result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor;
				result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor;
				result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = value.register.int32_0 * (int)(object)factor;
				result.register.int32_1 = value.register.int32_1 * (int)(object)factor;
				result.register.int32_2 = value.register.int32_2 * (int)(object)factor;
				result.register.int32_3 = value.register.int32_3 * (int)(object)factor;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor;
				result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = value.register.int64_0 * (long)(object)factor;
				result.register.int64_1 = value.register.int64_1 * (long)(object)factor;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = value.register.single_0 * (float)(object)factor;
				result.register.single_1 = value.register.single_1 * (float)(object)factor;
				result.register.single_2 = value.register.single_2 * (float)(object)factor;
				result.register.single_3 = value.register.single_3 * (float)(object)factor;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = value.register.double_0 * (double)(object)factor;
				result.register.double_1 = value.register.double_1 * (double)(object)factor;
			}
			return result;
		}

		public static Vector<T>operator *(T factor, Vector<T> value)
		{
			if (Vector.IsHardwareAccelerated)
			{
				return new Vector<T>(factor) * value;
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor);
				result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor);
				result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor);
				result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor);
				result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor);
				result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor);
				result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor);
				result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor);
				result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor);
				result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor);
				result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor);
				result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor);
				result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor);
				result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor);
				result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor);
				result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor);
				result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor);
				result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor);
				result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor);
				result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor);
				result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor);
				result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor);
				result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor);
				result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor);
				result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor);
				result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor);
				result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor);
				result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor);
				result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor);
				result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor);
				result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor);
				result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor);
				result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor);
				result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor);
				result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor);
				result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor);
				result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor);
				result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor);
				result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor);
				result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor);
				result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor);
				result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor);
				result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor);
				result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor);
				result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor;
				result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor;
				result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor;
				result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = value.register.int32_0 * (int)(object)factor;
				result.register.int32_1 = value.register.int32_1 * (int)(object)factor;
				result.register.int32_2 = value.register.int32_2 * (int)(object)factor;
				result.register.int32_3 = value.register.int32_3 * (int)(object)factor;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor;
				result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = value.register.int64_0 * (long)(object)factor;
				result.register.int64_1 = value.register.int64_1 * (long)(object)factor;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = value.register.single_0 * (float)(object)factor;
				result.register.single_1 = value.register.single_1 * (float)(object)factor;
				result.register.single_2 = value.register.single_2 * (float)(object)factor;
				result.register.single_3 = value.register.single_3 * (float)(object)factor;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = value.register.double_0 * (double)(object)factor;
				result.register.double_1 = value.register.double_1 * (double)(object)factor;
			}
			return result;
		}

		public unsafe static Vector<T>operator /(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarDivide(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarDivide(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarDivide(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarDivide(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarDivide(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarDivide(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarDivide(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarDivide(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 / right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 / right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 / right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 / right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 / right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 / right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 / right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 / right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 / right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 / right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 / right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 / right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 / right.register.single_0;
				result.register.single_1 = left.register.single_1 / right.register.single_1;
				result.register.single_2 = left.register.single_2 / right.register.single_2;
				result.register.single_3 = left.register.single_3 / right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 / right.register.double_0;
				result.register.double_1 = left.register.double_1 / right.register.double_1;
			}
			return result;
		}

		public static Vector<T>operator -(Vector<T> value)
		{
			return Zero - value;
		}

		[JitIntrinsic]
		public unsafe static Vector<T>operator &(Vector<T> left, Vector<T> right)
		{
			Vector<T> result = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				long* ptr = &result.register.int64_0;
				long* ptr2 = &left.register.int64_0;
				long* ptr3 = &right.register.int64_0;
				for (int i = 0; i < Vector<long>.Count; i++)
				{
					ptr[i] = ptr2[i] & ptr3[i];
				}
			}
			else
			{
				result.register.int64_0 = left.register.int64_0 & right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 & right.register.int64_1;
			}
			return result;
		}

		[JitIntrinsic]
		public unsafe static Vector<T>operator |(Vector<T> left, Vector<T> right)
		{
			Vector<T> result = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				long* ptr = &result.register.int64_0;
				long* ptr2 = &left.register.int64_0;
				long* ptr3 = &right.register.int64_0;
				for (int i = 0; i < Vector<long>.Count; i++)
				{
					ptr[i] = ptr2[i] | ptr3[i];
				}
			}
			else
			{
				result.register.int64_0 = left.register.int64_0 | right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 | right.register.int64_1;
			}
			return result;
		}

		[JitIntrinsic]
		public unsafe static Vector<T>operator ^(Vector<T> left, Vector<T> right)
		{
			Vector<T> result = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				long* ptr = &result.register.int64_0;
				long* ptr2 = &left.register.int64_0;
				long* ptr3 = &right.register.int64_0;
				for (int i = 0; i < Vector<long>.Count; i++)
				{
					ptr[i] = ptr2[i] ^ ptr3[i];
				}
			}
			else
			{
				result.register.int64_0 = left.register.int64_0 ^ right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 ^ right.register.int64_1;
			}
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector<T>operator ~(Vector<T> value)
		{
			return allOnes ^ value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool operator ==(Vector<T> left, Vector<T> right)
		{
			return left.Equals(right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool operator !=(Vector<T> left, Vector<T> right)
		{
			return !(left == right);
		}

		[JitIntrinsic]
		public static explicit operator Vector<byte>(Vector<T> value)
		{
			return new Vector<byte>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<sbyte>(Vector<T> value)
		{
			return new Vector<sbyte>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<ushort>(Vector<T> value)
		{
			return new Vector<ushort>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<short>(Vector<T> value)
		{
			return new Vector<short>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<uint>(Vector<T> value)
		{
			return new Vector<uint>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<int>(Vector<T> value)
		{
			return new Vector<int>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<ulong>(Vector<T> value)
		{
			return new Vector<ulong>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<long>(Vector<T> value)
		{
			return new Vector<long>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<float>(Vector<T> value)
		{
			return new Vector<float>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<double>(Vector<T> value)
		{
			return new Vector<double>(ref value.register);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[JitIntrinsic]
		internal unsafe static Vector<T> Equals(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(ScalarEquals(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(ScalarEquals(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(ScalarEquals(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 

System.Runtime.CompilerServices.Unsafe.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyFileVersion("6.0.21.52210")]
[assembly: AssemblyInformationalVersion("6.0.0")]
[assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyVersion("6.0.0.0")]
namespace System.Runtime.CompilerServices
{
	public static class Unsafe
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T Read<T>(void* source)
		{
			return Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T ReadUnaligned<T>(void* source)
		{
			return Unsafe.ReadUnaligned<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T ReadUnaligned<T>(ref byte source)
		{
			return Unsafe.ReadUnaligned<T>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Write<T>(void* destination, T value)
		{
			Unsafe.Write(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void WriteUnaligned<T>(void* destination, T value)
		{
			Unsafe.WriteUnaligned(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void WriteUnaligned<T>(ref byte destination, T value)
		{
			Unsafe.WriteUnaligned(ref destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(void* destination, ref T source)
		{
			Unsafe.Write(destination, source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(ref T destination, void* source)
		{
			destination = Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* AsPointer<T>(ref T value)
		{
			return Unsafe.AsPointer(ref value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void SkipInit<T>(out T value)
		{
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static int SizeOf<T>()
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlock(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlock(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlock(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T As<T>(object o) where T : class
		{
			return (T)o;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T AsRef<T>(void* source)
		{
			return ref *(T*)source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AsRef<T>(in T source)
		{
			return ref source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref TTo As<TFrom, TTo>(ref TFrom source)
		{
			return ref Unsafe.As<TFrom, TTo>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Unbox<T>(object box) where T : struct
		{
			return ref (T)box;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Add<T>(void* source, int elementOffset)
		{
			return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Subtract<T>(void* source, int elementOffset)
		{
			return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static IntPtr ByteOffset<T>(ref T origin, ref T target)
		{
			return Unsafe.ByteOffset(target: ref target, origin: ref origin);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool AreSame<T>(ref T left, ref T right)
		{
			return Unsafe.AreSame(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressGreaterThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressLessThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressLessThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static bool IsNullRef<T>(ref T source)
		{
			return Unsafe.AsPointer(ref source) == null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T NullRef<T>()
		{
			return ref *(T*)null;
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] A_0)
		{
			TransformFlags = A_0;
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}

System.Runtime.Numerics.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using FxResources.System.Runtime.Numerics;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Runtime.Numerics")]
[assembly: AssemblyDescription("System.Runtime.Numerics")]
[assembly: AssemblyDefaultAlias("System.Runtime.Numerics")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.24705.01")]
[assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyVersion("4.0.2.0")]
namespace FxResources.System.Runtime.Numerics
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		private const string s_resourcesName = "FxResources.System.Runtime.Numerics.SR";

		private static ResourceManager ResourceManager
		{
			get
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Expected O, but got Unknown
				if (s_resourceManager == null)
				{
					s_resourceManager = new ResourceManager(ResourceType);
				}
				return s_resourceManager;
			}
		}

		internal static string Argument_BadFormatSpecifier => GetResourceString("Argument_BadFormatSpecifier", null);

		internal static string Argument_InvalidNumberStyles => GetResourceString("Argument_InvalidNumberStyles", null);

		internal static string Argument_InvalidHexStyle => GetResourceString("Argument_InvalidHexStyle", null);

		internal static string Argument_MustBeBigInt => GetResourceString("Argument_MustBeBigInt", null);

		internal static string Format_TooLarge => GetResourceString("Format_TooLarge", null);

		internal static string ArgumentOutOfRange_MustBeNonNeg => GetResourceString("ArgumentOutOfRange_MustBeNonNeg", null);

		internal static string Overflow_BigIntInfinity => GetResourceString("Overflow_BigIntInfinity", null);

		internal static string Overflow_NotANumber => GetResourceString("Overflow_NotANumber", null);

		internal static string Overflow_ParseBigInteger => GetResourceString("Overflow_ParseBigInteger", null);

		internal static string Overflow_Int32 => GetResourceString("Overflow_Int32", null);

		internal static string Overflow_Int64 => GetResourceString("Overflow_Int64", null);

		internal static string Overflow_UInt32 => GetResourceString("Overflow_UInt32", null);

		internal static string Overflow_UInt64 => GetResourceString("Overflow_UInt64", null);

		internal static string Overflow_Decimal => GetResourceString("Overflow_Decimal", null);

		internal static System.Type ResourceType => typeof(FxResources.System.Runtime.Numerics.SR);

		[MethodImpl(8)]
		private static bool UsingResourceKeys()
		{
			return false;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text, (StringComparison)4))
			{
				return defaultString;
			}
			return text;
		}

		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(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", new object[2] { resourceFormat, p1 });
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", new object[3] { 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(", ", new object[4] { resourceFormat, p1, p2, p3 });
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}
	}
}
namespace System.Globalization
{
	internal class FormatProvider
	{
		private class Number
		{
			internal struct NumberBuffer
			{
				public int precision;

				public int scale;

				public bool sign;

				[SecurityCritical]
				public unsafe char* overrideDigits;

				public unsafe char* digits
				{
					[SecurityCritical]
					get
					{
						return overrideDigits;
					}
				}
			}

			private const int NumberMaxDigits = 32;

			internal const int DECIMAL_PRECISION = 29;

			private const int MIN_SB_BUFFER_SIZE = 105;

			private static string[] s_posCurrencyFormats = new string[4] { "$#", "#$", "$ #", "# $" };

			private static string[] s_negCurrencyFormats = new string[16]
			{
				"($#)", "-$#", "$-#", "$#-", "(#$)", "-#$", "#-$", "#$-", "-# $", "-$ #",
				"# $-", "$ #-", "$ -#", "#- $", "($ #)", "(# $)"
			};

			private static string[] s_posPercentFormats = new string[4] { "# %", "#%", "%#", "% #" };

			private static string[] s_negPercentFormats = new string[12]
			{
				"-# %", "-#%", "-%#", "%-#", "%#-", "#-%", "#%-", "-% #", "# %-", "% #-",
				"% -#", "#- %"
			};

			private static string[] s_negNumberFormats = new string[5] { "(#)", "-#", "- #", "#-", "# -" };

			private static string s_posNumberFormat = "#";

			private Number()
			{
			}

			private static bool IsWhite(char ch)
			{
				if (ch != ' ')
				{
					if (ch >= '\t')
					{
						return ch <= '\r';
					}
					return false;
				}
				return true;
			}

			[SecurityCritical]
			private unsafe static char* MatchChars(char* p, string str)
			{
				fixed (char* str2 = str)
				{
					return MatchChars(p, str2);
				}
			}

			[SecurityCritical]
			private unsafe static char* MatchChars(char* p, char* str)
			{
				if (*str == '\0')
				{
					return null;
				}
				while (*str != 0)
				{
					if (*p != *str && (*str != '\u00a0' || *p != ' '))
					{
						return null;
					}
					p++;
					str++;
				}
				return p;
			}

			[SecurityCritical]
			private unsafe static bool ParseNumber(ref char* str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, bool parseDecimal)
			{
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_0077: Invalid comparison between Unknown and I4
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_009f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
				//IL_0135: Unknown result type (might be due to invalid IL or missing references)
				//IL_0138: Unknown result type (might be due to invalid IL or missing references)
				//IL_0192: Unknown result type (might be due to invalid IL or missing references)
				//IL_0198: Unknown result type (might be due to invalid IL or missing references)
				//IL_0249: Unknown result type (might be due to invalid IL or missing references)
				//IL_024c: Unknown result type (might be due to invalid IL or missing references)
				//IL_028e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0291: Unknown result type (might be due to invalid IL or missing references)
				//IL_031f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0325: Unknown result type (might be due to invalid IL or missing references)
				//IL_0403: Unknown result type (might be due to invalid IL or missing references)
				//IL_0405: Unknown result type (might be due to invalid IL or missing references)
				//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
				//IL_03fd: Unknown result type (might be due to invalid IL or missing references)
				number.scale = 0;
				number.sign = false;
				string text = null;
				string str2 = null;
				string str3 = null;
				bool flag = false;
				string str4;
				string str5;
				if ((options & 0x100) != 0)
				{
					text = numfmt.CurrencySymbol;
					str2 = numfmt.NumberDecimalSeparator;
					str3 = numfmt.NumberGroupSeparator;
					str4 = numfmt.CurrencyDecimalSeparator;
					str5 = numfmt.CurrencyGroupSeparator;
					flag = true;
				}
				else
				{
					str4 = numfmt.NumberDecimalSeparator;
					str5 = numfmt.NumberGroupSeparator;
				}
				int num = 0;
				bool flag2 = false;
				bool flag3 = sb != null;
				bool flag4 = flag3 && (options & 0x200) > 0;
				int num2 = (flag3 ? 2147483647 : 32);
				char* ptr = str;
				char c = *ptr;
				while (true)
				{
					if (!IsWhite(c) || (options & 1) == 0 || (((uint)num & (true ? 1u : 0u)) != 0 && ((num & 1) == 0 || ((num & 0x20) == 0 && numfmt.NumberNegativePattern != 2))))
					{
						char* ptr2;
						if ((flag2 = (options & 4) != 0 && (num & 1) == 0) && (ptr2 = MatchChars(ptr, numfmt.PositiveSign)) != null)
						{
							num |= 1;
							ptr = ptr2 - 1;
						}
						else if (flag2 && (ptr2 = MatchChars(ptr, numfmt.NegativeSign)) != null)
						{
							num |= 1;
							number.sign = true;
							ptr = ptr2 - 1;
						}
						else if (c == '(' && (options & 0x10) != 0 && (num & 1) == 0)
						{
							num |= 3;
							number.sign = true;
						}
						else
						{
							if (text == null || (ptr2 = MatchChars(ptr, text)) == null)
							{
								break;
							}
							num |= 0x20;
							text = null;
							ptr = ptr2 - 1;
						}
					}
					c = *(++ptr);
				}
				int num3 = 0;
				int num4 = 0;
				while (true)
				{
					char* ptr2;
					if ((c >= '0' && c <= '9') || ((options & 0x200) != 0 && ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))))
					{
						num |= 4;
						if (c != '0' || (num & 8) != 0 || flag4)
						{
							if (num3 < num2)
							{
								if (flag3)
								{
									sb.Append(c);
								}
								else
								{
									number.digits[num3++] = c;
								}
								if (c != '0' || parseDecimal)
								{
									num4 = num3;
								}
							}
							if ((num & 0x10) == 0)
							{
								number.scale++;
							}
							num |= 8;
						}
						else if (((uint)num & 0x10u) != 0)
						{
							number.scale--;
						}
					}
					else if ((options & 0x20) != 0 && (num & 0x10) == 0 && ((ptr2 = MatchChars(ptr, str4)) != null || (flag && (num & 0x20) == 0 && (ptr2 = MatchChars(ptr, str2)) != null)))
					{
						num |= 0x10;
						ptr = ptr2 - 1;
					}
					else
					{
						if ((options & 0x40) == 0 || (num & 4) == 0 || ((uint)num & 0x10u) != 0 || ((ptr2 = MatchChars(ptr, str5)) == null && (!flag || ((uint)num & 0x20u) != 0 || (ptr2 = MatchChars(ptr, str3)) == null)))
						{
							break;
						}
						ptr = ptr2 - 1;
					}
					c = *(++ptr);
				}
				bool flag5 = false;
				number.precision = num4;
				if (flag3)
				{
					sb.Append('\0');
				}
				else
				{
					number.digits[num4] = '\0';
				}
				if (((uint)num & 4u) != 0)
				{
					if ((c == 'E' || c == 'e') && (options & 0x80) != 0)
					{
						char* ptr3 = ptr;
						c = *(++ptr);
						char* ptr2;
						if ((ptr2 = MatchChars(ptr, numfmt.PositiveSign)) != null)
						{
							c = *(ptr = ptr2);
						}
						else if ((ptr2 = MatchChars(ptr, numfmt.NegativeSign)) != null)
						{
							c = *(ptr = ptr2);
							flag5 = true;
						}
						if (c >= '0' && c <= '9')
						{
							int num5 = 0;
							do
							{
								num5 = num5 * 10 + (c - 48);
								c = *(++ptr);
								if (num5 > 1000)
								{
									num5 = 9999;
									while (c >= '0' && c <= '9')
									{
										c = *(++ptr);
									}
								}
							}
							while (c >= '0' && c <= '9');
							if (flag5)
							{
								num5 = -num5;
							}
							number.scale += num5;
						}
						else
						{
							ptr = ptr3;
							c = *ptr;
						}
					}
					while (true)
					{
						if (!IsWhite(c) || (options & 2) == 0)
						{
							char* ptr2;
							if ((flag2 = (options & 8) != 0 && (num & 1) == 0) && (ptr2 = MatchChars(ptr, numfmt.PositiveSign)) != null)
							{
								num |= 1;
								ptr = ptr2 - 1;
							}
							else if (flag2 && (ptr2 = MatchChars(ptr, numfmt.NegativeSign)) != null)
							{
								num |= 1;
								number.sign = true;
								ptr = ptr2 - 1;
							}
							else if (c == ')' && ((uint)num & 2u) != 0)
							{
								num &= -3;
							}
							else
							{
								if (text == null || (ptr2 = MatchChars(ptr, text)) == null)
								{
									break;
								}
								text = null;
								ptr = ptr2 - 1;
							}
						}
						c = *(++ptr);
					}
					if ((num & 2) == 0)
					{
						if ((num & 8) == 0)
						{
							if (!parseDecimal)
							{
								number.scale = 0;
							}
							if ((num & 0x10) == 0)
							{
								number.sign = false;
							}
						}
						str = ptr;
						return true;
					}
				}
				str = ptr;
				return false;
			}

			private static bool TrailingZeros(string s, int index)
			{
				for (int i = index; i < s.Length; i++)
				{
					if (s[i] != 0)
					{
						return false;
					}
				}
				return true;
			}

			[SecuritySafeCritical]
			internal unsafe static bool TryStringToNumber(string str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, bool parseDecimal)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				if (str == null)
				{
					return false;
				}
				fixed (char* ptr = str)
				{
					char* str2 = ptr;
					if (!ParseNumber(ref str2, options, ref number, sb, numfmt, parseDecimal) || (str2 - ptr < str.Length && !TrailingZeros(str, (int)(str2 - ptr))))
					{
						return false;
					}
				}
				return true;
			}

			[SecurityCritical]
			internal unsafe static void Int32ToDecChars(char* buffer, ref int index, uint value, int digits)
			{
				while (--digits >= 0 || value != 0)
				{
					buffer[--index] = (char)(value % 10 + 48);
					value /= 10;
				}
			}

			[SecurityCritical]
			internal unsafe static char ParseFormatSpecifier(string format, out int digits)
			{
				if (format != null)
				{
					fixed (char* ptr = format)
					{
						int num = 0;
						char c = ptr[num];
						if (c != 0)
						{
							if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
							{
								num++;
								int num2 = -1;
								if (ptr[num] >= '0' && ptr[num] <= '9')
								{
									num2 = ptr[num++] - 48;
									while (ptr[num] >= '0' && ptr[num] <= '9')
									{
										num2 = num2 * 10 + ptr[num++] - 48;
										if (num2 >= 10)
										{
											break;
										}
									}
								}
								if (ptr[num] == '\0')
								{
									digits = num2;
									return c;
								}
							}
							digits = -1;
							return '\0';
						}
					}
				}
				digits = -1;
				return 'G';
			}

			[SecurityCritical]
			internal unsafe static string NumberToString(NumberBuffer number, char format, int nMaxDigits, NumberFormatInfo info, bool isDecimal)
			{
				//IL_0004: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Expected O, but got Unknown
				//IL_0217: Unknown result type (might be due to invalid IL or missing references)
				int num = -1;
				StringBuilder val = new StringBuilder(105);
				switch (format)
				{
				case 'C':
				case 'c':
					num = ((nMaxDigits >= 0) ? nMaxDigits : info.CurrencyDecimalDigits);
					if (nMaxDigits < 0)
					{
						nMaxDigits = info.CurrencyDecimalDigits;
					}
					RoundNumber(ref number, number.scale + nMaxDigits);
					FormatCurrency(val, number, num, nMaxDigits, info);
					break;
				case 'F':
				case 'f':
					if (nMaxDigits < 0)
					{
						nMaxDigits = (num = info.NumberDecimalDigits);
					}
					else
					{
						num = nMaxDigits;
					}
					RoundNumber(ref number, number.scale + nMaxDigits);
					if (number.sign)
					{
						val.Append(info.NegativeSign);
					}
					FormatFixed(val, number, num, nMaxDigits, info, null, info.NumberDecimalSeparator, null);
					break;
				case 'N':
				case 'n':
					if (nMaxDigits < 0)
					{
						nMaxDigits = (num = info.NumberDecimalDigits);
					}
					else
					{
						num = nMaxDigits;
					}
					RoundNumber(ref number, number.scale + nMaxDigits);
					FormatNumber(val, number, num, nMaxDigits, info);
					break;
				case 'E':
				case 'e':
					if (nMaxDigits < 0)
					{
						nMaxDigits = (num = 6);
					}
					else
					{
						num = nMaxDigits;
					}
					nMaxDigits++;
					RoundNumber(ref number, nMaxDigits);
					if (number.sign)
					{
						val.Append(info.NegativeSign);
					}
					FormatScientific(val, number, num, nMaxDigits, info, format);
					break;
				case 'G':
				case 'g':
				{
					bool flag = true;
					if (nMaxDigits < 1)
					{
						if (isDecimal && nMaxDigits == -1)
						{
							nMaxDigits = (num = 29);
							flag = false;
						}
						else
						{
							nMaxDigits = (num = number.precision);
						}
					}
					else
					{
						num = nMaxDigits;
					}
					if (flag)
					{
						RoundNumber(ref number, nMaxDigits);
					}
					else if (isDecimal && *number.digits == '\0')
					{
						number.sign = false;
					}
					if (number.sign)
					{
						val.Append(info.NegativeSign);
					}
					FormatGeneral(val, number, num, nMaxDigits, info, (char)(format - 2), !flag);
					break;
				}
				case 'P':
				case 'p':
					if (nMaxDigits < 0)
					{
						nMaxDigits = (num = info.PercentDecimalDigits);
					}
					else
					{
						num = nMaxDigits;
					}
					number.scale += 2;
					RoundNumber(ref number, number.scale + nMaxDigits);
					FormatPercent(val, number, num, nMaxDigits, info);
					break;
				default:
					throw new FormatException(SR.Argument_BadFormatSpecifier);
				}
				return ((object)val).ToString();
			}

			[SecuritySafeCritical]
			private static void FormatCurrency(StringBuilder sb, NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info)
			{
				string text = (number.sign ? s_negCurrencyFormats[info.CurrencyNegativePattern] : s_posCurrencyFormats[info.CurrencyPositivePattern]);
				string text2 = text;
				foreach (char c in text2)
				{
					switch (c)
					{
					case '#':
						FormatFixed(sb, number, nMinDigits, nMaxDigits, info, info.CurrencyGroupSizes, info.CurrencyDecimalSeparator, info.CurrencyGroupSeparator);
						break;
					case '-':
						sb.Append(info.NegativeSign);
						break;
					case '$':
						sb.Append(info.CurrencySymbol);
						break;
					default:
						sb.Append(c);
						break;
					}
				}
			}

			[SecurityCritical]
			private unsafe static int wcslen(char* s)
			{
				int num = 0;
				while (*(s++) != 0)
				{
					num++;
				}
				return num;
			}

			[SecurityCritical]
			private unsafe static void FormatFixed(StringBuilder sb, NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info, int[] groupDigits, string sDecimal, string sGroup)
			{
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				int scale = number.scale;
				char* ptr = number.digits;
				int num = wcslen(ptr);
				if (scale > 0)
				{
					if (groupDigits != null)
					{
						int num2 = 0;
						int num3 = groupDigits[num2];
						int num4 = groupDigits.Length;
						int num5 = scale;
						int length = sGroup.Length;
						int num6 = 0;
						if (num4 != 0)
						{
							while (scale > num3 && groupDigits[num2] != 0)
							{
								num5 += length;
								if (num2 < num4 - 1)
								{
									num2++;
								}
								num3 += groupDigits[num2];
								if (num3 < 0 || num5 < 0)
								{
									throw new ArgumentOutOfRangeException();
								}
							}
							num6 = ((num3 != 0) ? groupDigits[0] : 0);
						}
						char* ptr2 = stackalloc char[num5];
						num2 = 0;
						int num7 = 0;
						int num8 = ((scale < num) ? scale : num);
						char* ptr3 = ptr2 + num5 - 1;
						for (int num9 = scale - 1; num9 >= 0; num9--)
						{
							*(ptr3--) = ((num9 < num8) ? ptr[num9] : '0');
							if (num6 > 0)
							{
								num7++;
								if (num7 == num6 && num9 != 0)
								{
									for (int num10 = length - 1; num10 >= 0; num10--)
									{
										*(ptr3--) = sGroup[num10];
									}
									if (num2 < num4 - 1)
									{
										num2++;
										num6 = groupDigits[num2];
									}
									num7 = 0;
								}
							}
						}
						sb.Append(ptr2, num5);
						ptr += num8;
					}
					else
					{
						int num11 = Math.Min(num, scale);
						sb.Append(ptr, num11);
						ptr += num11;
						if (scale > num)
						{
							sb.Append('0', scale - num);
						}
					}
				}
				else
				{
					sb.Append('0');
				}
				if (nMaxDigits > 0)
				{
					sb.Append(sDecimal);
					if (scale < 0 && nMaxDigits > 0)
					{
						int num12 = Math.Min(-scale, nMaxDigits);
						sb.Append('0', num12);
						scale += num12;
						nMaxDigits -= num12;
					}
					while (nMaxDigits > 0)
					{
						sb.Append((*ptr != 0) ? (*(ptr++)) : '0');
						nMaxDigits--;
					}
				}
			}

			[SecuritySafeCritical]
			private static void FormatNumber(StringBuilder sb, NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info)
			{
				string text = (number.sign ? s_negNumberFormats[info.NumberNegativePattern] : s_posNumberFormat);
				string text2 = text;
				foreach (char c in text2)
				{
					switch (c)
					{
					case '#':
						FormatFixed(sb, number, nMinDigits, nMaxDigits, info, info.NumberGroupSizes, info.NumberDecimalSeparator, info.NumberGroupSeparator);
						break;
					case '-':
						sb.Append(info.NegativeSign);
						break;
					default:
						sb.Append(c);
						break;
					}
				}
			}

			[SecurityCritical]
			private unsafe static void FormatScientific(StringBuilder sb, NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info, char expChar)
			{
				char* digits = number.digits;
				sb.Append((*digits != 0) ? (*(digits++)) : '0');
				if (nMaxDigits != 1)
				{
					sb.Append(info.NumberDecimalSeparator);
				}
				while (--nMaxDigits > 0)
				{
					sb.Append((*digits != 0) ? (*(digits++)) : '0');
				}
				int value = ((*number.digits != 0) ? (number.scale - 1) : 0);
				FormatExponent(sb, info, value, expChar, 3, positiveSign: true);
			}

			[SecurityCritical]
			private unsafe static void FormatExponent(StringBuilder sb, NumberFormatInfo info, int value, char expChar, int minDigits, bool positiveSign)
			{
				sb.Append(expChar);
				if (value < 0)
				{
					sb.Append(info.NegativeSign);
					value = -value;
				}
				else if (positiveSign)
				{
					sb.Append(info.PositiveSign);
				}
				char* ptr = stackalloc char[11];
				int index = 10;
				Int32ToDecChars(ptr, ref index, (uint)value, minDigits);
				int num = 10 - index;
				while (--num >= 0)
				{
					sb.Append(ptr[index++]);
				}
			}

			[SecurityCritical]
			private unsafe static void FormatGeneral(StringBuilder sb, NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info, char expChar, bool bSuppressScientific)
			{
				int i = number.scale;
				bool flag = false;
				if (!bSuppressScientific && (i > nMaxDigits || i < -3))
				{
					i = 1;
					flag = true;
				}
				char* digits = number.digits;
				if (i > 0)
				{
					do
					{
						sb.Append((*digits != 0) ? (*(digits++)) : '0');
					}
					while (--i > 0);
				}
				else
				{
					sb.Append('0');
				}
				if (*digits != 0 || i < 0)
				{
					sb.Append(info.NumberDecimalSeparator);
					for (; i < 0; i++)
					{
						sb.Append('0');
					}
					while (*digits != 0)
					{
						sb.Append(*(digits++));
					}
				}
				if (flag)
				{
					FormatExponent(sb, info, number.scale - 1, expChar, 2, positiveSign: true);
				}
			}

			[SecuritySafeCritical]
			private static void FormatPercent(StringBuilder sb, NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info)
			{
				string text = (number.sign ? s_negPercentFormats[info.PercentNegativePattern] : s_posPercentFormats[info.PercentPositivePattern]);
				string text2 = text;
				foreach (char c in text2)
				{
					switch (c)
					{
					case '#':
						FormatFixed(sb, number, nMinDigits, nMaxDigits, info, info.PercentGroupSizes, info.PercentDecimalSeparator, info.PercentGroupSeparator);
						break;
					case '-':
						sb.Append(info.NegativeSign);
						break;
					case '%':
						sb.Append(info.PercentSymbol);
						break;
					default:
						sb.Append(c);
						break;
					}
				}
			}

			[SecurityCritical]
			private unsafe static void RoundNumber(ref NumberBuffer number, int pos)
			{
				int i;
				for (i = 0; i < pos && number.digits[i] != 0; i++)
				{
				}
				if (i == pos && number.digits[i] >= '5')
				{
					while (i > 0 && number.digits[i - 1] == '9')
					{
						i--;
					}
					if (i > 0)
					{
						char* num = number.digits + (i - 1);
						*num = (char)(*num + 1);
					}
					else
					{
						number.scale++;
						*number.digits = '1';
						i = 1;
					}
				}
				else
				{
					while (i > 0 && number.digits[i - 1] == '0')
					{
						i--;
					}
				}
				if (i == 0)
				{
					number.scale = 0;
					number.sign = false;
				}
				number.digits[i] = '\0';
			}

			[SecurityCritical]
			private unsafe static int FindSection(string format, int section)
			{
				if (section == 0)
				{
					return 0;
				}
				fixed (char* ptr = format)
				{
					int num = 0;
					while (true)
					{
						char c;
						char c2 = (c = ptr[num++]);
						if ((uint)c2 <= 34u)
						{
							if (c2 == '\0')
							{
								break;
							}
							if (c2 != '"')
							{
								continue;
							}
						}
						else if (c2 != '\'')
						{
							switch (c2)
							{
							default:
								continue;
							case '\\':
								if (ptr[num] != 0)
								{
									num++;
								}
								continue;
							case ';':
								break;
							}
							if (--section == 0)
							{
								if (ptr[num] == '\0' || ptr[num] == ';')
								{
									break;
								}
								return num;
							}
							continue;
						}
						while (ptr[num] != 0 && ptr[num++] != c)
						{
						}
					}
					return 0;
				}
			}

			[SecurityCritical]
			internal unsafe static string NumberToStringFormat(NumberBuffer number, string format, NumberFormatInfo info)
			{
				//IL_035b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0362: Expected O, but got Unknown
				int num = 0;
				int num2 = FindSection(format, (*number.digits == '\0') ? 2 : (number.sign ? 1 : 0));
				int num3;
				int num4;
				bool flag;
				bool flag2;
				int num5;
				int num6;
				int num9;
				while (true)
				{
					num3 = 0;
					num4 = -1;
					num5 = 2147483647;
					num6 = 0;
					flag = false;
					int num7 = -1;
					flag2 = false;
					int num8 = 0;
					num9 = num2;
					fixed (char* ptr = format)
					{
						char c;
						while ((c = ptr[num9++]) != 0)
						{
							switch (c)
							{
							case ';':
								break;
							case '#':
								num3++;
								continue;
							case '0':
								if (num5 == 2147483647)
								{
									num5 = num3;
								}
								num3++;
								num6 = num3;
								continue;
							case '.':
								if (num4 < 0)
								{
									num4 = num3;
								}
								continue;
							case ',':
								if (num3 <= 0 || num4 >= 0)
								{
									continue;
								}
								if (num7 >= 0)
								{
									if (num7 == num3)
									{
										num++;
										continue;
									}
									flag2 = true;
								}
								num7 = num3;
								num = 1;
								continue;
							case '%':
								num8 += 2;
								continue;
							case '‰':
								num8 += 3;
								continue;
							case '"':
							case '\'':
								while (ptr[num9] != 0 && ptr[num9++] != c)
								{
								}
								continue;
							case '\\':
								if (ptr[num9] != 0)
								{
									num9++;
								}
								continue;
							case 'E':
							case 'e':
								if (ptr[num9] == '0' || ((ptr[num9] == '+' || ptr[num9] == '-') && ptr[num9 + 1] == '0'))
								{
									while (ptr[++num9] == '0')
									{
									}
									flag = true;
								}
								continue;
							default:
								continue;
							}
							break;
						}
					}
					if (num4 < 0)
					{
						num4 = num3;
					}
					if (num7 >= 0)
					{
						if (num7 == num4)
						{
							num8 -= num * 3;
						}
						else
						{
							flag2 = true;
						}
					}
					if (*number.digits != 0)
					{
						number.scale += num8;
						int pos = (flag ? num3 : (number.scale + num3 - num4));
						RoundNumber(ref number, pos);
						if (*number.digits != 0)
						{
							break;
						}
						num9 = FindSection(format, 2);
						if (num9 == num2)
						{
							break;
						}
						num2 = num9;
						continue;
					}
					number.sign = false;
					number.scale = 0;
					break;
				}
				num5 = ((num5 < num4) ? (num4 - num5) : 0);
				num6 = ((num6 > num4) ? (num4 - num6) : 0);
				int num10;
				int num11;
				if (flag)
				{
					num10 = num4;
					num11 = 0;
				}
				else
				{
					num10 = ((number.scale > num4) ? number.scale : num4);
					num11 = number.scale - num4;
				}
				num9 = num2;
				char* digits = number.digits;
				int[] array = new int[4];
				int num12 = -1;
				if (flag2 && info.NumberGroupSeparator.Length > 0)
				{
					int[] numberGroupSizes = info.NumberGroupSizes;
					int num13 = 0;
					int i = 0;
					int num14 = numberGroupSizes.Length;
					if (num14 != 0)
					{
						i = numberGroupSizes[num13];
					}
					int num15 = i;
					int num16 = num10 + ((num11 < 0) ? num11 : 0);
					for (int num17 = ((num5 > num16) ? num5 : num16); num17 > i; i += num15)
					{
						if (num15 == 0)
						{
							break;
						}
						num12++;
						if (num12 >= array.Length)
						{
							System.Array.Resize<int>(ref array, array.Length * 2);
						}
						array[num12] = i;
						if (num13 < num14 - 1)
						{
							num13++;
							num15 = numberGroupSizes[num13];
						}
					}
				}
				StringBuilder val = new StringBuilder(105);
				if (number.sign && num2 == 0)
				{
					val.Append(info.NegativeSign);
				}
				bool flag3 = false;
				fixed (char* ptr2 = format)
				{
					char c;
					while ((c = ptr2[num9++]) != 0 && c != ';')
					{
						if (num11 > 0 && (c == '#' || c == '.' || c == '0'))
						{
							while (num11 > 0)
							{
								val.Append((*digits != 0) ? (*(digits++)) : '0');
								if (flag2 && num10 > 1 && num12 >= 0 && num10 == array[num12] + 1)
								{
									val.Append(info.NumberGroupSeparator);
									num12--;
								}
								num10--;
								num11--;
							}
						}
						switch (c)
						{
						case '#':
						case '0':
							if (num11 < 0)
							{
								num11++;
								c = ((num10 <= num5) ? '0' : '\0');
							}
							else
							{
								c = ((*digits != 0) ? (*(digits++)) : ((num10 > num6) ? '0' : '\0'));
							}
							if (c != 0)
							{
								val.Append(c);
								if (flag2 && num10 > 1 && num12 >= 0 && num10 == array[num12] + 1)
								{
									val.Append(info.NumberGroupSeparator);
									num12--;
								}
							}
							num10--;
							break;
						case '.':
							if (!(num10 != 0 || flag3) && (num6 < 0 || (num4 < num3 && *digits != 0)))
							{
								val.Append(info.NumberDecimalSeparator);
								flag3 = true;
							}
							break;
						case '‰':
							val.Append(info.PerMilleSymbol);
							break;
						case '%':
							val.Append(info.PercentSymbol);
							break;
						case '"':
						case '\'':
							while (ptr2[num9] != 0 && ptr2[num9] != c)
							{
								val.Append(ptr2[num9++]);
							}
							if (ptr2[num9] != 0)
							{
								num9++;
							}
							break;
						case '\\':
							if (ptr2[num9] != 0)
							{
								val.Append(ptr2[num9++]);
							}
							break;
						case 'E':
						case 'e':
						{
							bool positiveSign = false;
							int num18 = 0;
							if (flag)
							{
								if (ptr2[num9] == '0')
								{
									num18++;
								}
								else if (ptr2[num9] == '+' && ptr2[num9 + 1] == '0')
								{
									positiveSign = true;
								}
								else if (ptr2[num9] != '-' || ptr2[num9 + 1] != '0')
								{
									val.Append(c);
									break;
								}
								while (ptr2[++num9] == '0')
								{
									num18++;
								}
								if (num18 > 10)
								{
									num18 = 10;
								}
								int value = ((*number.digits != 0) ? (number.scale - num4) : 0);
								FormatExponent(val, info, value, c, num18, positiveSign);
								flag = false;
							}
							else
							{
								val.Append(c);
								if (ptr2[num9] == '+' || ptr2[num9] == '-')
								{
									val.Append(ptr2[num9++]);
								}
								while (ptr2[num9] == '0')
								{
									val.Append(ptr2[num9++]);
								}
							}
							break;
						}
						default:
							val.Append(c);
							break;
						case ',':
							break;
						}
					}
				}
				return ((object)val).ToString();
			}
		}

		[SecurityCritical]
		internal unsafe static string FormatBigInteger(int precision, int scale, bool sign, string format, NumberFormatInfo numberFormatInfo, char[] digits, int startIndex)
		{
			int digits2;
			char c = Number.ParseFormatSpecifier(format, out digits2);
			fixed (char* ptr = digits)
			{
				Number.NumberBuffer number = default(Number.NumberBuffer);
				number.overrideDigits = ptr + startIndex;
				number.precision = precision;
				number.scale = scale;
				number.sign = sign;
				if (c != 0)
				{
					return Number.NumberToString(number, c, digits2, numberFormatInfo, isDecimal: false);
				}
				return Number.NumberToStringFormat(number, format, numberFormatInfo);
			}
		}

		[SecurityCritical]
		internal unsafe static bool TryStringToBigInteger(string s, NumberStyles styles, NumberFormatInfo numberFormatInfo, StringBuilder receiver, out int precision, out int scale, out bool sign)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			Number.NumberBuffer number = default(Number.NumberBuffer);
			number.overrideDigits = (char*)1;
			if (!Number.TryStringToNumber(s, styles, ref number, receiver, numberFormatInfo, parseDecimal: false))
			{
				precision = 0;
				scale = 0;
				sign = false;
				return false;
			}
			precision = number.precision;
			scale = number.scale;
			sign = number.sign;
			return true;
		}
	}
}
namespace System.Numerics
{
	internal static class BigIntegerCalculator
	{
		internal struct BitsBuffer
		{
			private uint[] _bits;

			private int _length;

			public BitsBuffer(int size, uint value)
			{
				_bits = new uint[size];
				_length = ((value != 0) ? 1 : 0);
				_bits[0] = value;
			}

			public BitsBuffer(int size, uint[] value)
			{
				_bits = new uint[size];
				_length = ActualLength(value);
				System.Array.Copy((System.Array)value, 0, (System.Array)_bits, 0, _length);
			}

			[SecuritySafeCritical]
			public unsafe void MultiplySelf(ref BitsBuffer value, ref BitsBuffer temp)
			{
				fixed (uint* ptr2 = _bits)
				{
					fixed (uint* ptr = value._bits)
					{
						fixed (uint* bits = temp._bits)
						{
							if (_length < value._length)
							{
								Multiply(ptr, value._length, ptr2, _length, bits, _length + value._length);
							}
							else
							{
								Multiply(ptr2, _length, ptr, value._length, bits, _length + value._length);
							}
						}
					}
				}
				Apply(ref temp, _length + value._length);
			}

			[SecuritySafeCritical]
			public unsafe void SquareSelf(ref BitsBuffer temp)
			{
				fixed (uint* value = _bits)
				{
					fixed (uint* bits = temp._bits)
					{
						Square(value, _length, bits, _length + _length);
					}
				}
				Apply(ref temp, _length + _length);
			}

			public void Reduce(ref FastReducer reducer)
			{
				_length = reducer.Reduce(_bits, _length);
			}

			[SecuritySafeCritical]
			public unsafe void Reduce(uint[] modulus)
			{
				if (_length < modulus.Length)
				{
					return;
				}
				fixed (uint* left = _bits)
				{
					fixed (uint* right = modulus)
					{
						Divide(left, _length, right, modulus.Length, null, 0);
					}
				}
				_length = ActualLength(_bits, modulus.Length);
			}

			[SecuritySafeCritical]
			public unsafe void Reduce(ref BitsBuffer modulus)
			{
				if (_length < modulus._length)
				{
					return;
				}
				fixed (uint* left = _bits)
				{
					fixed (uint* right = modulus._bits)
					{
						Divide(left, _length, right, modulus._length, null, 0);
					}
				}
				_length = ActualLength(_bits, modulus._length);
			}

			public void Overwrite(ulong value)
			{
				if (_length > 2)
				{
					System.Array.Clear((System.Array)_bits, 2, _length - 2);
				}
				uint num = (uint)value;
				uint num2 = (uint)(value >> 32);
				_bits[0] = num;
				_bits[1] = num2;
				_length = ((num2 != 0) ? 2 : ((num != 0) ? 1 : 0));
			}

			public void Overwrite(uint value)
			{
				if (_length > 1)
				{
					System.Array.Clear((System.Array)_bits, 1, _length - 1);
				}
				_bits[0] = value;
				_length = ((value != 0) ? 1 : 0);
			}

			public uint[] GetBits()
			{
				return _bits;
			}

			public int GetSize()
			{
				return _bits.Length;
			}

			public int GetLength()
			{
				return _length;
			}

			public void Refresh(int maxLength)
			{
				if (_length > maxLength)
				{
					System.Array.Clear((System.Array)_bits, maxLength, _length - maxLength);
				}
				_length = ActualLength(_bits, maxLength);
			}

			private void Apply(ref BitsBuffer temp, int maxLength)
			{
				System.Array.Clear((System.Array)_bits, 0, _length);
				uint[] bits = temp._bits;
				temp._bits = _bits;
				_bits = bits;
				_length = ActualLength(_bits, maxLength);
			}
		}

		internal struct FastReducer
		{
			private readonly uint[] _modulus;

			private readonly uint[] _mu;

			private readonly uint[] _q1;

			private readonly uint[] _q2;

			private readonly int _muLength;

			public FastReducer(uint[] modulus)
			{
				uint[] array = new uint[modulus.Length * 2 + 1];
				array[array.Length - 1] = 1u;
				_mu = Divide(array, modulus);
				_modulus = modulus;
				_q1 = new uint[modulus.Length * 2 + 2];
				_q2 = new uint[modulus.Length * 2 + 1];
				_muLength = ActualLength(_mu);
			}

			public int Reduce(uint[] value, int length)
			{
				if (length < _modulus.Length)
				{
					return length;
				}
				int leftLength = DivMul(value, length, _mu, _muLength, _q1, _modulus.Length - 1);
				int rightLength = DivMul(_q1, leftLength, _modulus, _modulus.Length, _q2, _modulus.Length + 1);
				return SubMod(value, length, _q2, rightLength, _modulus, _modulus.Length + 1);
			}

			[SecuritySafeCritical]
			private unsafe static int DivMul(uint[] left, int leftLength, uint[] right, int rightLength, uint[] bits, int k)
			{
				System.Array.Clear((System.Array)bits, 0, bits.Length);
				if (leftLength > k)
				{
					leftLength -= k;
					fixed (uint* ptr2 = left)
					{
						fixed (uint* ptr = right)
						{
							fixed (uint* bits2 = bits)
							{
								if (leftLength < rightLength)
								{
									Multiply(ptr, rightLength, ptr2 + k, leftLength, bits2, leftLength + rightLength);
								}
								else
								{
									Multiply(ptr2 + k, leftLength, ptr, rightLength, bits2, leftLength + rightLength);
								}
							}
						}
					}
					return ActualLength(bits, leftLength + rightLength);
				}
				return 0;
			}

			[SecuritySafeCritical]
			private unsafe static int SubMod(uint[] left, int leftLength, uint[] right, int rightLength, uint[] modulus, int k)
			{
				if (leftLength > k)
				{
					leftLength = k;
				}
				if (rightLength > k)
				{
					rightLength = k;
				}
				fixed (uint* left2 = left)
				{
					fixed (uint* right2 = right)
					{
						fixed (uint* right3 = modulus)
						{
							SubtractSelf(left2, leftLength, right2, rightLength);
							leftLength = ActualLength(left, leftLength);
							while (Compare(left2, leftLength, right3, modulus.Length) >= 0)
							{
								SubtractSelf(left2, leftLength, right3, modulus.Length);
								leftLength = ActualLength(left, leftLength);
							}
						}
					}
				}
				System.Array.Clear((System.Array)left, leftLength, left.Length - leftLength);
				return leftLength;
			}
		}

		private static int ReducerThreshold = 32;

		private static int SquareThreshold = 32;

		private static int AllocationThreshold = 256;

		private static int MultiplyThreshold = 32;

		public static uint[] Add(uint[] left, uint right)
		{
			uint[] array = new uint[left.Length + 1];
			long num = (long)left[0] + (long)right;
			array[0] = (uint)num;
			long num2 = num >> 32;
			for (int i = 1; i < left.Length; i++)
			{
				num = left[i] + num2;
				array[i] = (uint)num;
				num2 = num >> 32;
			}
			array[left.Length] = (uint)num2;
			return array;
		}

		[SecuritySafeCritical]
		public unsafe static uint[] Add(uint[] left, uint[] right)
		{
			uint[] array = new uint[left.Length + 1];
			fixed (uint* left2 = left)
			{
				fixed (uint* right2 = right)
				{
					fixed (uint* bits = array)
					{
						Add(left2, left.Length, right2, right.Length, bits, array.Length);
					}
				}
			}
			return array;
		}

		[SecuritySafeCritical]
		private unsafe static void Add(uint* left, int leftLength, uint* right, int rightLength, uint* bits, int bitsLength)
		{
			int i = 0;
			long num = 0L;
			for (; i < rightLength; i++)
			{
				long num2 = left[i] + num + right[i];
				bits[i] = (uint)num2;
				num = num2 >> 32;
			}
			for (; i < leftLength; i++)
			{
				long num3 = left[i] + num;
				bits[i] = (uint)num3;
				num = num3 >> 32;
			}
			bits[i] = (uint)num;
		}

		[SecuritySafeCritical]
		private unsafe static void AddSelf(uint* left, int leftLength, uint* right, int rightLength)
		{
			int i = 0;
			long num = 0L;
			for (; i < rightLength; i++)
			{
				long num2 = left[i] + num + right[i];
				left[i] = (uint)num2;
				num = num2 >> 32;
			}
			while (num != 0L && i < leftLength)
			{
				long num3 = left[i] + num;
				left[i] = (uint)num3;
				num = num3 >> 32;
				i++;
			}
		}

		public static uint[] Subtract(uint[] left, uint right)
		{
			uint[] array = new uint[left.Length];
			long num = (long)left[0] - (long)right;
			array[0] = (uint)num;
			long num2 = num >> 32;
			for (int i = 1; i < left.Length; i++)
			{
				num = left[i] + num2;
				array[i] = (uint)num;
				num2 = num >> 32;
			}
			return array;
		}

		[SecuritySafeCritical]
		public unsafe static uint[] Subtract(uint[] left, uint[] right)
		{
			uint[] array = new uint[left.Length];
			fixed (uint* left2 = left)
			{
				fixed (uint* right2 = right)
				{
					fixed (uint* bits = array)
					{
						Subtract(left2, left.Length, right2, right.Length, bits, array.Length);
					}
				}
			}
			return array;
		}

		[SecuritySafeCritical]
		private unsafe static void Subtract(uint* left, int leftLength, uint* right, int rightLength, uint* bits, int bitsLength)
		{
			int i = 0;
			long num = 0L;
			for (; i < rightLength; i++)
			{
				long num2 = left[i] + num - right[i];
				bits[i] = (uint)num2;
				num = num2 >> 32;
			}
			for (; i < leftLength; i++)
			{
				long num3 = left[i] + num;
				bits[i] = (uint)num3;
				num = num3 >> 32;
			}
		}

		[SecuritySafeCritical]
		private unsafe static void SubtractSelf(uint* left, int leftLength, uint* right, int rightLength)
		{
			int i = 0;
			long num = 0L;
			for (; i < rightLength; i++)
			{
				long num2 = left[i] + num - right[i];
				left[i] = (uint)num2;
				num = num2 >> 32;
			}
			while (num != 0L && i < leftLength)
			{
				long num3 = left[i] + num;
				left[i] = (uint)num3;
				num = num3 >> 32;
				i++;
			}
		}

		public static int Compare(uint[] left, uint[] right)
		{
			if (left.Length < right.Length)
			{
				return -1;
			}
			if (left.Length > right.Length)
			{
				return 1;
			}
			for (int num = left.Length - 1; num >= 0; num--)
			{
				if (left[num] < right[num])
				{
					return -1;
				}
				if (left[num] > right[num])
				{
					return 1;
				}
			}
			return 0;
		}

		[SecuritySafeCritical]
		private unsafe static int Compare(uint* left, int leftLength, uint* right, int rightLength)
		{
			if (leftLength < rightLength)
			{
				return -1;
			}
			if (leftLength > rightLength)
			{
				return 1;
			}
			for (int num = leftLength - 1; num >= 0; num--)
			{
				if (left[num] < right[num])
				{
					return -1;
				}
				if (left[num] > right[num])
				{
					return 1;
				}
			}
			return 0;
		}

		public static uint[] Divide(uint[] left, uint right, out uint remainder)
		{
			uint[] array = new uint[left.Length];
			ulong num = 0uL;
			for (int num2 = left.Length - 1; num2 >= 0; num2--)
			{
				ulong num3 = (num << 32) | left[num2];
				ulong num4 = num3 / right;
				array[num2] = (uint)num4;
				num = num3 - num4 * right;
			}
			remainder = (uint)num;
			return array;
		}

		public static uint[] Divide(uint[] left, uint right)
		{
			uint[] array = new uint[left.Length];
			ulong num = 0uL;
			for (int num2 = left.Length - 1; num2 >= 0; num2--)
			{
				ulong num3 = (num << 32) | left[num2];
				ulong num4 = num3 / right;
				array[num2] = (uint)num4;
				num = num3 - num4 * right;
			}
			return array;
		}

		public static uint Remainder(uint[] left, uint right)
		{
			ulong num = 0uL;
			for (int num2 = left.Length - 1; num2 >= 0; num2--)
			{
				ulong num3 = (num << 32) | left[num2];
				num = num3 % right;
			}
			return (uint)num;
		}

		[SecuritySafeCritical]
		public unsafe static uint[] Divide(uint[] left, uint[] right, out uint[] remainder)
		{
			uint[] array = CreateCopy(left);
			uint[] array2 = new uint[left.Length - right.Length + 1];
			fixed (uint* left2 = array)
			{
				fixed (uint* right2 = right)
				{
					fixed (uint* bits = array2)
					{
						Divide(left2, array.Length, right2, right.Length, bits, array2.Length);
					}
				}
			}
			remainder = array;
			return array2;
		}

		[SecuritySafeCritical]
		public unsafe static uint[] Divide(uint[] left, uint[] right)
		{
			uint[] array = CreateCopy(left);
			uint[] array2 = new uint[left.Length - right.Length + 1];
			fixed (uint* left2 = array)
			{
				fixed (uint* right2 = right)
				{
					fixed (uint* bits = array2)
					{
						Divide(left2, array.Length, right2, right.Length, bits, array2.Length);
					}
				}
			}
			return array2;
		}

		[SecuritySafeCritical]
		public unsafe static uint[] Remainder(uint[] left, uint[] right)
		{
			uint[] array = CreateCopy(left);
			fixed (uint* left2 = array)
			{
				fixed (uint* right2 = right)
				{
					Divide(left2, array.Length, right2, right.Length, null, 0);
				}
			}
			return array;
		}

		[SecuritySafeCritical]
		private unsafe static void Divide(uint* left, int leftLength, uint* right, int rightLength, uint* bits, int bitsLength)
		{
			uint num = right[rightLength - 1];
			uint num2 = ((rightLength > 1) ? right[rightLength - 2] : 0u);
			int num3 = LeadingZeros(num);
			int num4 = 32 - num3;
			if (num3 > 0)
			{
				uint num5 = ((rightLength > 2) ? right[rightLength - 3] : 0u);
				num = (num << num3) | (num2 >> num4);
				num2 = (num2 << num3) | (num5 >> num4);
			}
			for (int num6 = leftLength; num6 >= rightLength; num6--)
			{
				int num7 = num6 - rightLength;
				uint num8 = ((num6 < leftLength) ? left[num6] : 0u);
				ulong num9 = ((ulong)num8 << 32) | left[num6 - 1];
				uint num10 = ((num6 > 1) ? left[num6 - 2] : 0u);
				if (num3 > 0)
				{
					uint num11 = ((num6 > 2) ? left[num6 - 3] : 0u);
					num9 = (num9 << num3) | (num10 >> num4);
					num10 = (num10 << num3) | (num11 >> num4);
				}
				ulong num12 = num9 / num;
				if (num12 > 4294967295u)
				{
					num12 = 4294967295uL;
				}
				while (DivideGuessTooBig(num12, num9, num10, num, num2))
				{
					num12--;
				}
				if (num12 != 0)
				{
					uint num13 = SubtractDivisor(left + num7, leftLength - num7, right, rightLength, num12);
					if (num13 != num8)
					{
						num13 = AddDivisor(left + num7, leftLength - num7, right, rightLength);
						num12--;
					}
				}
				if (bitsLength != 0)
				{
					bits[num7] = (uint)num12;
				}
				if (num6 < leftLength)
				{
					left[num6] = 0u;
				}
			}
		}

		[SecuritySafeCritical]
		private unsafe static uint AddDivisor(uint* left, int leftLength, uint* right, int rightLength)
		{
			ulong num = 0uL;
			for (int i = 0; i < rightLength; i++)
			{
				ulong num2 = left[i] + num + right[i];
				left[i] = (uint)num2;
				num = num2 >> 32;
			}
			return (uint)num;
		}

		[SecuritySafeCritical]
		private unsafe static uint SubtractDivisor(uint* left, int leftLength, uint* right, int rightLength, ulong q)
		{
			ulong num = 0uL;
			for (int i = 0; i < rightLength; i++)
			{
				num += right[i] * q;
				uint num2 = (uint)num;
				num >>= 32;
				if (left[i] < num2)
				{
					num++;
				}
				left[i] -= num2;
			}
			return (uint)num;
		}

		private static bool DivideGuessTooBig(ulong q, ulong valHi, uint valLo, uint divHi, uint divLo)
		{
			ulong num = divHi * q;
			ulong num2 = divLo * q;
			num += num2 >> 32;
			num2 &= 0xFFFFFFFFu;
			if (num < valHi)
			{
				return false;
			}
			if (num > valHi)
			{
				return true;
			}
			if (num2 < valLo)
			{
				return false;
			}
			if (num2 > valLo)
			{
				return true;
			}
			return false;
		}

		private static uint[] CreateCopy(uint[] value)
		{
			uint[] array = new uint[value.Length];
			System.Array.Copy((System.Array)value, 0, (System.Array)array, 0, array.Length);
			return array;
		}

		private static int LeadingZeros(uint value)
		{
			if (value == 0)
			{
				return 32;
			}
			int num = 0;
			if ((value & 0xFFFF0000u) == 0)
			{
				num += 16;
				value <<= 16;
			}
			if ((value & 0xFF000000u) == 0)
			{
				num += 8;
				value <<= 8;
			}
			if ((value & 0xF0000000u) == 0)
			{
				num += 4;
				value <<= 4;
			}
			if ((value & 0xC0000000u) == 0)
			{
				num += 2;
				value <<= 2;
			}
			if ((value & 0x80000000u) == 0)
			{
				num++;
			}
			return num;
		}

		public static uint Gcd(uint left, uint right)
		{
			while (right != 0)
			{
				uint num = left % right;
				left = right;
				right = num;
			}
			return left;
		}

		public static ulong Gcd(ulong left, ulong right)
		{
			while (right > 4294967295u)
			{
				ulong num = left % right;
				left = right;
				right = num;
			}
			if (right != 0L)
			{
				return Gcd((uint)right, (uint)(left % right));
			}
			return left;
		}

		public static uint Gcd(uint[] left, uint right)
		{
			uint right2 = Remainder(left, right);
			return Gcd(right, right2);
		}

		public static uint[] Gcd(uint[] left, uint[] right)
		{
			BitsBuffer left2 = new BitsBuffer(left.Length, left);
			BitsBuffer right2 = new BitsBuffer(right.Length, right);
			Gcd(ref left2, ref right2);
			return left2.GetBits();
		}

		private static void Gcd(ref BitsBuffer left, ref BitsBuffer right)
		{
			while (right.GetLength() > 2)
			{
				ExtractDigits(ref left, ref right, out var x, out var y);
				uint num = 1u;
				uint num2 = 0u;
				uint num3 = 0u;
				uint num4 = 1u;
				int num5 = 0;
				while (y != 0L)
				{
					ulong num6 = x / y;
					if (num6 > 4294967295u)
					{
						break;
					}
					ulong num7 = num + num6 * num3;
					ulong num8 = num2 + num6 * num4;
					ulong num9 = x - num6 * y;
					if (num7 > 2147483647 || num8 > 2147483647 || num9 < num8 || num9 + num7 > y - num3)
					{
						break;
					}
					num = (uint)num7;
					num2 = (uint)num8;
					x = num9;
					num5++;
					if (x == num2)
					{
						break;
					}
					num6 = y / x;
					if (num6 > 4294967295u)
					{
						break;
					}
					num7 = num4 + num6 * num2;
					num8 = num3 + num6 * num;
					num9 = y - num6 * x;
					if (num7 > 2147483647 || num8 > 2147483647 || num9 < num8 || num9 + num7 > x - num2)
					{
						break;
					}
					num4 = (uint)num7;
					num3 = (uint)num8;
					y = num9;
					num5++;
					if (y == num3)
					{
						break;
					}
				}
				if (num2 == 0)
				{
					left.Reduce(ref right);
					BitsBuffer bitsBuffer = left;
					left = right;
					right = bitsBuffer;
					continue;
				}
				LehmerCore(ref left, ref right, num, num2, num3, num4);
				if (num5 % 2 == 1)
				{
					BitsBuffer bitsBuffer2 = left;
					left = right;
					right = bitsBuffer2;
				}
			}
			if (right.GetLength() > 0)
			{
				left.Reduce(ref right);
				uint[] bits = right.GetBits();
				uint[] bits2 = left.GetBits();
				ulong left2 = ((ulong)bits[1] << 32) | bits[0];
				ulong right2 = ((ulong)bits2[1] << 32) | bits2[0];
				left.Overwrite(Gcd(left2, right2));
				right.Overwrite(0u);
			}
		}

		private static void ExtractDigits(ref BitsBuffer xBuffer, ref BitsBuffer yBuffer, out ulong x, out ulong y)
		{
			uint[] bits = xBuffer.GetBits();
			int length = xBuffer.GetLength();
			uint[] bits2 = yBuffer.GetBits();
			int length2 = yBuffer.GetLength();
			ulong num = bits[length - 1];
			ulong num2 = bits[length - 2];
			ulong num3 = bits[length - 3];
			ulong num4;
			ulong num5;
			ulong num6;
			switch (length - length2)
			{
			case 0:
				num4 = bits2[length2 - 1];
				num5 = bits2[length2 - 2];
				num6 = bits2[length2 - 3];
				break;
			case 1:
				num4 = 0uL;
				num5 = bits2[length2 - 1];
				num6 = bits2[length2 - 2];
				break;
			case 2:
				num4 = 0uL;
				num5 = 0uL;
				num6 = bits2[length2 - 1];
				break;
			default:
				num4 = 0uL;
				num5 = 0uL;
				num6 = 0uL;
				break;
			}
			int num7 = LeadingZeros((uint)num);
			x = ((num << 32 + num7) | (num2 << num7) | (num3 >> 32 - num7)) >> 1;
			y = ((num4 << 32 + num7) | (num5 << num7) | (num6 >> 32 - num7)) >> 1;
		}

		private static void LehmerCore(ref BitsBuffer xBuffer, ref BitsBuffer yBuffer, long a, long b, long c, long d)
		{
			uint[] bits = xBuffer.GetBits();
			uint[] bits2 = yBuffer.GetBits();
			int length = yBuffer.GetLength();
			long num = 0L;
			long num2 = 0L;
			for (int i = 0; i < length; i++)
			{
				long num3 = a * bits[i] - b * bits2[i] + num;
				long num4 = d * bits2[i] - c * bits[i] + num2;
				num = num3 >> 32;
				num2 = num4 >> 32;
				bits[i] = (uint)num3;
				bits2[i] = (uint)num4;
			}
			xBuffer.Refresh(length);
			yBuffer.Refresh(length);
		}

		public static uint[] Pow(uint value, uint power)
		{
			int size = PowBound(power, 1, 1);
			BitsBuffer value2 = new BitsBuffer(size, value);
			return PowCore(power, ref value2);
		}

		public static uint[] Pow(uint[] value, uint power)
		{
			int size = PowBound(power, value.Length, 1);
			BitsBuffer value2 = new BitsBuffer(size, value);
			return PowCore(power, ref value2);
		}

		private static uint[] PowCore(uint power, ref BitsBuffer value)
		{
			int size = value.GetSize();
			BitsBuffer temp = new BitsBuffer(size, 0u);
			BitsBuffer result = new BitsBuffer(size, 1u);
			PowCore(power, ref value, ref result, ref temp);
			return result.GetBits();
		}

		private static int PowBound(uint power, int valueLength, int resultLength)
		{
			checked
			{
				while (power != 0)
				{
					if ((power & 1) == 1)
					{
						resultLength += valueLength;
					}
					if (power != 1)
					{
						valueLength += valueLength;
					}
					power >>= 1;
				}
				return resultLength;
			}
		}

		private static void PowCore(uint power, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp)
		{
			while (power != 0)
			{
				if ((power & 1) == 1)
				{
					result.MultiplySelf(ref value, ref temp);
				}
				if (power != 1)
				{
					value.SquareSelf(ref temp);
				}
				power >>= 1;
			}
		}

		public static uint Pow(uint value, uint power, uint modulus)
		{
			return PowCore(power, modulus, value, 1uL);
		}

		public static uint Pow(uint[] value, uint power, uint modulus)
		{
			uint num = Remainder(value, modulus);
			return PowCore(power, modulus, num, 1uL);
		}

		public static uint Pow(uint value, uint[] power, uint modulus)
		{
			return PowCore(power, modulus, value, 1uL);
		}

		public static uint Pow(uint[] value, uint[] power, uint modulus)
		{
			uint num = Remainder(value, modulus);
			return PowCore(power, modulus, num, 1uL);
		}

		private static uint PowCore(uint[] power, uint modulus, ulong value, ulong result)
		{
			for (int i = 0; i < power.Length - 1; i++)
			{
				uint num = power[i];
				for (int j = 0; j < 32; j++)
				{
					if ((num & 1) == 1)
					{
						result = result * value % modulus;
					}
					value = value * value % modulus;
					num >>= 1;
				}
			}
			return PowCore(power[power.Length - 1], modulus, value, result);
		}

		private static uint PowCore(uint power, uint modulus, ulong value, ulong result)
		{
			while (power != 0)
			{
				if ((power & 1) == 1)
				{
					result = result * value % modulus;
				}
				if (power != 1)
				{
					value = value * value % modulus;
				}
				power >>= 1;
			}
			return (uint)(result % modulus);
		}

		public static uint[] Pow(uint value, uint power, uint[] modulus)
		{
			int size = modulus.Length + modulus.Length;
			BitsBuffer value2 = new BitsBuffer(size, value);
			return PowCore(power, modulus, ref value2);
		}

		public static uint[] Pow(uint[] value, uint power, uint[] modulus)
		{
			if (value.Length > modulus.Length)
			{
				value = Remainder(value, modulus);
			}
			int size = modulus.Length + modulus.Length;
			BitsBuffer value2 = new BitsBuffer(size, value);
			return PowCore(power, modulus, ref value2);
		}

		public static uint[] Pow(uint value, uint[] power, uint[] modulus)
		{
			int size = modulus.Length + modulus.Length;
			BitsBuffer value2 = new BitsBuffer(size, value);
			return PowCore(power, modulus, ref value2);
		}

		public static uint[] Pow(uint[] value, uint[] power, uint[] modulus)
		{
			if (value.Length > modulus.Length)
			{
				value = Remainder(value, modulus);
			}
			int size = modulus.Length + modulus.Length;
			BitsBuffer value2 = new BitsBuffer(size, value);
			return PowCore(power, modulus, ref value2);
		}

		private static uint[] PowCore(uint[] power, uint[] modulus, ref BitsBuffer value)
		{
			int size = value.GetSize();
			BitsBuffer temp = new BitsBuffer(size, 0u);
			BitsBuffer result = new BitsBuffer(size, 1u);
			if (modulus.Length < ReducerThreshold)
			{
				PowCore(power, modulus, ref value, ref result, ref temp);
			}
			else
			{
				FastReducer reducer = new FastReducer(modulus);
				PowCore(power, ref reducer, ref value, ref result, ref temp);
			}
			return result.GetBits();
		}

		private static uint[] PowCore(uint power, uint[] modulus, ref BitsBuffer value)
		{
			int size = value.GetSize();
			BitsBuffer temp = new BitsBuffer(size, 0u);
			BitsBuffer result = new BitsBuffer(size, 1u);
			if (modulus.Length < ReducerThreshold)
			{
				PowCore(power, modulus, ref value, ref result, ref temp);
			}
			else
			{
				FastReducer reducer = new FastReducer(modulus);
				PowCore(power, ref reducer, ref value, ref result, ref temp);
			}
			return result.GetBits();
		}

		private static void PowCore(uint[] power, uint[] modulus, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp)
		{
			for (int i = 0; i < power.Length - 1; i++)
			{
				uint num = power[i];
				for (int j = 0; j < 32; j++)
				{
					if ((num & 1) == 1)
					{
						result.MultiplySelf(ref value, ref temp);
						result.Reduce(modulus);
					}
					value.SquareSelf(ref temp);
					value.Reduce(modulus);
					num >>= 1;
				}
			}
			PowCore(power[power.Length - 1], modulus, ref value, ref result, ref temp);
		}

		private static void PowCore(uint power, uint[] modulus, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp)
		{
			while (power != 0)
			{
				if ((power & 1) == 1)
				{
					result.MultiplySelf(ref value, ref temp);
					result.Reduce(modulus);
				}
				if (power != 1)
				{
					value.SquareSelf(ref temp);
					value.Reduce(modulus);
				}
				power >>= 1;
			}
		}

		private static void PowCore(uint[] power, ref FastReducer reducer, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp)
		{
			for (int i = 0; i < power.Length - 1; i++)
			{
				uint num = power[i];
				for (int j = 0; j < 32; j++)
				{
					if ((num & 1) == 1)
					{
						result.MultiplySelf(ref value, ref temp);
						result.Reduce(ref reducer);
					}
					value.SquareSelf(ref temp);
					value.Reduce(ref reducer);
					num >>= 1;
				}
			}
			PowCore(power[power.Length - 1], ref reducer, ref value, ref result, ref temp);
		}

		private static void PowCore(uint power, ref FastReducer reducer, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp)
		{
			while (power != 0)
			{
				if ((power & 1) == 1)
				{
					result.MultiplySelf(ref value, ref temp);
					result.Reduce(ref reducer);
				}
				if (power != 1)
				{
					value.SquareSelf(ref temp);
					value.Reduce(ref reducer);
				}
				power >>= 1;
			}
		}

		private static int ActualLength(uint[] value)
		{
			return ActualLength(value, value.Length);
		}

		private static int ActualLength(uint[] value, int length)
		{
			while (length > 0 && value[length - 1] == 0)
			{
				length--;
			}
			return length;
		}

		[SecuritySafeCritical]
		public unsafe static uint[] Square(uint[] value)
		{
			uint[] array = new uint[value.Length + value.Length];
			fixed (uint* value2 = value)
			{
				fixed (uint* bits = array)
				{
					Square(value2, value.Length, bits, array.Length);
				}
			}
			return array;
		}

		[SecuritySafeCritical]
		private unsafe static void Square(uint* value, int valueLength, uint* bits, int bitsLength)
		{
			if (valueLength < SquareThreshold)
			{
				for (int i = 0; i < valueLength; i++)
				{
					ulong num = 0uL;
					for (int j = 0; j < i; j++)
					{
						ulong num2 = bits[i + j] + num;
						ulong num3 = (ulong)value[j] * (ulong)value[i];
						bits[i + j] = (uint)(num2 + (num3 << 1));
						num = num3 + (num2 >> 1) >> 31;
					}
					ulong num4 = (ulong)((long)value[i] * (long)value[i]) + num;
					bits[i + i] = (uint)num4;
					bits[i + i + 1] = (uint)(num4 >> 32);
				}
				return;
			}
			int num5 = valueLength >> 1;
			int num6 = num5 << 1;
			int num7 = num5;
			uint* ptr = value + num5;
			int num8 = valueLength - num5;
			int num9 = num6;
			uint* ptr2 = bits + num6;
			int num10 = bitsLength - num6;
			Square(value, num7, bits, num9);
			Square(ptr, num8, ptr2, num10);
			int num11 = num8 + 1;
			int num12 = num11 + num11;
			if (num12 < AllocationThreshold)
			{
				uint* ptr3 = stackalloc uint[num11];
				uint* ptr4 = stackalloc uint[num12];
				Add(ptr, num8, value, num7, ptr3, num11);
				Square(ptr3, num11, ptr4, num12);
				SubtractCore(ptr2, num10, bits, num9, ptr4, num12);
				AddSelf(bits + num5, bitsLength - num5, ptr4, num12);
				return;
			}
			fixed (uint* ptr5 = new uint[num11])
			{
				fixed (uint* ptr6 = new uint[num12])
				{
					Add(ptr, num8, value, num7, ptr5, num11);
					Square(ptr5, num11, ptr6, num12);
					SubtractCore(ptr2, num10, bits, num9, ptr6, num12);
					AddSelf(bits + num5, bitsLength - num5, ptr6, num12);
				}
			}
		}

		public static uint[] Multiply(uint[] left, uint right)
		{
			int i = 0;
			ulong num = 0uL;
			uint[] array = new uint[left.Length + 1];
			for (; i < left.Length; i++)
			{
				ulong num2 = (ulong)((long)left[i] * (long)right) + num;
				array[i] = (uint)num2;
				num = num2 >> 32;
			}
			array[i] = (uint)num;
			return array;
		}

		[SecuritySafeCritical]
		public unsafe static uint[] Multiply(uint[] left, uint[] right)
		{
			uint[] array = new uint[left.Length + right.Length];
			fixed (uint* left2 = left)
			{
				fixed (uint* right2 = right)
				{
					fixed (uint* bits = array)
					{
						Multiply(left2, left.Length, right2, right.Length, bits, array.Length);
					}
				}
			}
			return array;
		}

		[SecuritySafeCritical]
		private unsafe static void Multiply(uint* left, int leftLength, uint* right, int rightLength, uint* bits, int bitsLength)
		{
			if (rightLength < MultiplyThreshold)
			{
				for (int i = 0; i < rightLength; i++)
				{
					ulong num = 0uL;
					for (int j = 0; j < leftLength; j++)
					{
						ulong num2 = bits[i + j] + num + (ulong)((long)left[j] * (long)right[i]);
						bits[i + j] = (uint)num2;
						num = num2 >> 32;
					}
					bits[i + leftLength] = (uint)num;
				}
				return;
			}
			int num3 = rightLength >> 1;
			int num4 = num3 << 1;
			int num5 = num3;
			uint* left2 = left + num3;
			int num6 = leftLength - num3;
			int rightLength2 = num3;
			uint* ptr = right + num3;
			int num7 = rightLength - num3;
			int num8 = num4;
			uint* ptr2 = bits + num4;
			int num9 = bitsLength - num4;
			Multiply(left, num5, right, rightLength2, bits, num8);
			Multiply(left2, num6, ptr, num7, ptr2, num9);
			int num10 = num6 + 1;
			int num11 = num7 + 1;
			int num12 = num10 + num11;
			if (num12 < AllocationThreshold)
			{
				uint* ptr3 = stackalloc uint[num10];
				uint* ptr4 = stackalloc uint[num11];
				uint* ptr5 = stackalloc uint[num12];
				Add(left2, num6, left, num5, ptr3, num10);
				Add(ptr, num7, right, rightLength2, ptr4, num11);
				Multiply(ptr3, num10, ptr4, num11, ptr5, num12);
				SubtractCore(ptr2, num9, bits, num8, ptr5, num12);
				AddSelf(bits + num3, bitsLength - num3, ptr5, num12);
				return;
			}
			fixed (uint* ptr6 = new uint[num10])
			{
				fixed (uint* ptr7 = new uint[num11])
				{
					fixed (uint* ptr8 = new uint[num12])
					{
						Add(left2, num6, left, num5, ptr6, num10);
						Add(ptr, num7, right, rightLength2, ptr7, num11);
						Multiply(ptr6, num10, ptr7, num11, ptr8, num12);
						SubtractCore(ptr2, num9, bits, num8, ptr8, num12);
						AddSelf(bits + num3, bitsLength - num3, ptr8, num12);
					}
				}
			}
		}

		[SecuritySafeCritical]
		private unsafe static void SubtractCore(uint* left, int leftLength, uint* right, int rightLength, uint* core, int coreLength)
		{
			int i = 0;
			long num = 0L;
			for (; i < rightLength; i++)
			{
				long num2 = core[i] + num - left[i] - right[i];
				core[i] = (uint)num2;
				num = num2 >> 32;
			}
			for (; i < leftLength; i++)
			{
				long num3 = core[i] + num - left[i];
				core[i] = (uint)num3;
				num = num3 >> 32;
			}
			while (num != 0L && i < coreLength)
			{
				long num4 = core[i] + num;
				core[i] = (uint)num4;
				num = num4 >> 32;
				i++;
			}
		}
	}
	public struct BigInteger : System.IFormattable, IComparable, IComparable<BigInteger>, IEquatable<BigInteger>
	{
		private const int knMaskHighBit = -2147483648;

		private const uint kuMaskHighBit = 2147483648u;

		private const int kcbitUint = 32;

		private const int kcbitUlong = 64;

		private const int DecimalScaleFactorMask = 16711680;

		private const int DecimalSignMask = -2147483648;

		internal readonly int _sign;

		internal readonly uint[] _bits;

		private static readonly BigInteger s_bnMinInt = new BigInteger(-1, new uint[1] { 2147483648u });

		private static readonly BigInteger s_bnOneInt = new BigInteger(1);

		private static readonly BigInteger s_bnZeroInt = new BigInteger(0);

		private static readonly BigInteger s_bnMinusOneInt = new BigInteger(-1);

		public static BigInteger Zero => s_bnZeroInt;

		public static BigInteger One => s_bnOneInt;

		public static BigInteger MinusOne => s_bnMinusOneInt;

		public bool IsPowerOfTwo
		{
			get
			{
				if (_bits == null)
				{
					if ((_sign & (_sign - 1)) == 0)
					{
						return _sign != 0;
					}
					return false;
				}
				if (_sign != 1)
				{
					return false;
				}
				int num = _bits.Length - 1;
				if ((_bits[num] & (_bits[num] - 1)) != 0)
				{
					return false;
				}
				while (--num >= 0)
				{
					if (_bits[num] != 0)
					{
						return false;
					}
				}
				return true;
			}
		}

		public bool IsZero => _sign == 0;

		public bool IsOne
		{
			get
			{
				if (_sign == 1)
				{
					return _bits == null;
				}
				return false;
			}
		}

		public bool IsEven
		{
			get
			{
				if (_bits != null)
				{
					return (_bits[0] & 1) == 0;
				}
				return (_sign & 1) == 0;
			}
		}

		public int Sign => (_sign >> 31) - (-_sign >> 31);

		public BigInteger(int value)
		{
			if (value == -2147483648)
			{
				this = s_bnMinInt;
				return;
			}
			_sign = value;
			_bits = null;
		}

		[CLSCompliant(false)]
		public BigInteger(uint value)
		{
			if (value <= 2147483647)
			{
				_sign = (int)value;
				_bits = null;
			}
			else
			{
				_sign = 1;
				_bits = new uint[1];
				_bits[0] = value;
			}
		}

		public BigInteger(long value)
		{
			if (-2147483648 < value && value <= 2147483647)
			{
				_sign = (int)value;
				_bits = null;
				return;
			}
			if (value == -2147483648)
			{
				this = s_bnMinInt;
				return;
			}
			ulong num = 0uL;
			if (value < 0)
			{
				num = (ulong)(-value);
				_sign = -1;
			}
			else
			{
				num = (ulong)value;
				_sign = 1;
			}
			if (num <= 4294967295u)
			{
				_bits = new uint[1];
				_bits[0] = (uint)num;
			}
			else
			{
				_bits = new uint[2];
				_bits[0] = (uint)num;
				_bits[1] = (uint)(num >> 32);
			}
		}

		[CLSCompliant(false)]
		public BigInteger(ulong value)
		{
			if (value <= 2147483647)
			{
				_sign = (int)value;
				_bits = null;
			}
			else if (value <= 4294967295u)
			{
				_sign = 1;
				_bits = new uint[1];
				_bits[0] = (uint)value;
			}
			else
			{
				_sign = 1;
				_bits = new uint[2];
				_bits[0] = (uint)value;
				_bits[1] = (uint)(value >> 32);
			}
		}

		public BigInteger(float value)
			: this((double)value)
		{
		}

		public BigInteger(double value)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if (double.IsInfinity(value))
			{
				throw new OverflowException(SR.Overflow_BigIntInfinity);
			}
			if (double.IsNaN(value))
			{
				throw new OverflowException(SR.Overflow_NotANumber);
			}
			_sign = 0;
			_bits = null;
			NumericsHelpers.GetDoubleParts(value, out var sign, out var exp, out var man, out var _);
			if (man == 0L)
			{
				this = Zero;
				return;
			}
			if (exp <= 0)
			{
				if (exp <= -64)
				{
					this = Zero;
					return;
				}
				this = man >> -exp;
				if (sign < 0)
				{
					_sign = -_sign;
				}
				return;
			}
			if (exp <= 11)
			{
				this = man << exp;
				if (sign < 0)
				{
					_sign = -_sign;
				}
				return;
			}
			man <<= 11;
			exp -= 11;
			int num = (exp - 1) / 32 + 1;
			int num2 = num * 32 - exp;
			_bits = new uint[num + 2];
			_bits[num + 1] = (uint)(man >> num2 + 32);
			_bits[num] = (uint)(man >> num2);
			if (num2 > 0)
			{
				_bits[num - 1] = (uint)((int)man << 32 - num2);
			}
			_sign = sign;
		}

		public BigInteger(decimal value)
		{
			int[] bits = decimal.GetBits(decimal.Truncate(value));
			int num = 3;
			while (num > 0 && bits[num - 1] == 0)
			{
				num--;
			}
			switch (num)
			{
			case 0:
				this = s_bnZeroInt;
				return;
			case 1:
				if (bits[0] > 0)
				{
					_sign = bits[0];
					_sign *= (((bits[3] & -2147483648) == 0) ? 1 : (-1));
					_bits = null;
					return;
				}
				break;
			}
			_bits = new uint[num];
			_bits[0] = (uint)bits[0];
			if (num > 1)
			{
				_bits[1] = (uint)bits[1];
			}
			if (num > 2)
			{
				_bits[2] = (uint)bits[2];
			}
			_sign = (((bits[3] & -2147483648) == 0) ? 1 : (-1));
		}

		[CLSCompliant(false)]
		public BigInteger(byte[] value)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			int num = value.Length;
			bool flag = num > 0 && (value[num - 1] & 0x80) == 128;
			while (num > 0 && value[num - 1] == 0)
			{
				num--;
			}
			if (num == 0)
			{
				_sign = 0;
				_bits = null;
				return;
			}
			if (num <= 4)
			{
				if (flag)
				{
					_sign = -1;
				}
				else
				{
					_sign = 0;
				}
				for (int num2 = num - 1; num2 >= 0; num2--)
				{
					_sign <<= 8;
					_sign |= value[num2];
				}
				_bits = null;
				if (_sign < 0 && !flag)
				{
					_bits = new uint[1];
					_bits[0] = (uint)_sign;
					_sign = 1;
				}
				if (_sign == -2147483648)
				{
					this = s_bnMinInt;
				}
				return;
			}
			int num3 = num % 4;
			int num4 = num / 4 + ((num3 != 0) ? 1 : 0);
			bool flag2 = true;
			uint[] array = new uint[num4];
			int num5 = 3;
			int i;
			for (i = 0; i < num4 - ((num3 != 0) ? 1 : 0); i++)
			{
				for (int j = 0; j < 4; j++)
				{
					if (value[num5] != 0)
					{
						flag2 = false;
					}
					array[i] <<= 8;
					array[i] |= value[num5];
					num5--;
				}
				num5 += 8;
			}
			if (num3 != 0)
			{
				if (flag)
				{
					array[num4 - 1] = 4294967295u;
				}
				for (num5 = num - 1; num5 >= num - num3; num5--)
				{
					if (value[num5] != 0)
					{
						flag2 = false;
					}
					array[i] <<= 8;
					array[i] |= value[num5];
				}
			}
			if (flag2)
			{
				this = s_bnZeroInt;
			}
			else if (flag)
			{
				NumericsHelpers.DangerousMakeTwosComplement(array);
				int num6 = array.Length;
				while (num6 > 0 && array[num6 - 1] == 0)
				{
					num6--;
				}
				if (num6 == 1 && (int)array[0] > 0)
				{
					if (array[0] == 1)
					{
						this = s_bnMinusOneInt;
						return;
					}
					if (array[0] == 2147483648u)
					{
						this = s_bnMinInt;
						return;
					}
					_sign = -1 * (int)array[0];
					_bits = null;
				}
				else if (num6 != array.Length)
				{
					_sign = -1;
					_bits = new uint[num6];
					System.Array.Copy((System.Array)array, 0, (System.Array)_bits, 0, num6);
				}
				else
				{
					_sign = -1;
					_bits = array;
				}
			}
			else
			{
				_sign = 1;
				_bits = array;
			}
		}

		internal BigInteger(int n, uint[] rgu)
		{
			_sign = n;
			_bits = rgu;
		}

		internal BigInteger(uint[] value, bool negative)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			int num = value.Length;
			while (num > 0 && value[num - 1] == 0)
			{
				num--;
			}
			switch (num)
			{
			case 0:
				this = s_bnZeroInt;
				break;
			case 1:
				if (value[0] < 2147483648u)
				{
					_sign = (int)(negative ? (0 - value[0]) : value[0]);
					_bits = null;
					if (_sign == -2147483648)
					{
						this = s_bnMinInt;
					}
					break;
				}
				goto default;
			default:
				_sign = ((!negative) ? 1 : (-1));
				_bits = new uint[num];
				System.Array.Copy((System.Array)value, 0, (System.Array)_bits, 0, num);
				break;
			}
		}

		private BigInteger(uint[] value)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			int num = value.Length;
			bool flag = num > 0 && (value[num - 1] & 0x80000000u) == 2147483648u;
			while (num > 0 && value[num - 1] == 0)
			{
				num--;
			}
			switch (num)
			{
			case 0:
				this = s_bnZeroInt;
				return;
			case 1:
				if ((int)value[0] < 0 && !flag)
				{
					_bits = new uint[1];
					_bits[0] = value[0];
					_sign = 1;
				}
				else if (-2147483648 == (int)value[0])
				{
					this = s_bnMinInt;
				}
				else
				{
					_sign = (int)value[0];
					_bits = null;
				}
				return;
			}
			if (!flag)
			{
				if (num != value.Length)
				{
					_sign = 1;
					_bits = new uint[num];
					System.Array.Copy((System.Array)value, 0, (System.Array)_bits, 0, num);
				}
				else
				{
					_sign = 1;
					_bits = value;
				}
				return;
			}
			NumericsHelpers.DangerousMakeTwosComplement(value);
			int num2 = value.Length;
			while (num2 > 0 && value[num2 - 1] == 0)
			{
				num2--;
			}
			if (num2 == 1 && (int)value[0] > 0)
			{
				if (value[0] == 1)
				{
					this = s_bnMinusOneInt;
					return;
				}
				if (value[0] == 2147483648u)
				{
					this = s_bnMinInt;
					return;
				}
				_sign = -1 * (int)value[0];
				_bits = null;
			}
			else if (num2 != value.Length)
			{
				_sign = -1;
				_bits = new uint[num2];
				System.Array.Copy((System.Array)value, 0, (System.Array)_bits, 0, num2);
			}
			else
			{
				_sign = -1;
				_bits = value;
			}
		}

		public static BigInteger Parse(string value)
		{
			return Parse(value, (NumberStyles)7);
		}

		public static BigInteger Parse(string value, NumberStyles style)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return Parse(value, style, (IFormatProvider)(object)NumberFormatInfo.CurrentInfo);
		}

		public static BigInteger Parse(string value, IFormatProvider provider)
		{
			return Parse(value, (NumberStyles)7, (IFormatProvider)(object)NumberFormatInfo.GetInstance(provider));
		}

		public static BigInteger Parse(string value, NumberStyles style, IFormatProvider provider)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return BigNumber.ParseBigInteger(value, style, NumberFormatInfo.GetInstance(provider));
		}

		public static bool TryParse(string value, out BigInteger result)
		{
			return TryParse(value, (NumberStyles)7, (IFormatProvider)(object)NumberFormatInfo.CurrentInfo, out result);
		}

		public static bool TryParse(string value, NumberStyles style, IFormatProvider provider, out BigInteger result)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return BigNumber.TryParseBigInteger(value, style, NumberFormatInfo.GetInstance(provider), out result);
		}

		public static int Compare(BigInteger left, BigInteger right)
		{
			return left.CompareTo(right);
		}

		public static BigInteger Abs(BigInteger value)
		{
			if (!(value >= Zero))
			{
				return -value;
			}
			return value;
		}

		public static BigInteger Add(BigInteger left, BigInteger right)
		{
			return left + right;
		}

		public static BigInteger Subtract(BigInteger left, BigInteger right)
		{
			return left - right;
		}

		public static BigInteger Multiply(BigInteger left, BigInteger right)
		{
			return left * right;
		}

		public static BigInteger Divide(BigInteger dividend, BigInteger divisor)
		{
			return dividend / divisor;
		}

		public static BigInteger Remainder(BigInteger dividend, BigInteger divisor)
		{
			return dividend % divisor;
		}

		public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out BigInteger remainder)
		{
			bool flag = dividend._bits == null;
			bool flag2 = divisor._bits == null;
			if (flag && flag2)
			{
				remainder = dividend._sign % divisor._sign;
				return dividend._sign / divisor._sign;
			}
			if (flag)
			{
				remainder = dividend;
				return s_bnZeroInt;
			}
			if (flag2)
			{
				uint remainder2;
				uint[] value = BigIntegerCalculator.Divide(dividend._bits, NumericsHelpers.Abs(divisor._sign), out remainder2);
				remainder = ((dividend._sign < 0) ? (-1 * remainder2) : remainder2);
				return new BigInteger(value, (dividend._sign < 0) ^ (divisor._sign < 0));
			}
			if (dividend._bits.Length < divisor._bits.Length)
			{
				remainder = dividend;
				return s_bnZeroInt;
			}
			uint[] remainder3;
			uint[] value2 = BigIntegerCalculator.Divide(dividend._bits, divisor._bits, out remainder3);
			remainder = new BigInteger(remainder3, dividend._sign < 0);
			return new BigInteger(value2, (dividend._sign < 0) ^ (divisor._sign < 0));
		}

		public static BigInteger Negate(BigInteger value)
		{
			return -value;
		}

		public static double Log(BigInteger value)
		{
			return Log(value, Math.E);
		}

		public static double Log(BigInteger value, double baseValue)
		{
			if (value._sign < 0 || baseValue == 1.0)
			{
				return 0.0 / 0.0;
			}
			if (baseValue == 1.0 / 0.0)
			{
				if (!value.IsOne)
				{
					return 0.0 / 0.0;
				}
				return 0.0;
			}
			if (baseValue == 0.0 && !value.IsOne)
			{
				return 0.0 / 0.0;
			}
			if (value._bits == null)
			{
				return Math.Log((double)value._sign, baseValue);
			}
			ulong num = value._bits[value._bits.Length - 1];
			ulong num2 = ((value._bits.Length > 1) ? value._bits[value._bits.Length - 2] : 0u);
			ulong num3 = ((value._bits.Length > 2) ? value._bits[value._bits.Length - 3] : 0u);
			int num4 = NumericsHelpers.CbitHighZero((uint)num);
			long num5 = (long)value._bits.Length * 32L - num4;
			ulong num6 = (num << 32 + num4) | (num2 << num4) | (num3 >> 32 - num4);
			return Math.Log((double)num6, baseValue) + (double)(num5 - 64) / Math.Log(baseValue, 2.0);
		}

		public static double Log10(BigInteger value)
		{
			return Log(value, 10.0);
		}

		public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right)
		{
			bool flag = left._bits == null;
			bool flag2 = right._bits == null;
			if (flag && flag2)
			{
				return BigIntegerCalculator.Gcd(NumericsHelpers.Abs(left._sign), NumericsHelpers.Abs(right._sign));
			}
			if (flag)
			{
				if (left._sign == 0)
				{
					return new BigInteger(right._bits, negative: false);
				}
				return BigIntegerCalculator.Gcd(right._bits, NumericsHelpers.Abs(left._sign));
			}
			if (flag2)
			{
				if (right._sign == 0)
				{
					return new BigInteger(left._bits, negative: false);
				}
				return BigIntegerCalculator.Gcd(left._bits, NumericsHelpers.Abs(right._sign));
			}
			if (BigIntegerCalculator.Compare(left._bits, right._bits) < 0)
			{
				return GreatestCommonDivisor(right._bits, left._bits);
			}
			return GreatestCommonDivisor(left._bits, right._bits);
		}

		private static BigInteger GreatestCommonDivisor(uint[] leftBits, uint[] rightBits)
		{
			if (rightBits.Length == 1)
			{
				uint right = BigIntegerCalculator.Remainder(leftBits, rightBits[0]);
				return BigIntegerCalculator.Gcd(rightBits[0], right);
			}
			if (rightBits.Length == 2)
			{
				uint[] array = BigIntegerCalculator.Remainder(leftBits, rightBits);
				ulong left = ((ulong)rightBits[1] << 32) | rightBits[0];
				ulong right2 = ((ulong)array[1] << 32) | array[0];
				return BigIntegerCalculator.Gcd(left, right2);
			}
			uint[] value = BigIntegerCalculator.Gcd(leftBits, rightBits);
			return new BigInteger(value, negative: false);
		}

		public static BigInteger Max(BigInteger left, BigInteger right)
		{
			if (left.CompareTo(right) < 0)
			{
				return right;
			}
			return left;
		}

		public static BigInteger Min(BigInteger left, BigInteger right)
		{
			if (left.CompareTo(right) <= 0)
			{
				return left;
			}
			return right;
		}

		public static BigInteger ModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (exponent.Sign < 0)
			{
				throw new ArgumentOutOfRangeException("exponent", SR.ArgumentOutOfRange_MustBeNonNeg);
			}
			bool flag = value._bits == null;
			bool flag2 = exponent._bits == null;
			if (modulus._bits == null)
			{
				uint num = ((flag && flag2) ? BigIntegerCalculator.Pow(NumericsHelpers.Abs(value._sign), NumericsHelpers.Abs(exponent._sign), NumericsHelpers.Abs(modulus._sign)) : (flag ? BigIntegerCalculator.Pow(NumericsHelpers.Abs(value._sign), exponent._bits, NumericsHelpers.Abs(modulus._sign)) : (flag2 ? BigIntegerCalculator.Pow(value._bits, NumericsHelpers.Abs(exponent._sign), NumericsHelpers.Abs(modulus._sign)) : BigIntegerCalculator.Pow(value._bits, exponent._bits, NumericsHelpers.Abs(modulus._sign)))));
				return (value._sign < 0 && !exponent.IsEven) ? (-1 * num) : num;
			}
			uint[] value2 = ((flag && flag2) ? BigIntegerCalculator.Pow(NumericsHelpers.Abs(value._sign), NumericsHelpers.Abs(exponent._sign), modulus._bits) : (flag ? BigIntegerCalculator.Pow(NumericsHelpers.Abs(value._sign), exponent._bits, modulus._bits) : (flag2 ? BigIntegerCalculator.Pow(value._bits, NumericsHelpers.Abs(exponent._sign), modulus._bits) : BigIntegerCalculator.Pow(value._bits, exponent._bits, modulus._bits))));
			return new BigInteger(value2, value._sign < 0 && !exponent.IsEven);
		}

		public static BigInteger Pow(BigInteger value, int exponent)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (exponent < 0)
			{
				throw new ArgumentOutOfRangeException("exponent", SR.ArgumentOutOfRange_MustBeNonNeg);
			}
			switch (exponent)
			{
			case 0:
				return s_bnOneInt;
			case 1:
				return value;
			default:
			{
				bool flag = value._bits == null;
				if (flag)
				{
					if (value._sign == 1)
					{
						return value;
					}
					if (value._sign == -1)
					{
						if ((exponent & 1) == 0)
						{
							return s_bnOneInt;
						}
						return value;
					}
					if (value._sign == 0)
					{
						return value;
					}
				}
				uint[] value2 = (flag ? BigIntegerCalculator.Pow(NumericsHelpers.Abs(value._sign), NumericsHelpers.Abs(exponent)) : BigIntegerCalculator.Pow(value._bits, NumericsHelpers.Abs(exponent)));
				return new BigInteger(value2, value._sign < 0 && (exponent & 1) != 0);
			}
			}
		}

		public override int GetHashCode()
		{
			if (_bits == null)
			{
				return _sign;
			}
			int num = _sign;
			int num2 = _bits.Length;
			while (--num2 >= 0)
			{
				num = NumericsHelpers.CombineHash(num, (int)_bits[num2]);
			}
			return num;
		}

		public override bool Equals(object obj)
		{
			if (!(obj is BigInteger))
			{
				return false;
			}
			return Equals((BigInteger)obj);
		}

		public bool Equals(long other)
		{
			if (_bits == null)
			{
				return _sign == other;
			}
			int num;
			if ((_sign ^ other) < 0 || (num = _bits.Length) > 2)
			{
				return false;
			}
			ulong num2 = (ulong)((other < 0) ? (-other) : other);
			if (num == 1)
			{
				return _bits[0] == num2;
			}
			return NumericsHelpers.MakeUlong(_bits[1], _bits[0]) == num2;
		}

		[CLSCompliant(false)]
		public bool Equals(ulong other)
		{
			if (_sign < 0)
			{
				return false;
			}
			if (_bits == null)
			{
				return (ulong)_sign == other;
			}
			int num = _bits.Length;
			if (num > 2)
			{
				return false;
			}
			if (num == 1)
			{
				return _bits[0] == other;
			}
			return NumericsHelpers.MakeUlong(_bits[1], _bits[0]) == other;
		}

		public bool Equals(BigInteger other)
		{
			if (_sign != other._sign)
			{
				return false;
			}
			if (_bits == other._bits)
			{
				return true;
			}
			if (_bits == null || other._bits == null)
			{
				return false;
			}
			int num = _bits.Length;
			if (num != other._bits.Length)
			{
				return false;
			}
			int diffLength = GetDiffLength(_bits, other._bits, num);
			return diffLength == 0;
		}

		public int CompareTo(long other)
		{
			if (_bits == null)
			{
				return ((long)_sign).CompareTo(other);
			}
			int num;
			if ((_sign ^ other) < 0 || (num = _bits.Length) > 2)
			{
				return _sign;
			}
			ulong num2 = (ulong)((other < 0) ? (-other) : other);
			ulong num3 = ((num == 2) ? NumericsHelpers.MakeUlong(_bits[1], _bits[0]) : _bits[0]);
			return _sign * num3.CompareTo(num2);
		}

		[CLSCompliant(false)]
		public int CompareTo(ulong other)
		{
			if (_sign < 0)
			{
				return -1;
			}
			if (_bits == null)
			{
				return ((ulong)_sign).CompareTo(other);
			}
			int num = _bits.Length;
			if (num > 2)
			{
				return 1;
			}
			return ((num == 2) ? NumericsHelpers.MakeUlong(_bits[1], _bits[0]) : _bits[0]).CompareTo(other);
		}

		public int CompareTo(BigInteger other)
		{
			if ((_sign ^ other._sign) < 0)
			{
				if (_sign >= 0)
				{
					return 1;
				}
				return -1;
			}
			if (_bits == null)
			{
				if (other._bits == null)
				{
					if (_sign >= other._sign)
					{
						if (_sign <= other._sign)
						{
							return 0;
						}
						return 1;
					}
					return -1;
				}
				return -other._sign;
			}
			int num;
			int num2;
			if (other._bits == null || (num = _bits.Length) > (num2 = other._bits.Length))
			{
				return _sign;
			}
			if (num < num2)
			{
				return -_sign;
			}
			int diffLength = GetDiffLength(_bits, other._bits, num);
			if (diffLength == 0)
			{
				return 0;
			}
			if (_bits[diffLength - 1] >= other._bits[diffLength - 1])
			{
				return _sign;
			}
			return -_sign;
		}

		int IComparable.CompareTo(object obj)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (obj == null)
			{
				return 1;
			}
			if (!(obj is BigInteger))
			{
				throw new ArgumentException(SR.Argument_MustBeBigInt, "obj");
			}
			return CompareTo((BigInteger)obj);
		}

		public byte[] ToByteArray()
		{
			int sign = _sign;
			if (sign == 0)
			{
				return new byte[1];
			}
			int i = 0;
			uint[] bits = _bits;
			byte b;
			uint num;
			if (bits == null)
			{
				b = (byte)((sign < 0) ? 255u : 0u);
				num = (uint)sign;
			}
			else if (sign == -1)
			{
				b = 255;
				for (; bits[i] == 0; i++)
				{
				}
				num = ~bits[bits.Length - 1];
				if (bits.Length - 1 == i)
				{
					num++;
				}
			}
			else
			{
				b = 0;
				num = bits[bits.Length - 1];
			}
			byte b2;
			int num2;
			if ((b2 = (byte)(num >> 24)) != b)
			{
				num2 = 3;
			}
			else if ((b2 = (byte)(num >> 16)) != b)
			{
				num2 = 2;
			}
			else if ((b2 = (byte)(num >> 8)) != b)
			{
				num2 = 1;
			}
			else
			{
				b2 = (byte)num;
				num2 = 0;
			}
			bool flag = (b2 & 0x80) != (b & 0x80);
			int num3 = 0;
			byte[] array;
			if (bits == null)
			{
				array = new byte[num2 + 1 + (flag ? 1 : 0)];
			}
			else
			{
				array = new byte[checked(4 * (bits.Length - 1) + num2 + 1 + (flag ? 1 : 0))];
				for (int j = 0; j < bits.Length - 1; j++)
				{
					uint num4 = bits[j];
					if (sign == -1)
					{
						num4 = ~num4;
						if (j <= i)
						{
							num4++;
						}
					}
					for (int k = 0; k < 4; k++)
					{
						array[num3++] = (byte)num4;
						num4 >>= 8;
					}
				}
			}
			for (int l = 0; l <= num2; l++)
			{
				array[num3++] = (byte)num;
				num >>= 8;
			}
			if (flag)
			{
				array[array.Length - 1] = b;
			}
			return array;
		}

		private uint[] ToUInt32Array()
		{
			if (_bits == null && _sign == 0)
			{
				return new uint[1];
			}
			uint[] array;
			uint num;
			if (_bits == null)
			{
				array = new uint[1] { (uint)_sign };
				num = ((_sign < 0) ? 4294967295u : 0u);
			}
			else if (_sign == -1)
			{
				array = (uint[])((System.Array)_bits).Clone();
				NumericsHelpers.DangerousMakeTwosComplement(array);
				num = 4294967295u;
			}
			else
			{
				array = _bits;
				num = 0u;
			}
			int num2 = array.Length - 1;
			while (num2 > 0 && array[num2] == num)
			{
				num2--;
			}
			bool flag = (array[num2] & 0x80000000u) != (num & 0x80000000u);
			uint[] array2 = new uint[num2 + 1 + (flag ? 1 : 0)];
			System.Array.Copy((System.Array)array, 0, (System.Array)array2, 0, num2 + 1);
			if (flag)
			{
				array2[array2.Length - 1] = num;
			}
			return array2;
		}

		public override string ToString()
		{
			return BigNumber.FormatBigInteger(this, null, NumberFormatInfo.CurrentInfo);
		}

		public string ToString(IFormatProvider provider)
		{
			return BigNumber.FormatBigInteger(this, null, NumberFormatInfo.GetInstance(provider));
		}

		public string ToString(string format)
		{
			return BigNumber.FormatBigInteger(this, format, NumberFormatInfo.CurrentInfo);
		}

		public string ToString(string format, IFormatProvider provider)
		{
			return BigNumber.FormatBigInteger(this, format, NumberFormatInfo.GetInstance(provider));
		}

		private static BigInteger Add(uint[] leftBits, int leftSign, uint[] rightBits, int rightSign)
		{
			bool flag = leftBits == null;
			bool flag2 = rightBits == null;
			if (flag && flag2)
			{
				return (long)leftSign + (long)rightSign;
			}
			if (flag)
			{
				uint[] value = BigIntegerCalculator.Add(rightBits, NumericsHelpers.Abs(leftSign));
				return new BigInteger(value, leftSign < 0);
			}
			if (flag2)
			{
				uint[] value2 = BigIntegerCalculator.Add(leftBits, NumericsHelpers.Abs(rightSign));
				return new BigInteger(value2, leftSign < 0);
			}
			if (leftBits.Length < rightBits.Length)
			{
				uint[] value3 = BigIntegerCalculator.Add(rightBits, leftBits);
				return new BigInteger(value3, leftSign < 0);
			}
			uint[] value4 = BigIntegerCalculator.Add(leftBits, rightBits);
			return new BigInteger(value4, leftSign < 0);
		}

		public static BigInteger operator -(BigInteger left, BigInteger right)
		{
			if (left._sign < 0 != right._sign < 0)
			{
				return Add(left._bits, left._sign, right._bits, -1 * right._sign);
			}
			return Subtract(left._bits, left._sign, right._bits, right._sign);
		}

		private static BigInteger Subtract(uint[] leftBits, int leftSign, uint[] rightBits, int rightSign)
		{
			bool flag = leftBits == null;
			bool flag2 = rightBits == null;
			if (flag && flag2)
			{
				return (long)leftSign - (long)rightSign;
			}
			if (flag)
			{
				uint[] value = BigIntegerCalculator.Subtract(rightBits, NumericsHelpers.Abs(leftSign));
				return new BigInteger(value, leftSign >= 0);
			}
			if (flag2)
			{
				uint[] value2 = BigIntegerCalculator.Subtract(leftBits, NumericsHelpers.Abs(rightSign));
				return new BigInteger(value2, leftSign < 0);
			}
			if (BigIntegerCalculator.Compare(leftBits, rightBits) < 0)
			{
				uint[] value3 = BigIntegerCalculator.Subtract(rightBits, leftBits);
				return new BigInteger(value3, leftSign >= 0);
			}
			uint[] value4 = BigIntegerCalculator.Subtract(leftBits, rightBits);
			return new BigInteger(value4, leftSign < 0);
		}

		public static implicit operator BigInteger(byte value)
		{
			return new BigInteger(value);
		}

		[CLSCompliant(false)]
		public static implicit operator BigInteger(sbyte value)
		{
			return new BigInteger(value);
		}

		public static implicit operator BigInteger(short value)
		{
			return new BigInteger(value);
		}

		[CLSCompliant(false)]
		public static implicit operator BigInteger(ushort value)
		{
			return new BigInteger(value);
		}

		public static implicit operator BigInteger(int value)
		{
			return new BigInteger(value);
		}

		[CLSCompliant(false)]
		public static implicit operator BigInteger(uint value)
		{
			return new BigInteger(value);
		}

		public static implicit operator BigInteger(long value)
		{
			return new BigInteger(value);
		}

		[CLSCompliant(false)]
		public static implicit operator BigInteger(ulong value)
		{
			return new BigInteger(value);
		}

		public static explicit operator BigInteger(float value)
		{
			return new BigInteger(value);
		}

		public static explicit operator BigInteger(double value)
		{
			return new BigInteger(value);
		}

		public static explicit operator BigInteger(decimal value)
		{
			return new BigInteger(value);
		}

		public static explicit operator byte(BigInteger value)
		{
			return checked((byte)(int)value);
		}

		[CLSCompliant(false)]
		public static explicit operator sbyte(BigInteger value)
		{
			return checked((sbyte)(int)value);
		}

		public static explicit operator short(BigInteger value)
		{
			return checked((short)(int)value);
		}

		[CLSCompliant(false)]
		public static explicit operator ushort(BigInteger value)
		{
			return checked((ushort)(int)value);
		}

		public static explicit operator int(BigInteger value)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (value._bits == null)
			{
				return value._sign;
			}
			if (value._bits.Length > 1)
			{
				throw new OverflowException(SR.Overflow_Int32);
			}
			if (value._sign > 0)
			{
				return checked((int)value._bits[0]);
			}
			if (value._bits[0] > 2147483648u)
			{
				throw new OverflowException(SR.Overflow_Int32);
			}
			return (int)(0 - value._bits[0]);
		}

		[CLSCompliant(false)]
		public static explicit operator uint(BigInteger value)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (value._bits == null)
			{
				return checked((uint)value._sign);
			}
			if (value._bits.Length > 1 || value._sign < 0)
			{
				throw new OverflowException(SR.Overflow_UInt32);
			}
			return value._bits[0];
		}

		public static explicit operator long(BigInteger value)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			if (value._bits == null)
			{
				return value._sign;
			}
			int num = value._bits.Length;
			if (num > 2)
			{
				throw new OverflowException(SR.Overflow_Int64);
			}
			ulong num2 = ((num <= 1) ? value._bits[0] : NumericsHelpers.MakeUlong(value._bits[1], value._bits[0]));
			long num3 = (long)((value._sign > 0) ? num2 : (0L - num2));
			if ((num3 > 0 && value._sign > 0) || (num3 < 0 && value._sign < 0))
			{
				return num3;
			}
			throw new OverflowException(SR.Overflow_Int64);
		}

		[CLSCompliant(false)]
		public static explicit operator ulong(BigInteger value)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (value._bits == null)
			{
				return checked((ulong)value._sign);
			}
			int num = value._bits.Length;
			if (num > 2 || value._sign < 0)
			{
				throw new OverflowException(SR.Overflow_UInt64);
			}
			if (num > 1)
			{
				return NumericsHelpers.MakeUlong(value._bits[1], value._bits[0]);
			}
			return value._bits[0];
		}

		public static explicit operator float(BigInteger value)
		{
			return (float)(double)value;
		}

		public static explicit operator double(BigInteger value)
		{
			int sign = value._sign;
			uint[] bits = value._bits;
			if (bits == null)
			{
				return sign;
			}
			int num = bits.Length;
			if (num > 32)
			{
				if (sign == 1)
				{
					return 1.0 / 0.0;
				}
				return -1.0 / 0.0;
			}
			ulong num2 = bits[num - 1];
			ulong num3 = ((num > 1) ? bits[num - 2] : 0u);
			ulong num4 = ((num > 2) ? bits[num - 3] : 0u);
			int num5 = NumericsHelpers.CbitHighZero((uint)num2);
			int exp = (num - 2) * 32 - num5;
			ulong man = (num2 << 32 + num5) | (num3 << num5) | (num4 >> 32 - num5);
			return NumericsHelpers.GetDoubleFromParts(sign, exp, man);
		}

		public static explicit operator decimal(BigInteger value)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (value._bits == null)
			{
				return decimal.op_Implicit(value._sign);
			}
			int num = value._bits.Length;
			if (num > 3)
			{
				throw new OverflowException(SR.Overflow_Decimal);
			}
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			if (num > 2)
			{
				num4 = (int)value._bits[2];
			}
			if (num > 1)
			{
				num3 = (int)value._bits[1];
			}
			if (num > 0)
			{
				num2 = (int)value._bits[0];
			}
			return new decimal(num2, num3, num4, value._sign < 0, (byte)0);
		}

		public static BigInteger operator &(BigInteger left, BigInteger right)
		{
			if (left.IsZero || right.IsZero)
			{
				return Zero;
			}
			uint[] array = left.ToUInt32Array();
			uint[] array2 = right.ToUInt32Array();
			uint[] array3 = new uint[Math.Max(array.Length, array2.Length)];
			uint num = ((left._sign < 0) ? 4294967295u : 0u);
			uint num2 = ((right._sign < 0) ? 4294967295u : 0u);
			for (int i = 0; i < array3.Length; i++)
			{
				uint num3 = ((i < array.Length) ? array[i] : num);
				uint num4 = ((i < array2.Length) ? array2[i] : num2);
				array3[i] = num3 & num4;
			}
			return new BigInteger(array3);
		}

		public static BigInteger operator |(BigInteger left, BigInteger right)
		{
			if (left.IsZero)
			{
				return right;
			}
			if (right.IsZero)
			{
				return left;
			}
			uint[] array = left.ToUInt32Array();
			uint[] array2 = right.ToUInt32Array();
			uint[] array3 = new uint[Math.Max(array.Length, array2.Length)];
			uint num = ((left._sign < 0) ? 4294967295u : 0u);
			uint num2 = ((right._sign < 0) ? 4294967295u : 0u);
			for (int i = 0; i < array3.Length; i++)
			{
				uint num3 = ((i < array.Length) ? array[i] : num);
				uint num4 = ((i < array2.Length) ? array2[i] : num2);
				array3[i] = num3 | num4;
			}
			return new BigInteger(array3);
		}

		public static BigInteger operator ^(BigInteger left, BigInteger right)
		{
			uint[] array = left.ToUInt32Array();
			uint[] array2 = right.ToUInt32Array();
			uint[] array3 = new uint[Math.Max(array.Length, array2.Length)];
			uint num = ((left._sign < 0) ? 4294967295u : 0u);
			uint num2 = ((right._sign < 0) ? 4294967295u : 0u);
			for (int i = 0; i < array3.Length; i++)
			{
				uint num3 = ((i < array.Length) ? array[i] : num);
				uint num4 = ((i < array2.Length) ? array2[i] : num2);
				array3[i] = num3 ^ num4;
			}
			return new BigInteger(array3);
		}

		public static BigInteger operator <<(BigInteger value, int shift)
		{
			if (shift == 0)
			{
				return value;
			}
			if (shift == -2147483648)
			{
				return value >> 2147483647 >> 1;
			}
			if (shift < 0)
			{
				return value >> -shift;
			}
			int num = shift / 32;
			int num2 = shift - num * 32;
			uint[] xd;
			int xl;
			bool partsForBitManipulation = GetPartsForBitManipulation(ref value, out xd, out xl);
			int num3 = xl + num + 1;
			uint[] array = new uint[num3];
			if (num2 == 0)
			{
				for (int i = 0; i < xl; i++)
				{
					array[i + num] = xd[i];
				}
			}
			else
			{
				int num4 = 32 - num2;
				uint num5 = 0u;
				int j;
				for (j = 0; j < xl; j++)
				{
					uint num6 = xd[j];
					array[j + num] = (num6 << num2) | num5;
					num5 = num6 >> num4;
				}
				array[j + num] = num5;
			}
			return new BigInteger(array, partsForBitManipulation);
		}

		public static BigInteger operator >>(BigInteger value, int shift)
		{
			if (shift == 0)
			{
				return value;
			}
			if (shift == -2147483648)
			{
				return value << 2147483647 << 1;
			}
			if (shift < 0)
			{
				return value << -shift;
			}
			int num = shift / 32;
			int num2 = shift - num * 32;
			uint[] xd;
			int xl;
			bool partsForBitManipulation = GetPartsForBitManipulation(ref value, out xd, out xl);
			if (partsForBitManipulation)
			{
				if (shift >= 32 * xl)
				{
					return MinusOne;
				}
				uint[] array = new uint[xl];
				System.Array.Copy((System.Array)xd, 0, (System.Array)array, 0, xl);
				xd = array;
				NumericsHelpers.DangerousMakeTwosCompl

System.Security.Cryptography.OpenSsl.dll

Decompiled a month ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Security.Cryptography.OpenSsl")]
[assembly: AssemblyDescription("System.Security.Cryptography.OpenSsl")]
[assembly: AssemblyDefaultAlias("System.Security.Cryptography.OpenSsl")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyFileVersion("1.0.24212.01")]
[assembly: AssemblyInformationalVersion("1.0.24212.01. Commit Hash: 9688ddbb62c04189cac4c4a06e31e93377dccd41")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("NotSupported", "True")]
[assembly: AssemblyVersion("4.0.0.0")]
namespace System.Security.Cryptography;

public sealed class ECDsaOpenSsl : ECDsa
{
	public override int KeySize
	{
		get
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			throw new PlatformNotSupportedException();
		}
		set
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			throw new PlatformNotSupportedException();
		}
	}

	public override KeySizes[] LegalKeySizes
	{
		get
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			throw new PlatformNotSupportedException();
		}
	}

	public ECDsaOpenSsl()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public ECDsaOpenSsl(int keySize)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public ECDsaOpenSsl(System.IntPtr handle)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public ECDsaOpenSsl(ECCurve curve)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public ECDsaOpenSsl(SafeEvpPKeyHandle pkeyHandle)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	protected override void Dispose(bool disposing)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public SafeEvpPKeyHandle DuplicateKeyHandle()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override ECParameters ExportExplicitParameters(bool includePrivateParameters)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override ECParameters ExportParameters(bool includePrivateParameters)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override void GenerateKey(ECCurve curve)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override void ImportParameters(ECParameters parameters)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override byte[] SignHash(byte[] hash)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override bool VerifyHash(byte[] hash, byte[] signature)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}
}
public sealed class RSAOpenSsl : RSA
{
	public override int KeySize
	{
		set
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			throw new PlatformNotSupportedException();
		}
	}

	public override KeySizes[] LegalKeySizes
	{
		get
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			throw new PlatformNotSupportedException();
		}
	}

	public RSAOpenSsl()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public RSAOpenSsl(int keySize)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public RSAOpenSsl(System.IntPtr handle)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public RSAOpenSsl(RSAParameters parameters)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public RSAOpenSsl(SafeEvpPKeyHandle pkeyHandle)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	protected override void Dispose(bool disposing)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public SafeEvpPKeyHandle DuplicateKeyHandle()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override RSAParameters ExportParameters(bool includePrivateParameters)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override void ImportParameters(RSAParameters parameters)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}
}
public sealed class SafeEvpPKeyHandle : SafeHandle
{
	public override bool IsInvalid
	{
		get
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			throw new PlatformNotSupportedException();
		}
	}

	public SafeEvpPKeyHandle(System.IntPtr handle, bool ownsHandle)
		: base((System.IntPtr)0, false)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	public SafeEvpPKeyHandle DuplicateHandle()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}

	protected override bool ReleaseHandle()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		throw new PlatformNotSupportedException();
	}
}

System.Text.Encodings.Web.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading;
using FxResources.System.Text.Encodings.Web;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Text.Encodings.Web")]
[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("Provides types for encoding and escaping strings for use in JavaScript, HyperText Markup Language (HTML), and uniform resource locators (URL).\r\n\r\nCommonly Used Types:\r\nSystem.Text.Encodings.Web.HtmlEncoder\r\nSystem.Text.Encodings.Web.UrlEncoder\r\nSystem.Text.Encodings.Web.JavaScriptEncoder")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Text.Encodings.Web")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
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]
	internal sealed class IsByRefLikeAttribute : 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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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.Text.Encodings.Web
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				ToCharsBuffer(bytes[i], chars, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan());
			Span<char> buffer = span;
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				ToCharsBuffer(readOnlySpan[i], buffer, num, casing);
				num += 2;
			}
			return buffer.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			return TryDecodeFromUtf16_Scalar(chars, bytes, out charsProcessed);
		}

		private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < bytes.Length)
			{
				num3 = FromChar(chars[num + 1]);
				num4 = FromChar(chars[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				bytes[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				long num2 = -17875860044349952L << (int)num;
				ulong num3 = num - 64;
				return (long)((ulong)num2 & num3) < 0L;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string TextEncoderDoesNotImplementMaxOutputCharsPerInputChar => GetResourceString("TextEncoderDoesNotImplementMaxOutputCharsPerInputChar");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.Numerics
{
	internal static class BitOperations
	{
		private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32]
		{
			0, 9, 1, 10, 13, 21, 2, 29, 11, 14,
			16, 18, 22, 25, 3, 30, 8, 12, 20, 28,
			15, 17, 24, 7, 19, 27, 23, 6, 26, 5,
			4, 31
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int Log2(uint value)
		{
			return Log2SoftwareFallback(value | 1u);
		}

		private static int Log2SoftwareFallback(uint value)
		{
			value |= value >> 1;
			value |= value >> 2;
			value |= value >> 4;
			value |= value >> 8;
			value |= value >> 16;
			return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (nint)(value * 130329821 >> 27));
		}
	}
}
namespace System.Text
{
	internal static class UnicodeDebug
	{
		[Conditional("DEBUG")]
		internal static void AssertIsBmpCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsBmpCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsHighSurrogateCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsHighSurrogateCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsLowSurrogateCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsLowSurrogateCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsValidCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsValidCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsValidScalar(uint scalarValue)
		{
			System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsValidSupplementaryPlaneScalar(uint scalarValue)
		{
			if (System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue))
			{
				System.Text.UnicodeUtility.IsBmpCodePoint(scalarValue);
			}
		}

		private static string ToHexString(uint codePoint)
		{
			return FormattableString.Invariant($"U+{codePoint:X4}");
		}
	}
	internal static class UnicodeUtility
	{
		public const uint ReplacementChar = 65533u;

		public static int GetPlane(uint codePoint)
		{
			return (int)(codePoint >> 16);
		}

		public static uint GetScalarFromUtf16SurrogatePair(uint highSurrogateCodePoint, uint lowSurrogateCodePoint)
		{
			return (highSurrogateCodePoint << 10) + lowSurrogateCodePoint - 56613888;
		}

		public static int GetUtf16SequenceLength(uint value)
		{
			value -= 65536;
			value += 33554432;
			value >>= 24;
			return (int)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void GetUtf16SurrogatesFromSupplementaryPlaneScalar(uint value, out char highSurrogateCodePoint, out char lowSurrogateCodePoint)
		{
			highSurrogateCodePoint = (char)(value + 56557568 >> 10);
			lowSurrogateCodePoint = (char)((value & 0x3FF) + 56320);
		}

		public static int GetUtf8SequenceLength(uint value)
		{
			int num = (int)(value - 2048) >> 31;
			value ^= 0xF800u;
			value -= 63616;
			value += 67108864;
			value >>= 24;
			return (int)value + num * 2;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsAsciiCodePoint(uint value)
		{
			return value <= 127;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsBmpCodePoint(uint value)
		{
			return value <= 65535;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHighSurrogateCodePoint(uint value)
		{
			return IsInRangeInclusive(value, 55296u, 56319u);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound)
		{
			return value - lowerBound <= upperBound - lowerBound;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsLowSurrogateCodePoint(uint value)
		{
			return IsInRangeInclusive(value, 56320u, 57343u);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsSurrogateCodePoint(uint value)
		{
			return IsInRangeInclusive(value, 55296u, 57343u);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsValidCodePoint(uint codePoint)
		{
			return codePoint <= 1114111;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsValidUnicodeScalar(uint value)
		{
			return ((value - 1114112) ^ 0xD800) >= 4293855232u;
		}
	}
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public unsafe void Append(char* value, int length)
		{
			if (_pos > _chars.Length - length)
			{
				Grow(length);
			}
			Span<char> span = _chars.Slice(_pos, length);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = *(value++);
			}
			_pos += length;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
	internal readonly struct Rune : IEquatable<Rune>
	{
		private const int MaxUtf16CharsPerRune = 2;

		private const char HighSurrogateStart = '\ud800';

		private const char LowSurrogateStart = '\udc00';

		private const int HighSurrogateRange = 1023;

		private readonly uint _value;

		public bool IsAscii => System.Text.UnicodeUtility.IsAsciiCodePoint(_value);

		public bool IsBmp => System.Text.UnicodeUtility.IsBmpCodePoint(_value);

		public static Rune ReplacementChar => UnsafeCreate(65533u);

		public int Utf16SequenceLength => System.Text.UnicodeUtility.GetUtf16SequenceLength(_value);

		public int Value => (int)_value;

		public Rune(uint value)
		{
			if (!System.Text.UnicodeUtility.IsValidUnicodeScalar(value))
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
			}
			_value = value;
		}

		public Rune(int value)
			: this((uint)value)
		{
		}

		private Rune(uint scalarValue, bool _)
		{
			_value = scalarValue;
		}

		public static bool operator ==(Rune left, Rune right)
		{
			return left._value == right._value;
		}

		public static bool operator !=(Rune left, Rune right)
		{
			return left._value != right._value;
		}

		public static bool IsControl(Rune value)
		{
			return ((value._value + 1) & 0xFFFFFF7Fu) <= 32;
		}

		public static OperationStatus DecodeFromUtf16(ReadOnlySpan<char> source, out Rune result, out int charsConsumed)
		{
			if (!source.IsEmpty)
			{
				char c = source[0];
				if (TryCreate(c, out result))
				{
					charsConsumed = 1;
					return OperationStatus.Done;
				}
				if (1u < (uint)source.Length)
				{
					char lowSurrogate = source[1];
					if (TryCreate(c, lowSurrogate, out result))
					{
						charsConsumed = 2;
						return OperationStatus.Done;
					}
				}
				else if (char.IsHighSurrogate(c))
				{
					goto IL_004c;
				}
				charsConsumed = 1;
				result = ReplacementChar;
				return OperationStatus.InvalidData;
			}
			goto IL_004c;
			IL_004c:
			charsConsumed = source.Length;
			result = ReplacementChar;
			return OperationStatus.NeedMoreData;
		}

		public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> source, out Rune result, out int bytesConsumed)
		{
			int num = 0;
			uint num2;
			if ((uint)num < (uint)source.Length)
			{
				num2 = source[num];
				if (System.Text.UnicodeUtility.IsAsciiCodePoint(num2))
				{
					goto IL_0021;
				}
				if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 194u, 244u))
				{
					num2 = num2 - 194 << 6;
					num++;
					if ((uint)num >= (uint)source.Length)
					{
						goto IL_0163;
					}
					int num3 = (sbyte)source[num];
					if (num3 < -64)
					{
						num2 += (uint)num3;
						num2 += 128;
						num2 += 128;
						if (num2 < 2048)
						{
							goto IL_0021;
						}
						if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2080u, 3343u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2912u, 2943u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 3072u, 3087u))
						{
							num++;
							if ((uint)num >= (uint)source.Length)
							{
								goto IL_0163;
							}
							num3 = (sbyte)source[num];
							if (num3 < -64)
							{
								num2 <<= 6;
								num2 += (uint)num3;
								num2 += 128;
								num2 -= 131072;
								if (num2 > 65535)
								{
									num++;
									if ((uint)num >= (uint)source.Length)
									{
										goto IL_0163;
									}
									num3 = (sbyte)source[num];
									if (num3 >= -64)
									{
										goto IL_0153;
									}
									num2 <<= 6;
									num2 += (uint)num3;
									num2 += 128;
									num2 -= 4194304;
								}
								goto IL_0021;
							}
						}
					}
				}
				else
				{
					num = 1;
				}
				goto IL_0153;
			}
			goto IL_0163;
			IL_0021:
			bytesConsumed = num + 1;
			result = UnsafeCreate(num2);
			return OperationStatus.Done;
			IL_0153:
			bytesConsumed = num;
			result = ReplacementChar;
			return OperationStatus.InvalidData;
			IL_0163:
			bytesConsumed = num;
			result = ReplacementChar;
			return OperationStatus.NeedMoreData;
		}

		public override bool Equals([NotNullWhen(true)] object obj)
		{
			if (obj is Rune other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(Rune other)
		{
			return this == other;
		}

		public override int GetHashCode()
		{
			return Value;
		}

		public static bool TryCreate(char ch, out Rune result)
		{
			if (!System.Text.UnicodeUtility.IsSurrogateCodePoint(ch))
			{
				result = UnsafeCreate(ch);
				return true;
			}
			result = default(Rune);
			return false;
		}

		public static bool TryCreate(char highSurrogate, char lowSurrogate, out Rune result)
		{
			uint num = (uint)(highSurrogate - 55296);
			uint num2 = (uint)(lowSurrogate - 56320);
			if ((num | num2) <= 1023)
			{
				result = UnsafeCreate((uint)((int)(num << 10) + (lowSurrogate - 56320) + 65536));
				return true;
			}
			result = default(Rune);
			return false;
		}

		public bool TryEncodeToUtf16(Span<char> destination, out int charsWritten)
		{
			if (destination.Length >= 1)
			{
				if (IsBmp)
				{
					destination[0] = (char)_value;
					charsWritten = 1;
					return true;
				}
				if (destination.Length >= 2)
				{
					System.Text.UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out destination[0], out destination[1]);
					charsWritten = 2;
					return true;
				}
			}
			charsWritten = 0;
			return false;
		}

		public bool TryEncodeToUtf8(Span<byte> destination, out int bytesWritten)
		{
			if (destination.Length >= 1)
			{
				if (IsAscii)
				{
					destination[0] = (byte)_value;
					bytesWritten = 1;
					return true;
				}
				if (destination.Length >= 2)
				{
					if (_value <= 2047)
					{
						destination[0] = (byte)(_value + 12288 >> 6);
						destination[1] = (byte)((_value & 0x3F) + 128);
						bytesWritten = 2;
						return true;
					}
					if (destination.Length >= 3)
					{
						if (_value <= 65535)
						{
							destination[0] = (byte)(_value + 917504 >> 12);
							destination[1] = (byte)(((_value & 0xFC0) >> 6) + 128);
							destination[2] = (byte)((_value & 0x3F) + 128);
							bytesWritten = 3;
							return true;
						}
						if (destination.Length >= 4)
						{
							destination[0] = (byte)(_value + 62914560 >> 18);
							destination[1] = (byte)(((_value & 0x3F000) >> 12) + 128);
							destination[2] = (byte)(((_value & 0xFC0) >> 6) + 128);
							destination[3] = (byte)((_value & 0x3F) + 128);
							bytesWritten = 4;
							return true;
						}
					}
				}
			}
			bytesWritten = 0;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static Rune UnsafeCreate(uint scalarValue)
		{
			return new Rune(scalarValue, _: false);
		}
	}
}
namespace System.Text.Unicode
{
	internal static class UnicodeHelpers
	{
		internal const int UNICODE_LAST_CODEPOINT = 1114111;

		private static ReadOnlySpan<byte> DefinedCharsBitmapSpan => new byte[8192]
		{
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 127, 0, 0, 0, 0,
			254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 252, 240, 215, 255, 255, 251, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 254, 255, 255, 255,
			127, 254, 255, 255, 255, 255, 255, 231, 254, 255,
			255, 255, 255, 255, 255, 0, 255, 255, 255, 135,
			31, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 191, 255, 255, 255, 255,
			255, 255, 255, 231, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 3, 0, 255, 255,
			255, 255, 255, 255, 255, 231, 255, 255, 255, 255,
			255, 63, 255, 127, 255, 255, 255, 79, 255, 7,
			255, 255, 255, 127, 3, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 239, 159, 249, 255, 255, 253,
			197, 243, 159, 121, 128, 176, 207, 255, 255, 127,
			238, 135, 249, 255, 255, 253, 109, 211, 135, 57,
			2, 94, 192, 255, 127, 0, 238, 191, 251, 255,
			255, 253, 237, 243, 191, 59, 1, 0, 207, 255,
			3, 254, 238, 159, 249, 255, 255, 253, 237, 243,
			159, 57, 224, 176, 207, 255, 255, 0, 236, 199,
			61, 214, 24, 199, 255, 195, 199, 61, 129, 0,
			192, 255, 255, 7, 255, 223, 253, 255, 255, 253,
			255, 243, 223, 61, 96, 39, 207, 255, 128, 255,
			255, 223, 253, 255, 255, 253, 239, 243, 223, 61,
			96, 96, 207, 255, 14, 0, 255, 223, 253, 255,
			255, 255, 255, 255, 223, 253, 240, 255, 207, 255,
			255, 255, 238, 255, 127, 252, 255, 255, 251, 47,
			127, 132, 95, 255, 192, 255, 28, 0, 254, 255,
			255, 255, 255, 255, 255, 135, 255, 255, 255, 15,
			0, 0, 0, 0, 214, 247, 255, 255, 175, 255,
			255, 63, 95, 127, 255, 243, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 254,
			255, 255, 255, 31, 254, 255, 255, 255, 255, 254,
			255, 255, 255, 223, 255, 223, 255, 7, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 191, 32, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 61, 127, 61, 255, 255,
			255, 255, 255, 61, 255, 255, 255, 255, 61, 127,
			61, 255, 127, 255, 255, 255, 255, 255, 255, 255,
			61, 255, 255, 255, 255, 255, 255, 255, 255, 231,
			255, 255, 255, 31, 255, 255, 255, 3, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 63, 63,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			254, 255, 255, 31, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 1, 255, 255, 63, 128,
			255, 255, 127, 0, 255, 255, 15, 0, 255, 223,
			13, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 63, 255, 3, 255, 3, 255, 255,
			255, 3, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 1, 255, 255, 255, 255, 255, 7,
			255, 255, 255, 255, 255, 255, 255, 255, 63, 0,
			255, 255, 255, 127, 255, 15, 255, 15, 241, 255,
			255, 255, 255, 63, 31, 0, 255, 255, 255, 255,
			255, 15, 255, 255, 255, 3, 255, 199, 255, 255,
			255, 255, 255, 255, 255, 207, 255, 255, 255, 255,
			255, 255, 255, 127, 255, 255, 255, 159, 255, 3,
			255, 3, 255, 63, 255, 255, 255, 127, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 31, 255, 255, 255, 255, 255, 127,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 15, 240, 255, 255, 255, 255,
			255, 255, 255, 248, 255, 227, 255, 255, 255, 255,
			255, 255, 255, 1, 255, 255, 255, 255, 255, 231,
			255, 0, 255, 255, 255, 255, 255, 7, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 63, 63, 255, 255, 255, 255,
			63, 63, 255, 170, 255, 255, 255, 63, 255, 255,
			255, 255, 255, 255, 223, 255, 223, 255, 207, 239,
			255, 255, 220, 127, 0, 248, 255, 255, 255, 124,
			255, 255, 255, 255, 255, 127, 223, 255, 243, 255,
			255, 127, 255, 31, 255, 255, 255, 255, 1, 0,
			255, 255, 255, 255, 1, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 15, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 127, 0, 0, 0,
			255, 7, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			207, 255, 255, 255, 191, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 15, 254,
			255, 255, 255, 255, 191, 32, 255, 255, 255, 255,
			255, 255, 255, 128, 1, 128, 255, 255, 127, 0,
			127, 127, 127, 127, 127, 127, 127, 127, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 63, 0, 0, 0, 0, 255, 255,
			255, 251, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 15, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			63, 0, 0, 0, 255, 15, 254, 255, 255, 255,
			255, 255, 255, 255, 254, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 127, 254, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 224, 255,
			255, 255, 255, 255, 254, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 127, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 15, 0, 255, 255,
			255, 255, 255, 127, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 31, 255, 255, 255, 255,
			255, 255, 127, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 15, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 7,
			235, 3, 0, 0, 252, 255, 255, 255, 255, 255,
			255, 31, 255, 3, 255, 255, 255, 255, 255, 255,
			255, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			63, 192, 255, 3, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 15, 128,
			255, 255, 255, 31, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 191, 255, 195, 255, 255, 255, 127,
			255, 255, 255, 255, 255, 255, 127, 0, 255, 63,
			255, 243, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 7, 0, 0, 248, 255, 255,
			127, 0, 126, 126, 126, 0, 127, 127, 255, 255,
			255, 255, 255, 255, 255, 15, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 63, 255, 3, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			15, 0, 255, 255, 127, 248, 255, 255, 255, 255,
			255, 15, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 63, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 3, 0, 0,
			0, 0, 127, 0, 248, 224, 255, 255, 127, 95,
			219, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 7, 0, 248, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 252, 255, 255, 255, 255, 255,
			255, 128, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 3, 255, 255, 255, 255, 255, 255, 247, 255,
			127, 15, 223, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 31,
			254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 127, 252, 252, 252, 28, 127, 127,
			0, 62
		};

		internal static ReadOnlySpan<byte> GetDefinedBmpCodePointsBitmapLittleEndian()
		{
			return DefinedCharsBitmapSpan;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static void GetUtf16SurrogatePairFromAstralScalarValue(uint scalar, out char highSurrogate, out char lowSurrogate)
		{
			highSurrogate = (char)(scalar + 56557568 >> 10);
			lowSurrogate = (char)((scalar & 0x3FF) + 56320);
		}

		internal static int GetUtf8RepresentationForScalarValue(uint scalar)
		{
			if (scalar <= 127)
			{
				return (byte)scalar;
			}
			if (scalar <= 2047)
			{
				byte b = (byte)(0xC0u | (scalar >> 6));
				return ((byte)(0x80 | (scalar & 0x3F)) << 8) | b;
			}
			if (scalar <= 65535)
			{
				byte b2 = (byte)(0xE0u | (scalar >> 12));
				byte b3 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu));
				return ((((byte)(0x80 | (scalar & 0x3F)) << 8) | b3) << 8) | b2;
			}
			byte b4 = (byte)(0xF0u | (scalar >> 18));
			byte b5 = (byte)(0x80u | ((scalar >> 12) & 0x3Fu));
			byte b6 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu));
			return ((((((byte)(0x80 | (scalar & 0x3F)) << 8) | b6) << 8) | b5) << 8) | b4;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static bool IsSupplementaryCodePoint(int scalar)
		{
			return (scalar & -65536) != 0;
		}
	}
	public sealed class UnicodeRange
	{
		public int FirstCodePoint { get; }

		public int Length { get; }

		public UnicodeRange(int firstCodePoint, int length)
		{
			if (firstCodePoint < 0 || firstCodePoint > 65535)
			{
				throw new ArgumentOutOfRangeException("firstCodePoint");
			}
			if (length < 0 || (long)firstCodePoint + (long)length > 65536)
			{
				throw new ArgumentOutOfRangeException("length");
			}
			FirstCodePoint = firstCodePoint;
			Length = length;
		}

		public static UnicodeRange Create(char firstCharacter, char lastCharacter)
		{
			if (lastCharacter < firstCharacter)
			{
				throw new ArgumentOutOfRangeException("lastCharacter");
			}
			return new UnicodeRange(firstCharacter, 1 + (lastCharacter - firstCharacter));
		}
	}
	public static class UnicodeRanges
	{
		private static UnicodeRange _none;

		private static UnicodeRange _all;

		private static UnicodeRange _u0000;

		private static UnicodeRange _u0080;

		private static UnicodeRange _u0100;

		private static UnicodeRange _u0180;

		private static UnicodeRange _u0250;

		private static UnicodeRange _u02B0;

		private static UnicodeRange _u0300;

		private static UnicodeRange _u0370;

		private static UnicodeRange _u0400;

		private static UnicodeRange _u0500;

		private static UnicodeRange _u0530;

		private static UnicodeRange _u0590;

		private static UnicodeRange _u0600;

		private static UnicodeRange _u0700;

		private static UnicodeRange _u0750;

		private static UnicodeRange _u0780;

		private static UnicodeRange _u07C0;

		private static UnicodeRange _u0800;

		private static UnicodeRange _u0840;

		private static UnicodeRange _u0860;

		private static UnicodeRange _u0870;

		private static UnicodeRange _u08A0;

		private static UnicodeRange _u0900;

		private static UnicodeRange _u0980;

		private static UnicodeRange _u0A00;

		private static UnicodeRange _u0A80;

		private static UnicodeRange _u0B00;

		private static UnicodeRange _u0B80;

		private static UnicodeRange _u0C00;

		private static UnicodeRange _u0C80;

		private static UnicodeRange _u0D00;

		private static UnicodeRange _u0D80;

		private static UnicodeRange _u0E00;

		private static UnicodeRange _u0E80;

		private static UnicodeRange _u0F00;

		private static UnicodeRange _u1000;

		private static UnicodeRange _u10A0;

		private static UnicodeRange _u1100;

		private static UnicodeRange _u1200;

		private static UnicodeRange _u1380;

		private static UnicodeRange _u13A0;

		private static UnicodeRange _u1400;

		private static UnicodeRange _u1680;

		private static UnicodeRange _u16A0;

		private static UnicodeRange _u1700;

		private static UnicodeRange _u1720;

		private static UnicodeRange _u1740;

		private static UnicodeRange _u1760;

		private static UnicodeRange _u1780;

		private static UnicodeRange _u1800;

		private static UnicodeRange _u18B0;

		private static UnicodeRange _u1900;

		private static UnicodeRange _u1950;

		private static UnicodeRange _u1980;

		private static UnicodeRange _u19E0;

		private static UnicodeRange _u1A00;

		private static UnicodeRange _u1A20;

		private static UnicodeRange _u1AB0;

		private static UnicodeRange _u1B00;

		private static UnicodeRange _u1B80;

		private static UnicodeRange _u1BC0;

		private static UnicodeRange _u1C00;

		private static UnicodeRange _u1C50;

		private static UnicodeRange _u1C80;

		private static UnicodeRange _u1C90;

		private static UnicodeRange _u1CC0;

		private static UnicodeRange _u1CD0;

		private static UnicodeRange _u1D00;

		private static UnicodeRange _u1D80;

		private static UnicodeRange _u1DC0;

		private static UnicodeRange _u1E00;

		private static UnicodeRange _u1F00;

		private static UnicodeRange _u2000;

		private static UnicodeRange _u2070;

		private static UnicodeRange _u20A0;

		private static UnicodeRange _u20D0;

		private static UnicodeRange _u2100;

		private static UnicodeRange _u2150;

		private static UnicodeRange _u2190;

		private static UnicodeRange _u2200;

		private static UnicodeRange _u2300;

		private static UnicodeRange _u2400;

		private static UnicodeRange _u2440;

		private static UnicodeRange _u2460;

		private static UnicodeRange _u2500;

		private static UnicodeRange _u2580;

		private static UnicodeRange _u25A0;

		private static UnicodeRange _u2600;

		private static UnicodeRange _u2700;

		private static UnicodeRange _u27C0;

		private static UnicodeRange _u27F0;

		private static UnicodeRange _u2800;

		private static UnicodeRange _u2900;

		private static UnicodeRange _u2980;

		private static UnicodeRange _u2A00;

		private static UnicodeRange _u2B00;

		private static UnicodeRange _u2C00;

		private static UnicodeRange _u2C60;

		private static UnicodeRange _u2C80;

		private static UnicodeRange _u2D00;

		private static UnicodeRange _u2D30;

		private static UnicodeRange _u2D80;

		private static UnicodeRange _u2DE0;

		private static UnicodeRange _u2E00;

		private static UnicodeRange _u2E80;

		private static UnicodeRange _u2F00;

		private static UnicodeRange _u2FF0;

		private static UnicodeRange _u3000;

		private static UnicodeRange _u3040;

		private static UnicodeRange _u30A0;

		private static UnicodeRange _u3100;

		private static UnicodeRange _u3130;

		private static UnicodeRange _u3190;

		private static UnicodeRange _u31A0;

		private static UnicodeRange _u31C0;

		private static UnicodeRange _u31F0;

		private static UnicodeRange _u3200;

		private static UnicodeRange _u3300;

		private static UnicodeRange _u3400;

		private static UnicodeRange _u4DC0;

		private static UnicodeRange _u4E00;

		private static UnicodeRange _uA000;

		private static UnicodeRange _uA490;

		private static UnicodeRange _uA4D0;

		private static UnicodeRange _uA500;

		private static UnicodeRange _uA640;

		private static UnicodeRange _uA6A0;

		private static UnicodeRange _uA700;

		private static UnicodeRange _uA720;

		private static UnicodeRange _uA800;

		private static UnicodeRange _uA830;

		private static UnicodeRange _uA840;

		private static UnicodeRange _uA880;

		private static UnicodeRange _uA8E0;

		private static UnicodeRange _uA900;

		private static UnicodeRange _uA930;

		private static UnicodeRange _uA960;

		private static UnicodeRange _uA980;

		private static UnicodeRange _uA9E0;

		private static UnicodeRange _uAA00;

		private static UnicodeRange _uAA60;

		private static UnicodeRange _uAA80;

		private static UnicodeRange _uAAE0;

		private static UnicodeRange _uAB00;

		private static UnicodeRange _uAB30;

		private static UnicodeRange _uAB70;

		private static UnicodeRange _uABC0;

		private static UnicodeRange _uAC00;

		private static UnicodeRange _uD7B0;

		private static UnicodeRange _uF900;

		private static UnicodeRange _uFB00;

		private static UnicodeRange _uFB50;

		private static UnicodeRange _uFE00;

		private static UnicodeRange _uFE10;

		private static UnicodeRange _uFE20;

		private static UnicodeRange _uFE30;

		private static UnicodeRange _uFE50;

		private static UnicodeRange _uFE70;

		private static UnicodeRange _uFF00;

		private static UnicodeRange _uFFF0;

		public static UnicodeRange None => _none ?? CreateEmptyRange(ref _none);

		public static UnicodeRange All => _all ?? CreateRange(ref _all, '\0', '\uffff');

		public static UnicodeRange BasicLatin => _u0000 ?? CreateRange(ref _u0000, '\0', '\u007f');

		public static UnicodeRange Latin1Supplement => _u0080 ?? CreateRange(ref _u0080, '\u0080', 'ÿ');

		public static UnicodeRange LatinExtendedA => _u0100 ?? CreateRange(ref _u0100, 'Ā', 'ſ');

		public static UnicodeRange LatinExtendedB => _u0180 ?? CreateRange(ref _u0180, 'ƀ', 'ɏ');

		public static UnicodeRange IpaExtensions => _u0250 ?? CreateRange(ref _u0250, 'ɐ', 'ʯ');

		public static UnicodeRange SpacingModifierLetters => _u02B0 ?? CreateRange(ref _u02B0, 'ʰ', '\u02ff');

		public static UnicodeRange CombiningDiacriticalMarks => _u0300 ?? CreateRange(ref _u0300, '\u0300', '\u036f');

		public static UnicodeRange GreekandCoptic => _u0370 ?? CreateRange(ref _u0370, 'Ͱ', 'Ͽ');

		public static UnicodeRange Cyrillic => _u0400 ?? CreateRange(ref _u0400, 'Ѐ', 'ӿ');

		public static UnicodeRange CyrillicSupplement => _u0500 ?? CreateRange(ref _u0500, 'Ԁ', 'ԯ');

		public static UnicodeRange Armenian => _u0530 ?? CreateRange(ref _u0530, '\u0530', '֏');

		public static UnicodeRange Hebrew => _u0590 ?? CreateRange(ref _u0590, '\u0590', '\u05ff');

		public static UnicodeRange Arabic => _u0600 ?? CreateRange(ref _u0600, '\u0600', 'ۿ');

		public static UnicodeRange Syriac => _u0700 ?? CreateRange(ref _u0700, '܀', 'ݏ');

		public static UnicodeRange ArabicSupplement => _u0750 ?? CreateRange(ref _u0750, 'ݐ', 'ݿ');

		public static UnicodeRange Thaana => _u0780 ?? CreateRange(ref _u0780, 'ހ', '\u07bf');

		public static UnicodeRange NKo => _u07C0 ?? CreateRange(ref _u07C0, '߀', '߿');

		public static UnicodeRange Samaritan => _u0800 ?? CreateRange(ref _u0800, 'ࠀ', '\u083f');

		public static UnicodeRange Mandaic => _u0840 ?? CreateRange(ref _u0840, 'ࡀ', '\u085f');

		public static UnicodeRange SyriacSupplement => _u0860 ?? CreateRange(ref _u0860, 'ࡠ', '\u086f');

		public static UnicodeRange ArabicExtendedB => _u0870 ?? CreateRange(ref _u0870, '\u0870', '\u089f');

		public static UnicodeRange ArabicExtendedA => _u08A0 ?? CreateRange(ref _u08A0, 'ࢠ', '\u08ff');

		public static UnicodeRange Devanagari => _u0900 ?? CreateRange(ref _u0900, '\u0900', 'ॿ');

		public static UnicodeRange Bengali => _u0980 ?? CreateRange(ref _u0980, 'ঀ', '\u09ff');

		public static UnicodeRange Gurmukhi => _u0A00 ?? CreateRange(ref _u0A00, '\u0a00', '\u0a7f');

		public static UnicodeRange Gujarati => _u0A80 ?? CreateRange(ref _u0A80, '\u0a80', '\u0aff');

		public static UnicodeRange Oriya => _u0B00 ?? CreateRange(ref _u0B00, '\u0b00', '\u0b7f');

		public static UnicodeRange Tamil => _u0B80 ?? CreateRange(ref _u0B80, '\u0b80', '\u0bff');

		public static UnicodeRange Telugu => _u0C00 ?? CreateRange(ref _u0C00, '\u0c00', '౿');

		public static UnicodeRange Kannada => _u0C80 ?? CreateRange(ref _u0C80, 'ಀ', '\u0cff');

		public static UnicodeRange Malayalam => _u0D00 ?? CreateRange(ref _u0D00, '\u0d00', 'ൿ');

		public static UnicodeRange Sinhala => _u0D80 ?? CreateRange(ref _u0D80, '\u0d80', '\u0dff');

		public static UnicodeRange Thai => _u0E00 ?? CreateRange(ref _u0E00, '\u0e00', '\u0e7f');

		public static UnicodeRange Lao => _u0E80 ?? CreateRange(ref _u0E80, '\u0e80', '\u0eff');

		public static UnicodeRange Tibetan => _u0F00 ?? CreateRange(ref _u0F00, 'ༀ', '\u0fff');

		public static UnicodeRange Myanmar => _u1000 ?? CreateRange(ref _u1000, 'က', '႟');

		public static UnicodeRange Georgian => _u10A0 ?? CreateRange(ref _u10A0, 'Ⴀ', 'ჿ');

		public static UnicodeRange HangulJamo => _u1100 ?? CreateRange(ref _u1100, 'ᄀ', 'ᇿ');

		public static UnicodeRange Ethiopic => _u1200 ?? CreateRange(ref _u1200, 'ሀ', '\u137f');

		public static UnicodeRange EthiopicSupplement => _u1380 ?? CreateRange(ref _u1380, 'ᎀ', '\u139f');

		public static UnicodeRange Cherokee => _u13A0 ?? CreateRange(ref _u13A0, 'Ꭰ', '\u13ff');

		public static UnicodeRange UnifiedCanadianAboriginalSyllabics => _u1400 ?? CreateRange(ref _u1400, '᐀', 'ᙿ');

		public static UnicodeRange Ogham => _u1680 ?? CreateRange(ref _u1680, '\u1680', '\u169f');

		public static UnicodeRange Runic => _u16A0 ?? CreateRange(ref _u16A0, 'ᚠ', '\u16ff');

		public static UnicodeRange Tagalog => _u1700 ?? CreateRange(ref _u1700, 'ᜀ', '\u171f');

		public static UnicodeRange Hanunoo => _u1720 ?? CreateRange(ref _u1720, 'ᜠ', '\u173f');

		public static UnicodeRange Buhid => _u1740 ?? CreateRange(ref _u1740, 'ᝀ', '\u175f');

		public static UnicodeRange Tagbanwa => _u1760 ?? CreateRange(ref _u1760, 'ᝠ', '\u177f');

		public static UnicodeRange Khmer => _u1780 ?? CreateRange(ref _u1780, 'ក', '\u17ff');

		public static UnicodeRange Mongolian => _u1800 ?? CreateRange(ref _u1800, '᠀', '\u18af');

		public static UnicodeRange UnifiedCanadianAboriginalSyllabicsExtended => _u18B0 ?? CreateRange(ref _u18B0, 'ᢰ', '\u18ff');

		public static UnicodeRange Limbu => _u1900 ?? CreateRange(ref _u1900, 'ᤀ', '᥏');

		public static UnicodeRange TaiLe => _u1950 ?? CreateRange(ref _u1950, 'ᥐ', '\u197f');

		public static UnicodeRange NewTaiLue => _u1980 ?? CreateRange(ref _u1980, 'ᦀ', '᧟');

		public static UnicodeRange KhmerSymbols => _u19E0 ?? CreateRange(ref _u19E0, '᧠', '᧿');

		public static UnicodeRange Buginese => _u1A00 ?? CreateRange(ref _u1A00, 'ᨀ', '᨟');

		public static UnicodeRange TaiTham => _u1A20 ?? CreateRange(ref _u1A20, 'ᨠ', '\u1aaf');

		public static UnicodeRange CombiningDiacriticalMarksExtended => _u1AB0 ?? CreateRange(ref _u1AB0, '\u1ab0', '\u1aff');

		public static UnicodeRange Balinese => _u1B00 ?? CreateRange(ref _u1B00, '\u1b00', '\u1b7f');

		public static UnicodeRange Sundanese => _u1B80 ?? CreateRange(ref _u1B80, '\u1b80', 'ᮿ');

		public static UnicodeRange Batak => _u1BC0 ?? CreateRange(ref _u1BC0, 'ᯀ', '᯿');

		public static UnicodeRange Lepcha => _u1C00 ?? CreateRange(ref _u1C00, 'ᰀ', 'ᱏ');

		public static UnicodeRange OlChiki => _u1C50 ?? CreateRange(ref _u1C50, '᱐', '᱿');

		public static UnicodeRange CyrillicExtendedC => _u1C80 ?? CreateRange(ref _u1C80, 'ᲀ', '\u1c8f');

		public static UnicodeRange GeorgianExtended => _u1C90 ?? CreateRange(ref _u1C90, 'Ა', 'Ჿ');

		public static UnicodeRange SundaneseSupplement => _u1CC0 ?? CreateRange(ref _u1CC0, '᳀', '\u1ccf');

		public static UnicodeRange VedicExtensions => _u1CD0 ?? CreateRange(ref _u1CD0, '\u1cd0', '\u1cff');

		public static UnicodeRange PhoneticExtensions => _u1D00 ?? CreateRange(ref _u1D00, 'ᴀ', 'ᵿ');

		public static UnicodeRange PhoneticExtensionsSupplement => _u1D80 ?? CreateRange(ref _u1D80, 'ᶀ', 'ᶿ');

		public static UnicodeRange CombiningDiacriticalMarksSupplement => _u1DC0 ?? CreateRange(ref _u1DC0, '\u1dc0', '\u1dff');

		public static UnicodeRange LatinExtendedAdditional => _u1E00 ?? CreateRange(ref _u1E00, 'Ḁ', 'ỿ');

		public static UnicodeRange GreekExtended => _u1F00 ?? CreateRange(ref _u1F00, 'ἀ', '\u1fff');

		public static UnicodeRange GeneralPunctuation => _u2000 ?? CreateRange(ref _u2000, '\u2000', '\u206f');

		public static UnicodeRange SuperscriptsandSubscripts => _u2070 ?? CreateRange(ref _u2070, '⁰', '\u209f');

		public static UnicodeRange CurrencySymbols => _u20A0 ?? CreateRange(ref _u20A0, '₠', '\u20cf');

		public static UnicodeRange CombiningDiacriticalMarksforSymbols => _u20D0 ?? CreateRange(ref _u20D0, '\u20d0', '\u20ff');

		public static UnicodeRange LetterlikeSymbols => _u2100 ?? CreateRange(ref _u2100, '℀', '⅏');

		public static UnicodeRange NumberForms => _u2150 ?? CreateRange(ref _u2150, '⅐', '\u218f');

		public static UnicodeRange Arrows => _u2190 ?? CreateRange(ref _u2190, '←', '⇿');

		public static UnicodeRange MathematicalOperators => _u2200 ?? CreateRange(ref _u2200, '∀', '⋿');

		public static UnicodeRange MiscellaneousTechnical => _u2300 ?? CreateRange(ref _u2300, '⌀', '⏿');

		public static UnicodeRange ControlPictures => _u2400 ?? CreateRange(ref _u2400, '␀', '\u243f');

		public static UnicodeRange OpticalCharacterRecognition => _u2440 ?? CreateRange(ref _u2440, '⑀', '\u245f');

		public static UnicodeRange EnclosedAlphanumerics => _u2460 ?? CreateRange(ref _u2460, '①', '⓿');

		public static UnicodeRange BoxDrawing => _u2500 ?? CreateRange(ref _u2500, '─', '╿');

		public static UnicodeRange BlockElements => _u2580 ?? CreateRange(ref _u2580, '▀', '▟');

		public static UnicodeRange GeometricShapes => _u25A0 ?? CreateRange(ref _u25A0, '■', '◿');

		public static UnicodeRange MiscellaneousSymbols => _u2600 ?? CreateRange(ref _u2600, '☀', '⛿');

		public static UnicodeRange Dingbats => _u2700 ?? CreateRange(ref _u2700, '✀', '➿');

		public static UnicodeRange MiscellaneousMathematicalSymbolsA => _u27C0 ?? CreateRange(ref _u27C0, '⟀', '⟯');

		public static UnicodeRange SupplementalArrowsA => _u27F0 ?? CreateRange(ref _u27F0, '⟰', '⟿');

		public static UnicodeRange BraillePatterns => _u2800 ?? CreateRange(ref _u2800, '⠀', '⣿');

		public static UnicodeRange SupplementalArrowsB => _u2900 ?? CreateRange(ref _u2900, '⤀', '⥿');

		public static UnicodeRange MiscellaneousMathematicalSymbolsB => _u2980 ?? CreateRange(ref _u2980, '⦀', '⧿');

		public static UnicodeRange SupplementalMathematicalOperators => _u2A00 ?? CreateRange(ref _u2A00, '⨀', '⫿');

		public static UnicodeRange MiscellaneousSymbolsandArrows => _u2B00 ?? CreateRange(ref _u2B00, '⬀', '⯿');

		public static UnicodeRange Glagolitic => _u2C00 ?? CreateRange(ref _u2C00, 'Ⰰ', '\u2c5f');

		public static UnicodeRange LatinExtendedC => _u2C60 ?? CreateRange(ref _u2C60, 'Ⱡ', 'Ɀ');

		public static UnicodeRange Coptic => _u2C80 ?? CreateRange(ref _u2C80, 'Ⲁ', '⳿');

		public static UnicodeRange GeorgianSupplement => _u2D00 ?? CreateRange(ref _u2D00, 'ⴀ', '\u2d2f');

		public static UnicodeRange Tifinagh => _u2D30 ?? CreateRange(ref _u2D30, 'ⴰ', '\u2d7f');

		public static UnicodeRange EthiopicExtended => _u2D80 ?? CreateRange(ref _u2D80, 'ⶀ', '\u2ddf');

		public static UnicodeRange CyrillicExtendedA => _u2DE0 ?? CreateRange(ref _u2DE0, '\u2de0', '\u2dff');

		public static UnicodeRange SupplementalPunctuation => _u2E00 ?? CreateRange(ref _u2E00, '⸀', '\u2e7f');

		public static UnicodeRange CjkRadicalsSupplement => _u2E80 ?? CreateRange(ref _u2E80, '⺀', '\u2eff');

		public static UnicodeRange KangxiRadicals => _u2F00 ?? CreateRange(ref _u2F00, '⼀', '\u2fdf');

		public static UnicodeRange IdeographicDescriptionCharacters => _u2FF0 ?? CreateRange(ref _u2FF0, '⿰', '\u2fff');

		public static UnicodeRange CjkSymbolsandPunctuation => _u3000 ?? CreateRange(ref _u3000, '\u3000', '〿');

		public static UnicodeRange Hiragana => _u3040 ?? CreateRange(ref _u3040, '\u3040', 'ゟ');

		public static UnicodeRange Katakana => _u30A0 ?? CreateRange(ref _u30A0, '゠', 'ヿ');

		public static UnicodeRange Bopomofo => _u3100 ?? CreateRange(ref _u3100, '\u3100', 'ㄯ');

		public static UnicodeRange HangulCompatibilityJamo => _u3130 ?? CreateRange(ref _u3130, '\u3130', '\u318f');

		public static UnicodeRange Kanbun => _u3190 ?? CreateRange(ref _u3190, '㆐', '㆟');

		public static UnicodeRange BopomofoExtended => _u31A0 ?? CreateRange(ref _u31A0, 'ㆠ', 'ㆿ');

		public static UnicodeRange CjkStrokes => _u31C0 ?? CreateRange(ref _u31C0, '㇀', '\u31ef');

		public static UnicodeRange KatakanaPhoneticExtensions => _u31F0 ?? CreateRange(ref _u31F0, 'ㇰ', 'ㇿ');

		public static UnicodeRange EnclosedCjkLettersandMonths => _u3200 ?? CreateRange(ref _u3200, '㈀', '㋿');

		public static UnicodeRange CjkCompatibility => _u3300 ?? CreateRange(ref _u3300, '㌀', '㏿');

		public static UnicodeRange CjkUnifiedIdeographsExtensionA => _u3400 ?? CreateRange(ref _u3400, '㐀', '䶿');

		public static UnicodeRange YijingHexagramSymbols => _u4DC0 ?? CreateRange(ref _u4DC0, '䷀', '䷿');

		public static UnicodeRange CjkUnifiedIdeographs => _u4E00 ?? CreateRange(ref _u4E00, '一', '\u9fff');

		public static UnicodeRange YiSyllables => _uA000 ?? CreateRange(ref _uA000, 'ꀀ', '\ua48f');

		public static UnicodeRange YiRadicals => _uA490 ?? CreateRange(ref _uA490, '꒐', '\ua4cf');

		public static UnicodeRange Lisu => _uA4D0 ?? CreateRange(ref _uA4D0, 'ꓐ', '꓿');

		public static UnicodeRange Vai => _uA500 ?? CreateRange(ref _uA500, 'ꔀ', '\ua63f');

		public static UnicodeRange CyrillicExtendedB => _uA640 ?? CreateRange(ref _uA640, 'Ꙁ', '\ua69f');

		public static UnicodeRange Bamum => _uA6A0 ?? CreateRange(ref _uA6A0, 'ꚠ', '\ua6ff');

		public static UnicodeRange ModifierToneLetters => _uA700 ?? CreateRange(ref _uA700, '\ua700', 'ꜟ');

		public static UnicodeRange LatinExtendedD => _uA720 ?? CreateRange(ref _uA720, '\ua720', 'ꟿ');

		public static UnicodeRange SylotiNagri => _uA800 ?? CreateRange(ref _uA800, 'ꠀ', '\ua82f');

		public static UnicodeRange CommonIndicNumberForms => _uA830 ?? CreateRange(ref _uA830, '꠰', '\ua83f');

		public static UnicodeRange Phagspa => _uA840 ?? CreateRange(ref _uA840, 'ꡀ', '\ua87f');

		public static UnicodeRange Saurashtra => _uA880 ?? CreateRange(ref _uA880, '\ua880', '\ua8df');

		public static UnicodeRange DevanagariExtended => _uA8E0 ?? CreateRange(ref _uA8E0, '\ua8e0', '\ua8ff');

		public static UnicodeRange KayahLi => _uA900 ?? CreateRange(ref _uA900, '꤀', '꤯');

		public static UnicodeRange Rejang => _uA930 ?? CreateRange(ref _uA930, 'ꤰ', '꥟');

		public static UnicodeRange HangulJamoExtendedA => _uA960 ?? CreateRange(ref _uA960, 'ꥠ', '\ua97f');

		public static UnicodeRange Javanese => _uA980 ?? CreateRange(ref _uA980, '\ua980', '꧟');

		public static UnicodeRange MyanmarExtendedB => _uA9E0 ?? CreateRange(ref _uA9E0, 'ꧠ', '\ua9ff');

		public static UnicodeRange Cham => _uAA00 ?? CreateRange(ref _uAA00, 'ꨀ', '꩟');

		public static UnicodeRange MyanmarExtendedA => _uAA60 ?? CreateRange(ref _uAA60, 'ꩠ', 'ꩿ');

		public static UnicodeRange TaiViet => _uAA80 ?? CreateRange(ref _uAA80, 'ꪀ', '꫟');

		public static UnicodeRange MeeteiMayekExtensions => _uAAE0 ?? CreateRange(ref _uAAE0, 'ꫠ', '\uaaff');

		public static UnicodeRange EthiopicExtendedA => _uAB00 ?? CreateRange(ref _uAB00, '\uab00', '\uab2f');

		public static UnicodeRange LatinExtendedE => _uAB30 ?? CreateRange(ref _uAB30, 'ꬰ', '\uab6f');

		public static UnicodeRange CherokeeSupplement => _uAB70 ?? CreateRange(ref _uAB70, 'ꭰ', 'ꮿ');

		public static UnicodeRange MeeteiMayek => _uABC0 ?? CreateRange(ref _uABC0, 'ꯀ', '\uabff');

		public static UnicodeRange HangulSyllables => _uAC00 ?? CreateRange(ref _uAC00, '가', '\ud7af');

		public static UnicodeRange HangulJamoExtendedB => _uD7B0 ?? CreateRange(ref _uD7B0, 'ힰ', '\ud7ff');

		public static UnicodeRange CjkCompatibilityIdeographs => _uF900 ?? CreateRange(ref _uF900, '豈', '\ufaff');

		public static UnicodeRange AlphabeticPresentationForms => _uFB00 ?? CreateRange(ref _uFB00, 'ff', 'ﭏ');

		public static UnicodeRange ArabicPresentationFormsA => _uFB50 ?? CreateRange(ref _uFB50, 'ﭐ', '\ufdff');

		public static UnicodeRange VariationSelectors => _uFE00 ?? CreateRange(ref _uFE00, '\ufe00', '\ufe0f');

		public static UnicodeRange VerticalForms => _uFE10 ?? CreateRange(ref _uFE10, '︐', '\ufe1f');

		public static UnicodeRange CombiningHalfMarks => _uFE20 ?? CreateRange(ref _uFE20, '\ufe20', '\ufe2f');

		public static UnicodeRange CjkCompatibilityForms => _uFE30 ?? CreateRange(ref _uFE30, '︰', '\ufe4f');

		public static UnicodeRange SmallFormVariants => _uFE50 ?? CreateRange(ref _uFE50, '﹐', '\ufe6f');

		public static UnicodeRange ArabicPresentationFormsB => _uFE70 ?? CreateRange(ref _uFE70, 'ﹰ', '\ufeff');

		public static UnicodeRange HalfwidthandFullwidthForms => _uFF00 ?? CreateRange(ref _uFF00, '\uff00', '\uffef');

		public static UnicodeRange Specials => _uFFF0 ?? CreateRange(ref _uFFF0, '\ufff0', '\uffff');

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static UnicodeRange CreateEmptyRange([NotNull] ref UnicodeRange range)
		{
			Volatile.Write(ref range, new UnicodeRange(0, 0));
			return range;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static UnicodeRange CreateRange([NotNull] ref UnicodeRange range, char first, char last)
		{
			Volatile.Write(ref range, UnicodeRange.Create(first, last));
			return range;
		}
	}
}
namespace System.Text.Encodings.Web
{
	internal struct AsciiByteMap
	{
		private const int BufferSize = 128;

		private unsafe fixed byte Buffer[128];

		internal unsafe void InsertAsciiChar(char key, byte value)
		{
			if (key < '\u0080')
			{
				Buffer[(uint)key] = value;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal unsafe readonly bool TryLookup(Rune key, out byte value)
		{
			if (key.IsAscii)
			{
				byte b = Buffer[(uint)key.Value];
				if (b != 0)
				{
					value = b;
					return true;
				}
			}
			value = 0;
			return false;
		}
	}
	internal struct AllowedBmpCodePointsBitmap
	{
		private const int BitmapLengthInDWords = 2048;

		private unsafe fixed uint Bitmap[2048];

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void AllowChar(char value)
		{
			_GetIndexAndOffset(value, out UIntPtr index, out int offset);
			ref uint reference = ref Bitmap[(ulong)index];
			reference |= (uint)(1 << offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void ForbidChar(char value)
		{
			_GetIndexAndOffset(value, out UIntPtr index, out int offset);
			ref uint reference = ref Bitmap[(ulong)index];
			reference &= (uint)(~(1 << offset));
		}

		public void ForbidHtmlCharacters()
		{
			ForbidChar('<');
			ForbidChar('>');
			ForbidChar('&');
			ForbidChar('\'');
			ForbidChar('"');
			ForbidChar('+');
		}

		public unsafe void ForbidUndefinedCharacters()
		{
			fixed (uint* pointer = Bitmap)
			{
				ReadOnlySpan<byte> definedBmpCodePointsBitmapLittleEndian = UnicodeHelpers.GetDefinedBmpCodePointsBitmapLittleEndian();
				Span<uint> span = new Span<uint>(pointer, 2048);
				for (int i = 0; i < span.Length; i++)
				{
					span[i] &= BinaryPrimitives.ReadUInt32LittleEndian(definedBmpCodePointsBitmapLittleEndian.Slice(i * 4));
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe readonly bool IsCharAllowed(char value)
		{
			_GetIndexAndOffset(

System.Text.Json.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Pipelines;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Reflection;
using System.Text.Json.Schema;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Converters;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using FxResources.System.Text.Json;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Text.Json")]
[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("Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.\r\n\r\nThe System.Text.Json 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("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Text.Json")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
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]
	internal sealed class RequiresLocationAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : 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.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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.Text.Json
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				ToCharsBuffer(bytes[i], chars, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan());
			Span<char> buffer = span;
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				ToCharsBuffer(readOnlySpan[i], buffer, num, casing);
				num += 2;
			}
			return buffer.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			return TryDecodeFromUtf16_Scalar(chars, bytes, out charsProcessed);
		}

		private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < bytes.Length)
			{
				num3 = FromChar(chars[num + 1]);
				num4 = FromChar(chars[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				bytes[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				long num2 = -17875860044349952L << (int)num;
				ulong num3 = num - 64;
				return (long)((ulong)num2 & num3) < 0L;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class Obsoletions
	{
		internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}";

		internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.";

		internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001";

		internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used.";

		internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002";

		internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime.";

		internal const string CodeAccessSecurityDiagId = "SYSLIB0003";

		internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported.";

		internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004";

		internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported.";

		internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005";

		internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadAbortDiagId = "SYSLIB0006";

		internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported.";

		internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007";

		internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException.";

		internal const string CreatePdbGeneratorDiagId = "SYSLIB0008";

		internal const string AuthenticationManagerMessage = "AuthenticationManager is not supported. Methods will no-op or throw PlatformNotSupportedException.";

		internal const string AuthenticationManagerDiagId = "SYSLIB0009";

		internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException.";

		internal const string RemotingApisDiagId = "SYSLIB0010";

		internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.";

		internal const string BinaryFormatterDiagId = "SYSLIB0011";

		internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead.";

		internal const string CodeBaseDiagId = "SYSLIB0012";

		internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead.";

		internal const string EscapeUriStringDiagId = "SYSLIB0013";

		internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.";

		internal const string WebRequestDiagId = "SYSLIB0014";

		internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+.";

		internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015";

		internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations.";

		internal const string GetContextInfoDiagId = "SYSLIB0016";

		internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException.";

		internal const string StrongNameKeyPairDiagId = "SYSLIB0017";

		internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException.";

		internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018";

		internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException.";

		internal const string RuntimeEnvironmentDiagId = "SYSLIB0019";

		internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull.";

		internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020";

		internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead.";

		internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021";

		internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead.";

		internal const string RijndaelDiagId = "SYSLIB0022";

		internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead.";

		internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023";

		internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception.";

		internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024";

		internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+.";

		internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025";

		internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use X509CertificateLoader to create a new certificate.";

		internal const string X509CertificateImmutableDiagId = "SYSLIB0026";

		internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey.";

		internal const string PublicKeyPropertyDiagId = "SYSLIB0027";

		internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key.";

		internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028";

		internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported.";

		internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029";

		internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter.";

		internal const string UseManagedSha1DiagId = "SYSLIB0030";

		internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1.";

		internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031";

		internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored.";

		internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032";

		internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead.";

		internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033";

		internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead.";

		internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034";

		internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner.";

		internal const string SignerInfoCounterSigDiagId = "SYSLIB0035";

		internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.";

		internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036";

		internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported.";

		internal const string AssemblyNameMembersDiagId = "SYSLIB0037";

		internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information.";

		internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038";

		internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults.";

		internal const string TlsVersion10and11DiagId = "SYSLIB0039";

		internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code.";

		internal const string EncryptionPolicyDiagId = "SYSLIB0040";

		internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations.";

		internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041";

		internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys.";

		internal const string EccXmlExportImportDiagId = "SYSLIB0042";

		internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead.";

		internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043";

		internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.";

		internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044";

		internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead.";

		internal const string CryptoStringFactoryDiagId = "SYSLIB0045";

		internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code.";

		internal const string ControlledExecutionRunDiagId = "SYSLIB0046";

		internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution.";

		internal const string XmlSecureResolverDiagId = "SYSLIB0047";

		internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead.";

		internal const string RsaEncryptDecryptDiagId = "SYSLIB0048";

		internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties.";

		internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049";

		internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used.";

		internal const string LegacyFormatterDiagId = "SYSLIB0050";

		internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code.";

		internal const string LegacyFormatterImplDiagId = "SYSLIB0051";

		internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported.";

		internal const string RegexExtensibilityDiagId = "SYSLIB0052";

		internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size.";

		internal const string AesGcmTagConstructorDiagId = "SYSLIB0053";

		internal const string ThreadVolatileReadWriteMessage = "Thread.VolatileRead and Thread.VolatileWrite are obsolete. Use Volatile.Read or Volatile.Write respectively instead.";

		internal const string ThreadVolatileReadWriteDiagId = "SYSLIB0054";

		internal const string ArmIntrinsicPerformsUnsignedOperationMessage = "The underlying hardware instruction does not perform a signed saturate narrowing operation, and it always returns an unsigned result. Use the unsigned overload instead.";

		internal const string ArmIntrinsicPerformsUnsignedOperationDiagId = "SYSLIB0055";

		internal const string LoadFromHashAlgorithmMessage = "LoadFrom with a custom AssemblyHashAlgorithm is obsolete. Use overloads without an AssemblyHashAlgorithm.";

		internal const string LoadFromHashAlgorithmDiagId = "SYSLIB0056";

		internal const string X509CtorCertDataObsoleteMessage = "Loading certificate data through the constructor or Import is obsolete. Use X509CertificateLoader instead to load certificates.";

		internal const string X509CtorCertDataObsoleteDiagId = "SYSLIB0057";
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge");

		internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss");

		internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16");

		internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16");

		internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose");

		internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty");

		internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8");

		internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64");

		internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16");

		internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16");

		internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8");

		internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray");

		internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty");

		internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose");

		internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject");

		internal static string DepthTooLarge => GetResourceString("DepthTooLarge");

		internal static string DestinationTooShort => GetResourceString("DestinationTooShort");

		internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid");

		internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound");

		internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound");

		internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson");

		internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound");

		internal static string ExpectedFalse => GetResourceString("ExpectedFalse");

		internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens");

		internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken");

		internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound");

		internal static string ExpectedNull => GetResourceString("ExpectedNull");

		internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound");

		internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound");

		internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound");

		internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound");

		internal static string ExpectedTrue => GetResourceString("ExpectedTrue");

		internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound");

		internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan");

		internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter");

		internal static string InvalidCast => GetResourceString("InvalidCast");

		internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString");

		internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString");

		internal static string UnsupportedEnumIdentifier => GetResourceString("UnsupportedEnumIdentifier");

		internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive");

		internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString");

		internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments");

		internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType");

		internal static string JsonElementDeepEqualsInsufficientExecutionStack => GetResourceString("JsonElementDeepEqualsInsufficientExecutionStack");

		internal static string JsonNumberExponentTooLarge => GetResourceString("JsonNumberExponentTooLarge");

		internal static string DefaultTypeInfoResolverImmutable => GetResourceString("DefaultTypeInfoResolverImmutable");

		internal static string TypeInfoResolverChainImmutable => GetResourceString("TypeInfoResolverChainImmutable");

		internal static string TypeInfoImmutable => GetResourceString("TypeInfoImmutable");

		internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive");

		internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid");

		internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray");

		internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty");

		internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge");

		internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge");

		internal static string FormatDecimal => GetResourceString("FormatDecimal");

		internal static string FormatDouble => GetResourceString("FormatDouble");

		internal static string FormatInt32 => GetResourceString("FormatInt32");

		internal static string FormatInt64 => GetResourceString("FormatInt64");

		internal static string FormatSingle => GetResourceString("FormatSingle");

		internal static string FormatUInt32 => GetResourceString("FormatUInt32");

		internal static string FormatUInt64 => GetResourceString("FormatUInt64");

		internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal");

		internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign");

		internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData");

		internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported");

		internal static string ValueTooLarge => GetResourceString("ValueTooLarge");

		internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd");

		internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue");

		internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType");

		internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize");

		internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar");

		internal static string InvalidComparison => GetResourceString("InvalidComparison");

		internal static string UnsupportedFormat => GetResourceString("UnsupportedFormat");

		internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment");

		internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd");

		internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd");

		internal static string SerializerOptionsReadOnly => GetResourceString("SerializerOptionsReadOnly");

		internal static string SerializerOptions_InvalidChainedResolver => GetResourceString("SerializerOptions_InvalidChainedResolver");

		internal static string StreamNotWritable => GetResourceString("StreamNotWritable");

		internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter");

		internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict");

		internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull");

		internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid");

		internal static string PropertyTypeNotNullable => GetResourceString("PropertyTypeNotNullable");

		internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute");

		internal static string ExtensionDataConflictsWithUnmappedMemberHandling => GetResourceString("ExtensionDataConflictsWithUnmappedMemberHandling");

		internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType");

		internal static string TypeRequiresAsyncSerialization => GetResourceString("TypeRequiresAsyncSerialization");

		internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment");

		internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment");

		internal static string CannotSkip => GetResourceString("CannotSkip");

		internal static string NotEnoughData => GetResourceString("NotEnoughData");

		internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator");

		internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments");

		internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor");

		internal static string DeserializeInterfaceOrAbstractType => GetResourceString("DeserializeInterfaceOrAbstractType");

		internal static string DeserializationMustSpecifyTypeDiscriminator => GetResourceString("DeserializationMustSpecifyTypeDiscriminator");

		internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible");

		internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid");

		internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead");

		internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible");

		internal static string ResolverTypeNotCompatible => GetResourceString("ResolverTypeNotCompatible");

		internal static string ResolverTypeInfoOptionsNotCompatible => GetResourceString("ResolverTypeInfoOptionsNotCompatible");

		internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite");

		internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull");

		internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute");

		internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize");

		internal static string FormatByte => GetResourceString("FormatByte");

		internal static string FormatInt16 => GetResourceString("FormatInt16");

		internal static string FormatSByte => GetResourceString("FormatSByte");

		internal static string FormatUInt16 => GetResourceString("FormatUInt16");

		internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected");

		internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber");

		internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable");

		internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound");

		internal static string MetadataIdCannotBeCombinedWithRef => GetResourceString("MetadataIdCannotBeCombinedWithRef");

		internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType");

		internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues");

		internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed");

		internal static string MetadataInvalidPropertyInArrayMetadata => GetResourceString("MetadataInvalidPropertyInArrayMetadata");

		internal static string MetadataStandaloneValuesProperty => GetResourceString("MetadataStandaloneValuesProperty");

		internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties");

		internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound");

		internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString");

		internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign");

		internal static string MetadataUnexpectedProperty => GetResourceString("MetadataUnexpectedProperty");

		internal static string UnmappedJsonProperty => GetResourceString("UnmappedJsonProperty");

		internal static string DuplicateMetadataProperty => GetResourceString("DuplicateMetadataProperty");

		internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter");

		internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding");

		internal static string ObjectWithParameterizedCtorRefMetadataNotSupported => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotSupported");

		internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull");

		internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType");

		internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam");

		internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded");

		internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType");

		internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported");

		internal static string JsonIncludeOnInaccessibleProperty => GetResourceString("JsonIncludeOnInaccessibleProperty");

		internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember");

		internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection");

		internal static string ConstructorContainsNullParameterNames => GetResourceString("ConstructorContainsNullParameterNames");

		internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified");

		internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid");

		internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported");

		internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid");

		internal static string NumberHandlingOnPropertyInvalid => GetResourceString("NumberHandlingOnPropertyInvalid");

		internal static string ConverterCanConvertMultipleTypes => GetResourceString("ConverterCanConvertMultipleTypes");

		internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType");

		internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue");

		internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull");

		internal static string SerializerConverterFactoryReturnsJsonConverterFactory => GetResourceString("SerializerConverterFactoryReturnsJsonConverterFactory");

		internal static string SerializerConverterFactoryInvalidArgument => GetResourceString("SerializerConverterFactoryInvalidArgument");

		internal static string NodeElementWrongType => GetResourceString("NodeElementWrongType");

		internal static string NodeElementCannotBeObjectOrArray => GetResourceString("NodeElementCannotBeObjectOrArray");

		internal static string NodeAlreadyHasParent => GetResourceString("NodeAlreadyHasParent");

		internal static string NodeCycleDetected => GetResourceString("NodeCycleDetected");

		internal static string NodeUnableToConvert => GetResourceString("NodeUnableToConvert");

		internal static string NodeUnableToConvertElement => GetResourceString("NodeUnableToConvertElement");

		internal static string NodeValueNotAllowed => GetResourceString("NodeValueNotAllowed");

		internal static string NodeWrongType => GetResourceString("NodeWrongType");

		internal static string NodeParentWrongType => GetResourceString("NodeParentWrongType");

		internal static string NodeDuplicateKey => GetResourceString("NodeDuplicateKey");

		internal static string SerializerContextOptionsReadOnly => GetResourceString("SerializerContextOptionsReadOnly");

		internal static string ConverterForPropertyMustBeValid => GetResourceString("ConverterForPropertyMustBeValid");

		internal static string NoMetadataForType => GetResourceString("NoMetadataForType");

		internal static string AmbiguousMetadataForType => GetResourceString("AmbiguousMetadataForType");

		internal static string CollectionIsReadOnly => GetResourceString("CollectionIsReadOnly");

		internal static string ArrayIndexNegative => GetResourceString("ArrayIndexNegative");

		internal static string ArrayTooSmall => GetResourceString("ArrayTooSmall");

		internal static string NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty => GetResourceString("NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty");

		internal static string NoMetadataForTypeProperties => GetResourceString("NoMetadataForTypeProperties");

		internal static string FieldCannotBeVirtual => GetResourceString("FieldCannotBeVirtual");

		internal static string MissingFSharpCoreMember => GetResourceString("MissingFSharpCoreMember");

		internal static string FSharpDiscriminatedUnionsNotSupported => GetResourceString("FSharpDiscriminatedUnionsNotSupported");

		internal static string Polymorphism_BaseConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_BaseConverterDoesNotSupportMetadata");

		internal static string Polymorphism_DerivedConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_DerivedConverterDoesNotSupportMetadata");

		internal static string Polymorphism_TypeDoesNotSupportPolymorphism => GetResourceString("Polymorphism_TypeDoesNotSupportPolymorphism");

		internal static string Polymorphism_DerivedTypeIsNotSupported => GetResourceString("Polymorphism_DerivedTypeIsNotSupported");

		internal static string Polymorphism_DerivedTypeIsAlreadySpecified => GetResourceString("Polymorphism_DerivedTypeIsAlreadySpecified");

		internal static string Polymorphism_TypeDicriminatorIdIsAlreadySpecified => GetResourceString("Polymorphism_TypeDicriminatorIdIsAlreadySpecified");

		internal static string Polymorphism_InvalidCustomTypeDiscriminatorPropertyName => GetResourceString("Polymorphism_InvalidCustomTypeDiscriminatorPropertyName");

		internal static string Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes => GetResourceString("Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes");

		internal static string Polymorphism_UnrecognizedTypeDiscriminator => GetResourceString("Polymorphism_UnrecognizedTypeDiscriminator");

		internal static string Polymorphism_RuntimeTypeNotSupported => GetResourceString("Polymorphism_RuntimeTypeNotSupported");

		internal static string Polymorphism_RuntimeTypeDiamondAmbiguity => GetResourceString("Polymorphism_RuntimeTypeDiamondAmbiguity");

		internal static string InvalidJsonTypeInfoOperationForKind => GetResourceString("InvalidJsonTypeInfoOperationForKind");

		internal static string OnDeserializingCallbacksNotSupported => GetResourceString("OnDeserializingCallbacksNotSupported");

		internal static string CreateObjectConverterNotCompatible => GetResourceString("CreateObjectConverterNotCompatible");

		internal static string JsonPropertyInfoBoundToDifferentParent => GetResourceString("JsonPropertyInfoBoundToDifferentParent");

		internal static string JsonSerializerOptionsNoTypeInfoResolverSpecified => GetResourceString("JsonSerializerOptionsNoTypeInfoResolverSpecified");

		internal static string JsonSerializerIsReflectionDisabled => GetResourceString("JsonSerializerIsReflectionDisabled");

		internal static string JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo => GetResourceString("JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo");

		internal static string JsonPropertyRequiredAndNotDeserializable => GetResourceString("JsonPropertyRequiredAndNotDeserializable");

		internal static string JsonPropertyRequiredAndExtensionData => GetResourceString("JsonPropertyRequiredAndExtensionData");

		internal static string JsonRequiredPropertiesMissing => GetResourceString("JsonRequiredPropertiesMissing");

		internal static string ObjectCreationHandlingPopulateNotSupportedByConverter => GetResourceString("ObjectCreationHandlingPopulateNotSupportedByConverter");

		internal static string ObjectCreationHandlingPropertyMustHaveAGetter => GetResourceString("ObjectCreationHandlingPropertyMustHaveAGetter");

		internal static string ObjectCreationHandlingPropertyValueTypeMustHaveASetter => GetResourceString("ObjectCreationHandlingPropertyValueTypeMustHaveASetter");

		internal static string ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization => GetResourceString("ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization");

		internal static string ObjectCreationHandlingPropertyCannotAllowReadOnlyMember => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReadOnlyMember");

		internal static string ObjectCreationHandlingPropertyCannotAllowReferenceHandling => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReferenceHandling");

		internal static string ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors => GetResourceString("ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors");

		internal static string FormatInt128 => GetResourceString("FormatInt128");

		internal static string FormatUInt128 => GetResourceString("FormatUInt128");

		internal static string FormatHalf => GetResourceString("FormatHalf");

		internal static string InvalidIndentCharacter => GetResourceString("InvalidIndentCharacter");

		internal static string InvalidIndentSize => GetResourceString("InvalidIndentSize");

		internal static string PipeWriterCanceled => GetResourceString("PipeWriterCanceled");

		internal static string PipeWriter_DoesNotImplementUnflushedBytes => GetResourceString("PipeWriter_DoesNotImplementUnflushedBytes");

		internal static string InvalidNewLine => GetResourceString("InvalidNewLine");

		internal static string PropertyGetterDisallowNull => GetResourceString("PropertyGetterDisallowNull");

		internal static string PropertySetterDisallowNull => GetResourceString("PropertySetterDisallowNull");

		internal static string ConstructorParameterDisallowNull => GetResourceString("ConstructorParameterDisallowNull");

		internal static string JsonSchemaExporter_ReferenceHandlerPreserve_NotSupported => GetResourceString("JsonSchemaExporter_ReferenceHandlerPreserve_NotSupported");

		internal static string JsonSchemaExporter_DepthTooLarge => GetResourceString("JsonSchemaExporter_DepthTooLarge");

		internal static string Arg_WrongType => GetResourceString("Arg_WrongType");

		internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall");

		internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported");

		internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound");

		internal static string Argument_IncompatibleArrayType => GetResourceString("Argument_IncompatibleArrayType");

		internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey");

		internal static string Argument_AddingDuplicate => GetResourceString("Argument_AddingDuplicate");

		internal static string InvalidOperation_ConcurrentOperationsNotSupported => GetResourceString("InvalidOperation_ConcurrentOperationsNotSupported");

		internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion");

		internal static string ArgumentOutOfRange_Generic_MustBeNonNegative => GetResourceString("ArgumentOutOfRange_Generic_MustBeNonNegative");

		internal static string ArgumentOutOfRange_Generic_MustBeGreaterOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeGreaterOrEqual");

		internal static string ArgumentOutOfRange_Generic_MustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeLessOrEqual");

		internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	internal sealed class ObsoleteAttribute : Attribute
	{
		public string Message { get; }

		public bool IsError { get; }

		public string DiagnosticId { get; set; }

		public string UrlFormat { get; set; }

		public ObsoleteAttribute()
		{
		}

		public ObsoleteAttribute(string message)
		{
			Message = message;
		}

		public ObsoleteAttribute(string message, bool error)
		{
			Message = message;
			IsError = error;
		}
	}
}
namespace System.Reflection
{
	internal sealed class NullabilityInfo
	{
		public Type Type { get; }

		public NullabilityState ReadState { get; internal set; }

		public NullabilityState WriteState { get; internal set; }

		public NullabilityInfo ElementType { get; }

		public NullabilityInfo[] GenericTypeArguments { get; }

		internal NullabilityInfo(Type type, NullabilityState readState, NullabilityState writeState, NullabilityInfo elementType, NullabilityInfo[] typeArguments)
		{
			Type = type;
			ReadState = readState;
			WriteState = writeState;
			ElementType = elementType;
			GenericTypeArguments = typeArguments;
		}
	}
	internal enum NullabilityState
	{
		Unknown,
		NotNull,
		Nullable
	}
	internal sealed class NullabilityInfoContext
	{
		[Flags]
		private enum NotAnnotatedStatus
		{
			None = 0,
			Private = 1,
			Internal = 2
		}

		private readonly struct NullableAttributeStateParser
		{
			private static readonly object UnknownByte = (byte)0;

			private readonly object _nullableAttributeArgument;

			public static NullableAttributeStateParser Unknown => new NullableAttributeStateParser(UnknownByte);

			public NullableAttributeStateParser(object nullableAttributeArgument)
			{
				_nullableAttributeArgument = nullableAttributeArgument;
			}

			public bool ParseNullableState(int index, ref NullabilityState state)
			{
				object nullableAttributeArgument = _nullableAttributeArgument;
				if (!(nullableAttributeArgument is byte b))
				{
					if (nullableAttributeArgument is ReadOnlyCollection<CustomAttributeTypedArgument> readOnlyCollection)
					{
						ReadOnlyCollection<CustomAttributeTypedArgument> readOnlyCollection2 = readOnlyCollection;
						if (index < readOnlyCollection2.Count && readOnlyCollection2[index].Value is byte b2)
						{
							state = TranslateByte(b2);
							return true;
						}
					}
					return false;
				}
				byte b3 = b;
				state = TranslateByte(b3);
				return true;
			}
		}

		private const string CompilerServicesNameSpace = "System.Runtime.CompilerServices";

		private readonly Dictionary<Module, NotAnnotatedStatus> _publicOnlyModules = new Dictionary<Module, NotAnnotatedStatus>();

		private readonly Dictionary<MemberInfo, NullabilityState> _context = new Dictionary<MemberInfo, NullabilityState>();

		private NullabilityState? GetNullableContext(MemberInfo memberInfo)
		{
			while (memberInfo != null)
			{
				if (_context.TryGetValue(memberInfo, out var value))
				{
					return value;
				}
				foreach (CustomAttributeData customAttributesDatum in memberInfo.GetCustomAttributesData())
				{
					if (customAttributesDatum.AttributeType.Name == "NullableContextAttribute" && customAttributesDatum.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttributesDatum.ConstructorArguments.Count == 1)
					{
						value = TranslateByte(customAttributesDatum.ConstructorArguments[0].Value);
						_context.Add(memberInfo, value);
						return value;
					}
				}
				memberInfo = memberInfo.DeclaringType;
			}
			return null;
		}

		public NullabilityInfo Create(ParameterInfo parameterInfo)
		{
			NetstandardHelpers.ThrowIfNull(parameterInfo, "parameterInfo");
			IList<CustomAttributeData> customAttributesData = parameterInfo.GetCustomAttributesData();
			NullableAttributeStateParser parser = ((parameterInfo.Member is MethodBase method && IsPrivateOrInternalMethodAndAnnotationDisabled(method)) ? NullableAttributeStateParser.Unknown : CreateParser(customAttributesData));
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(parameterInfo.Member, parameterInfo.ParameterType, parser);
			if (nullabilityInfo.ReadState != 0)
			{
				CheckParameterMetadataType(parameterInfo, nullabilityInfo);
			}
			CheckNullabilityAttributes(nullabilityInfo, customAttributesData);
			return nullabilityInfo;
		}

		private void CheckParameterMetadataType(ParameterInfo parameter, NullabilityInfo nullability)
		{
			MemberInfo member = parameter.Member;
			MemberInfo metaMember;
			ParameterInfo parameterInfo;
			if (!(member is ConstructorInfo member2))
			{
				if (!(member is MethodInfo method))
				{
					return;
				}
				MethodInfo methodMetadataDefinition = GetMethodMetadataDefinition(method);
				metaMember = methodMetadataDefinition;
				parameterInfo = (string.IsNullOrEmpty(parameter.Name) ? methodMetadataDefinition.ReturnParameter : GetMetaParameter(methodMetadataDefinition, parameter));
			}
			else
			{
				parameterInfo = GetMetaParameter((MethodBase)(metaMember = (ConstructorInfo)GetMemberMetadataDefinition(member2)), parameter);
			}
			if (parameterInfo != null)
			{
				CheckGenericParameters(nullability, metaMember, parameterInfo.ParameterType, parameter.Member.ReflectedType);
			}
		}

		private static ParameterInfo GetMetaParameter(MethodBase metaMethod, ParameterInfo parameter)
		{
			ReadOnlySpan<ParameterInfo> parametersAsSpan = metaMethod.GetParametersAsSpan();
			for (int i = 0; i < parametersAsSpan.Length; i++)
			{
				if (parameter.Position == i && parameter.Name == parametersAsSpan[i].Name)
				{
					return parametersAsSpan[i];
				}
			}
			return null;
		}

		private static MethodInfo GetMethodMetadataDefinition(MethodInfo method)
		{
			if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
			{
				method = method.GetGenericMethodDefinition();
			}
			return (MethodInfo)GetMemberMetadataDefinition(method);
		}

		private static void CheckNullabilityAttributes(NullabilityInfo nullability, IList<CustomAttributeData> attributes)
		{
			NullabilityState nullabilityState = NullabilityState.Unknown;
			NullabilityState nullabilityState2 = NullabilityState.Unknown;
			foreach (CustomAttributeData attribute in attributes)
			{
				if (attribute.AttributeType.Namespace == "System.Diagnostics.CodeAnalysis")
				{
					if (attribute.AttributeType.Name == "NotNullAttribute")
					{
						nullabilityState = NullabilityState.NotNull;
					}
					else if ((attribute.AttributeType.Name == "MaybeNullAttribute" || attribute.AttributeType.Name == "MaybeNullWhenAttribute") && nullabilityState == NullabilityState.Unknown && !IsValueTypeOrValueTypeByRef(nullability.Type))
					{
						nullabilityState = NullabilityState.Nullable;
					}
					else if (attribute.AttributeType.Name == "DisallowNullAttribute")
					{
						nullabilityState2 = NullabilityState.NotNull;
					}
					else if (attribute.AttributeType.Name == "AllowNullAttribute" && nullabilityState2 == NullabilityState.Unknown && !IsValueTypeOrValueTypeByRef(nullability.Type))
					{
						nullabilityState2 = NullabilityState.Nullable;
					}
				}
			}
			if (nullabilityState != 0)
			{
				nullability.ReadState = nullabilityState;
			}
			if (nullabilityState2 != 0)
			{
				nullability.WriteState = nullabilityState2;
			}
		}

		public NullabilityInfo Create(PropertyInfo propertyInfo)
		{
			NetstandardHelpers.ThrowIfNull(propertyInfo, "propertyInfo");
			MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true);
			MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
			NullableAttributeStateParser parser = (((getMethod == null || IsPrivateOrInternalMethodAndAnnotationDisabled(getMethod)) && (setMethod == null || IsPrivateOrInternalMethodAndAnnotationDisabled(setMethod))) ? NullableAttributeStateParser.Unknown : CreateParser(propertyInfo.GetCustomAttributesData()));
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(propertyInfo, propertyInfo.PropertyType, parser);
			if (getMethod != null)
			{
				CheckNullabilityAttributes(nullabilityInfo, getMethod.ReturnParameter.GetCustomAttributesData());
			}
			else
			{
				nullabilityInfo.ReadState = NullabilityState.Unknown;
			}
			if (setMethod != null)
			{
				ReadOnlySpan<ParameterInfo> parametersAsSpan = setMethod.GetParametersAsSpan();
				ParameterInfo parameterInfo = parametersAsSpan[parametersAsSpan.Length - 1];
				CheckNullabilityAttributes(nullabilityInfo, parameterInfo.GetCustomAttributesData());
			}
			else
			{
				nullabilityInfo.WriteState = NullabilityState.Unknown;
			}
			return nullabilityInfo;
		}

		private bool IsPrivateOrInternalMethodAndAnnotationDisabled(MethodBase method)
		{
			if ((method.IsPrivate || method.IsFamilyAndAssembly || method.IsAssembly) && IsPublicOnly(method.IsPrivate, method.IsFamilyAndAssembly, method.IsAssembly, method.Module))
			{
				return true;
			}
			return false;
		}

		public NullabilityInfo Create(EventInfo eventInfo)
		{
			NetstandardHelpers.ThrowIfNull(eventInfo, "eventInfo");
			return GetNullabilityInfo(eventInfo, eventInfo.EventHandlerType, CreateParser(eventInfo.GetCustomAttributesData()));
		}

		public NullabilityInfo Create(FieldInfo fieldInfo)
		{
			NetstandardHelpers.ThrowIfNull(fieldInfo, "fieldInfo");
			IList<CustomAttributeData> customAttributesData = fieldInfo.GetCustomAttributesData();
			NullableAttributeStateParser parser = (IsPrivateOrInternalFieldAndAnnotationDisabled(fieldInfo) ? NullableAttributeStateParser.Unknown : CreateParser(customAttributesData));
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(fieldInfo, fieldInfo.FieldType, parser);
			CheckNullabilityAttributes(nullabilityInfo, customAttributesData);
			return nullabilityInfo;
		}

		private bool IsPrivateOrInternalFieldAndAnnotationDisabled(FieldInfo fieldInfo)
		{
			if ((fieldInfo.IsPrivate || fieldInfo.IsFamilyAndAssembly || fieldInfo.IsAssembly) && IsPublicOnly(fieldInfo.IsPrivate, fieldInfo.IsFamilyAndAssembly, fieldInfo.IsAssembly, fieldInfo.Module))
			{
				return true;
			}
			return false;
		}

		private bool IsPublicOnly(bool isPrivate, bool isFamilyAndAssembly, bool isAssembly, Module module)
		{
			if (!_publicOnlyModules.TryGetValue(module, out var value))
			{
				value = PopulateAnnotationInfo(module.GetCustomAttributesData());
				_publicOnlyModules.Add(module, value);
			}
			if (value == NotAnnotatedStatus.None)
			{
				return false;
			}
			if (((isPrivate || isFamilyAndAssembly) && value.HasFlag(NotAnnotatedStatus.Private)) || (isAssembly && value.HasFlag(NotAnnotatedStatus.Internal)))
			{
				return true;
			}
			return false;
		}

		private static NotAnnotatedStatus PopulateAnnotationInfo(IList<CustomAttributeData> customAttributes)
		{
			bool flag = default(bool);
			foreach (CustomAttributeData customAttribute in customAttributes)
			{
				if (customAttribute.AttributeType.Name == "NullablePublicOnlyAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttribute.ConstructorArguments.Count == 1)
				{
					object value = customAttribute.ConstructorArguments[0].Value;
					int num;
					if (value is bool)
					{
						flag = (bool)value;
						num = 1;
					}
					else
					{
						num = 0;
					}
					if (((uint)num & (flag ? 1u : 0u)) != 0)
					{
						return NotAnnotatedStatus.Private | NotAnnotatedStatus.Internal;
					}
					return NotAnnotatedStatus.Private;
				}
			}
			return NotAnnotatedStatus.None;
		}

		private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser)
		{
			int index = 0;
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(memberInfo, type, parser, ref index);
			if (nullabilityInfo.ReadState != 0)
			{
				TryLoadGenericMetaTypeNullability(memberInfo, nullabilityInfo);
			}
			return nullabilityInfo;
		}

		private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser, ref int index)
		{
			NullabilityState state = NullabilityState.Unknown;
			NullabilityInfo elementType = null;
			NullabilityInfo[] array = Array.Empty<NullabilityInfo>();
			Type type2 = type;
			if (type2.IsByRef || type2.IsPointer)
			{
				type2 = type2.GetElementType();
			}
			if (type2.IsValueType)
			{
				Type underlyingType = Nullable.GetUnderlyingType(type2);
				if ((object)underlyingType != null)
				{
					type2 = underlyingType;
					state = NullabilityState.Nullable;
				}
				else
				{
					state = NullabilityState.NotNull;
				}
				if (type2.IsGenericType)
				{
					index++;
				}
			}
			else
			{
				if (!parser.ParseNullableState(index++, ref state))
				{
					NullabilityState? nullableContext = GetNullableContext(memberInfo);
					if (nullableContext.HasValue)
					{
						NullabilityState valueOrDefault = nullableContext.GetValueOrDefault();
						state = valueOrDefault;
					}
				}
				if (type2.IsArray)
				{
					elementType = GetNullabilityInfo(memberInfo, type2.GetElementType(), parser, ref index);
				}
			}
			if (type2.IsGenericType)
			{
				Type[] genericArguments = type2.GetGenericArguments();
				array = new NullabilityInfo[genericArguments.Length];
				for (int i = 0; i < genericArguments.Length; i++)
				{
					array[i] = GetNullabilityInfo(memberInfo, genericArguments[i], parser, ref index);
				}
			}
			return new NullabilityInfo(type, state, state, elementType, array);
		}

		private static NullableAttributeStateParser CreateParser(IList<CustomAttributeData> customAttributes)
		{
			foreach (CustomAttributeData customAttribute in customAttributes)
			{
				if (customAttribute.AttributeType.Name == "NullableAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttribute.ConstructorArguments.Count == 1)
				{
					return new NullableAttributeStateParser(customAttribute.ConstructorArguments[0].Value);
				}
			}
			return new NullableAttributeStateParser(null);
		}

		private void TryLoadGenericMetaTypeNullability(MemberInfo memberInfo, NullabilityInfo nullability)
		{
			MemberInfo memberMetadataDefinition = GetMemberMetadataDefinition(memberInfo);
			Type type = null;
			if (memberMetadataDefinition is FieldInfo fieldInfo)
			{
				type = fieldInfo.FieldType;
			}
			else if (memberMetadataDefinition is PropertyInfo property)
			{
				type = GetPropertyMetaType(property);
			}
			if (type != null)
			{
				CheckGenericParameters(nullability, memberMetadataDefinition, type, memberInfo.ReflectedType);
			}
		}

		private static MemberInfo GetMemberMetadataDefinition(MemberInfo member)
		{
			Type declaringType = member.DeclaringType;
			if (declaringType != null && declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
			{
				return NetstandardHelpers.GetMemberWithSameMetadataDefinitionAs(declaringType.GetGenericTypeDefinition(), member);
			}
			return member;
		}

		private static Type GetPropertyMetaType(PropertyInfo property)
		{
			MethodInfo getMethod = property.GetGetMethod(nonPublic: true);
			if ((object)getMethod != null)
			{
				return getMethod.ReturnType;
			}
			return property.GetSetMethod(nonPublic: true).GetParametersAsSpan()[0].ParameterType;
		}

		private void CheckGenericParameters(NullabilityInfo nullability, MemberInfo metaMember, Type metaType, Type reflectedType)
		{
			if (metaType.IsGenericParameter)
			{
				if (nullability.ReadState == NullabilityState.NotNull)
				{
					TryUpdateGenericParameterNullability(nullability, metaType, reflectedType);
				}
			}
			else
			{
				if (!metaType.ContainsGenericParameters)
				{
					return;
				}
				if (nullability.GenericTypeArguments.Length != 0)
				{
					Type[] genericArguments = metaType.GetGenericArguments();
					for (int i = 0; i < genericArguments.Length; i++)
					{
						CheckGenericParameters(nullability.GenericTypeArguments[i], metaMember, genericArguments[i], reflectedType);
					}
					return;
				}
				NullabilityInfo elementType = nullability.ElementType;
				if (elementType != null && metaType.IsArray)
				{
					CheckGenericParameters(elementType, metaMember, metaType.GetElementType(), reflectedType);
				}
				else if (metaType.IsByRef)
				{
					CheckGenericParameters(nullability, metaMember, metaType.GetElementType(), reflectedType);
				}
			}
		}

		private bool TryUpdateGenericParameterNullability(NullabilityInfo nullability, Type genericParameter, Type reflectedType)
		{
			if ((object)reflectedType != null && !genericParameter.IsGenericMethodParameter() && TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, reflectedType, reflectedType))
			{
				return true;
			}
			if (IsValueTypeOrValueTypeByRef(nullability.Type))
			{
				return true;
			}
			NullabilityState state = NullabilityState.Unknown;
			if (CreateParser(genericParameter.GetCustomAttributesData()).ParseNullableState(0, ref state))
			{
				nullability.ReadState = state;
				nullability.WriteState = state;
				return true;
			}
			NullabilityState? nullableContext = GetNullableContext(genericParameter);
			if (nullableContext.HasValue)
			{
				NullabilityState writeState = (nullability.ReadState = nullableContext.GetValueOrDefault());
				nullability.WriteState = writeState;
				return true;
			}
			return false;
		}

		private bool TryUpdateGenericTypeParameterNullabilityFromReflectedType(NullabilityInfo nullability, Type genericParameter, Type context, Type reflectedType)
		{
			Type type2 = ((context.IsGenericType && !context.IsGenericTypeDefinition) ? context.GetGenericTypeDefinition() : context);
			if (genericParameter.DeclaringType == type2)
			{
				return false;
			}
			Type baseType = type2.BaseType;
			if ((object)baseType == null)
			{
				return false;
			}
			if (!baseType.IsGenericType || (baseType.IsGenericTypeDefinition ? baseType : baseType.GetGenericTypeDefinition()) != genericParameter.DeclaringType)
			{
				return TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, baseType, reflectedType);
			}
			Type[] genericArguments = baseType.GetGenericArguments();
			Type type3 = genericArguments[genericParameter.GenericParameterPosition];
			if (type3.IsGenericParameter)
			{
				return TryUpdateGenericParameterNullability(nullability, type3, reflectedType);
			}
			NullableAttributeStateParser parser = CreateParser(type2.GetCustomAttributesData());
			int index = 1;
			for (int i = 0; i < genericParameter.GenericParameterPosition; i++)
			{
				index += CountNullabilityStates(genericArguments[i]);
			}
			return TryPopulateNullabilityInfo(nullability, parser, ref index);
			static int CountNullabilityStates(Type type)
			{
				Type type4 = Nullable.GetUnderlyingType(type) ?? type;
				if (type4.IsGenericType)
				{
					int num = 1;
					Type[] genericArguments2 = type4.GetGenericArguments();
					foreach (Type type5 in genericArguments2)
					{
						num += CountNullabilityStates(type5);
					}
					return num;
				}
				if (type4.HasElementType)
				{
					return (type4.IsArray ? 1 : 0) + CountNullabilityStates(type4.GetElementType());
				}
				return (!type.IsValueType) ? 1 : 0;
			}
		}

		private static bool TryPopulateNullabilityInfo(NullabilityInfo nullability, NullableAttributeStateParser parser, ref int index)
		{
			bool flag = IsValueTypeOrValueTypeByRef(nullability.Type);
			if (!flag)
			{
				NullabilityState state = NullabilityState.Unknown;
				if (!parser.ParseNullableState(index, ref state))
				{
					return false;
				}
				nullability.ReadState = state;
				nullability.WriteState = state;
			}
			if (!flag || (Nullable.GetUnderlyingType(nullability.Type) ?? nullability.Type).IsGenericType)
			{
				index++;
			}
			if (nullability.GenericTypeArguments.Length != 0)
			{
				NullabilityInfo[] genericTypeArguments = nullability.GenericTypeArguments;
				for (int i = 0; i < genericTypeArguments.Length; i++)
				{
					TryPopulateNullabilityInfo(genericTypeArguments[i], parser, ref index);
				}
			}
			else
			{
				NullabilityInfo elementType = nullability.ElementType;
				if (elementType != null)
				{
					TryPopulateNullabilityInfo(elementType, parser, ref index);
				}
			}
			return true;
		}

		private static NullabilityState TranslateByte(object value)
		{
			if (!(value is byte b))
			{
				return NullabilityState.Unknown;
			}
			return TranslateByte(b);
		}

		private static NullabilityState TranslateByte(byte b)
		{
			return b switch
			{
				1 => NullabilityState.NotNull, 
				2 => NullabilityState.Nullable, 
				_ => NullabilityState.Unknown, 
			};
		}

		private static bool IsValueTypeOrValueTypeByRef(Type type)
		{
			if (!type.IsValueType)
			{
				if (type.IsByRef || type.IsPointer)
				{
					return type.GetElementType().IsValueType;
				}
				return false;
			}
			return true;
		}
	}
	internal static class NetstandardHelpers
	{
		public static void ThrowIfNull(object argument, string paramName)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
			static void Throw(string paramName)
			{
				throw new ArgumentNullException(paramName);
			}
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This is finding the MemberInfo with the same MetadataToken as specified MemberInfo. If the specified MemberInfo exists and wasn't trimmed, then the current Type's MemberInfo couldn't have been trimmed.")]
		public static MemberInfo GetMemberWithSameMetadataDefinitionAs(this Type type, MemberInfo member)
		{
			ThrowIfNull(member, "member");
			MemberInfo[] members = type.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MemberInfo memberInfo in members)
			{
				if (HasSameMetadataDefinitionAs(memberInfo, member))
				{
					return memberInfo;
				}
			}
			throw new MissingMemberException(type.FullName, member.Name);
		}

		private static bool HasSameMetadataDefinitionAs(this MemberInfo info, MemberInfo other)
		{
			if (info.MetadataToken != other.MetadataToken)
			{
				return false;
			}
			if (!info.Module.Equals(other.Module))
			{
				return false;
			}
			return true;
		}

		public static bool IsGenericMethodParameter(this Type type)
		{
			if (type.IsGenericParameter)
			{
				return (object)type.DeclaringMethod != null;
			}
			return false;
		}

		public static ReadOnlySpan<ParameterInfo> GetParametersAsSpan(this MethodBase metaMethod)
		{
			return metaMethod.GetParameters();
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class DynamicDependencyAttribute : Attribute
	{
		public string MemberSignature { get; }

		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public Type Type { get; }

		public string TypeName { get; }

		public string AssemblyName { get; }

		public string Condition { get; set; }

		public DynamicDependencyAttribute(string memberSignature)
		{
			MemberSignature = memberSignature;
		}

		public DynamicDependencyAttribute(string memberSignature, Type type)
		{
			MemberSignature = memberSignature;
			Type = type;
		}

		public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName)
		{
			MemberSignature = memberSignature;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type)
		{
			MemberTypes = memberTypes;
			Type = type;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName)
		{
			MemberTypes = memberTypes;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | 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,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string Scope { get; set; }

		public string Target { get; set; }

		public string MessageId { get; set; }

		public string Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class StringSyntaxAttribute : Attribute
	{
		public const string CompositeFormat = "CompositeFormat";

		public const string DateOnlyFormat = "DateOnlyFormat";

		public const string DateTimeFormat = "DateTimeFormat";

		public const string EnumFormat = "EnumFormat";

		public const string GuidFormat = "GuidFormat";

		public const string Json = "Json";

		public const string NumericFormat = "NumericFormat";

		public const string Regex = "Regex";

		public const string TimeOnlyFormat = "TimeOnlyFormat";

		public const string TimeSpanFormat = "TimeSpanFormat";

		public const string Uri = "Uri";

		public const string Xml = "Xml";

		public string Syntax { get; }

		public object[] Arguments { get; }

		public StringSyntaxAttribute(string syntax)
		{
			Syntax = syntax;
			Arguments = Array.Empty<object>();
		}

		public StringSyntaxAttribute(string syntax, params object[] arguments)
		{
			Syntax = syntax;
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[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.Collections
{
	internal static class HashHelpers
	{
		public const uint HashCollisionThreshold = 100u;

		public const int MaxPrimeArrayLength = 2147483587;

		public const int HashPrime = 101;

		internal static ReadOnlySpan<int> Primes
		{
			get
			{
				object obj = global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6;
				if (obj == null)
				{
					obj = new int[72]
					{
						3, 7, 11, 17, 23, 29, 37, 47, 59, 71,
						89, 107, 131, 163, 197, 239, 293, 353, 431, 521,
						631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371,
						4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023,
						25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363,
						156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403,
						968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559,
						5999471, 7199369
					};
					global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6 = (int[])obj;
				}
				return new ReadOnlySpan<int>((int[]?)obj);
			}
		}

		public static bool IsPrime(int candidate)
		{
			if (((uint)candidate & (true ? 1u : 0u)) != 0)
			{
				int num = (int)Math.Sqrt(candidate);
				for (int i = 3; i <= num; i += 2)
				{
					if (candidate % i == 0)
					{
						return false;
					}
				}
				return true;
			}
			return candidate == 2;
		}

		public static int GetPrime(int min)
		{
			if (min < 0)
			{
				throw new ArgumentException(System.SR.Arg_HTCapacityOverflow);
			}
			ReadOnlySpan<int> primes = Primes;
			for (int i = 0; i < primes.Length; i++)
			{
				int num = primes[i];
				if (num >= min)
				{
					return num;
				}
			}
			for (int j = min | 1; j < int.MaxValue; j += 2)
			{
				if (IsPrime(j) && (j - 1) % 101 != 0)
				{
					return j;
				}
			}
			return min;
		}

		public static int ExpandPrime(int oldSize)
		{
			int num = 2 * oldSize;
			if ((uint)num > 2147483587u && 2147483587 > oldSize)
			{
				return 2147483587;
			}
			return GetPrime(num);
		}

		public static ulong GetFastModMultiplier(uint divisor)
		{
			return ulong.MaxValue / (ulong)divisor + 1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint FastMod(uint value, uint divisor, ulong multiplier)
		{
			return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32);
		}
	}
	internal static class ThrowHelper
	{
		[DoesNotReturn]
		internal static void ThrowKeyNotFound<TKey>(TKey key)
		{
			throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key));
		}

		[DoesNotReturn]
		internal static void ThrowDuplicateKey<TKey>(TKey key)
		{
			throw new ArgumentException(System.SR.Format(System.SR.Argument_AddingDuplicate, key), "key");
		}

		[DoesNotReturn]
		internal static void ThrowConcurrentOperation()
		{
			throw new InvalidOperationException(System.SR.InvalidOperation_ConcurrentOperationsNotSupported);
		}

		[DoesNotReturn]
		internal static void ThrowIndexArgumentOutOfRange()
		{
			throw new ArgumentOutOfRangeException("index");
		}

		[DoesNotReturn]
		internal static void ThrowVersionCheckFailed()
		{
			throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion);
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowNull(paramName);
			}
		}

		public static void ThrowIfNegative(int value, [CallerArgumentExpression("value")] string paramName = null)
		{
			if (value < 0)
			{
				ThrowNegative(value, paramName);
			}
		}

		public static void ThrowIfGreaterThan<T>(T value, T other, [CallerArgumentExpression("value")] string paramName = null) where T : IComparable<T>
		{
			if (value.CompareTo(other) > 0)
			{
				ThrowGreater(value, other, paramName);
			}
		}

		public static void ThrowIfLessThan<T>(T value, T other, [CallerArgumentExpression("value")] string paramName = null) where T : IComparable<T>
		{
			if (value.CompareTo(other) < 0)
			{
				ThrowLess(value, other, paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowNull(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[DoesNotReturn]
		private static void ThrowNegative(int value, string paramName)
		{
			throw new ArgumentOutOfRangeException(paramName, value, System.SR.Format(System.SR.ArgumentOutOfRange_Generic_MustBeNonNegative, paramName, value));
		}

		[DoesNotReturn]
		private static void ThrowGreater<T>(T value, T other, string paramName)
		{
			throw new ArgumentOutOfRangeException(paramName, value, System.SR.Format(System.SR.ArgumentOutOfRange_Generic_MustBeLessOrEqual, paramName, value, other));
		}

		[DoesNotReturn]
		private static void ThrowLess<T>(T value, T other, string paramName)
		{
			throw new ArgumentOutOfRangeException(paramName, value, System.SR.Format(System.SR.ArgumentOutOfRange_Generic_MustBeGreaterOrEqual, paramName, value, other));
		}
	}
}
namespace System.Collections.ObjectModel
{
	internal static class CollectionHelpers
	{
		internal static void ValidateCopyToArguments(int sourceCount, Array array, int index)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (array.Rank != 1)
			{
				throw new ArgumentException(System.SR.Arg_RankMultiDimNotSupported, "array");
			}
			if (array.GetLowerBound(0) != 0)
			{
				throw new ArgumentException(System.SR.Arg_NonZeroLowerBound, "array");
			}
			if (index < 0 || index > array.Length)
			{
				throw new ArgumentOutOfRangeException("index");
			}
			if (array.Length - index < sourceCount)
			{
				throw new ArgumentException(System.SR.Arg_ArrayPlusOffTooSmall);
			}
		}

		internal static void CopyTo<T>(ICollection<T> collection, Array array, int index)
		{
			ValidateCopyToArguments(collection.Count, array, index);
			if (collection is ICollection collection2)
			{
				collection2.CopyTo(array, index);
				return;
			}
			if (array is T[] array2)
			{
				collection.CopyTo(array2, index);
				return;
			}
			if (!(array is object[] array3))
			{
				throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array");
			}
			try
			{
				foreach (T item in collection)
				{
					array3[index++] = item;
				}
			}
			catch (ArrayTypeMismatchException)
			{
				throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array");
			}
		}
	}
}
namespace System.Collections.Generic
{
	internal sealed class ReferenceEqualityComparer : IEqualityComparer<object>, IEqualityComparer
	{
		public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer();


		private ReferenceEqualityComparer()
		{
		}

		public new bool Equals(object x, object y)
		{
			return x == y;
		}

		public int GetHashCode(object obj)
		{
			return RuntimeHelpers.GetHashCode(obj);
		}
	}
	[DebuggerDisplay("{Value}", Name = "[{Key}]")]
	internal readonly struct DebugViewDictionaryItem<TKey, TValue>
	{
		[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
		public TKey Key { get; }

		[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
		public TValue Value { get; }

		public DebugViewDictionaryItem(TKey key, TValue value)
		{
			Key = key;
			Value = value;
		}

		public DebugViewDictionaryItem(KeyValuePair<TKey, TValue> keyValue)
		{
			Key = keyValue.Key;
			Value = keyValue.Value;
		}
	}
	internal sealed class ICollectionDebugView<T>
	{
		private readonly ICollection<T> _collection;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public T[] Items
		{
			get
			{
				T[] array = new T[_collection.Count];
				_collection.CopyTo(array, 0);
				return array;
			}
		}

		public ICollectionDebugView(ICollection<T> collection)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			_collection = collection;
		}
	}
	internal sealed class IDictionaryDebugView<TKey, TValue>
	{
		private readonly IDictionary<TKey, TValue> _dict;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public DebugViewDictionaryItem<TKey, TValue>[] Items
		{
			get
			{
				KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[_dict.Count];
				_dict.CopyTo(array, 0);
				DebugViewDictionaryItem<TKey, TValue>[] array2 = new DebugViewDictionaryItem<TKey, TValue>[array.Length];
				for (int i = 0; i < array2.Length; i++)
				{
					array2[i] = new DebugViewDictionaryItem<TKey, TValue>(array[i]);
				}
				return array2;
			}
		}

		public IDictionaryDebugView(IDictionary<TKey, TValue> dictionary)
		{
			_dict = dictionary ?? throw new ArgumentNullException("dictionary");
		}
	}
	internal sealed class DictionaryKeyCollectionDebugView<TKey, TValue>
	{
		private readonly ICollection<TKey> _collection;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public TKey[] Items
		{
			get
			{
				TKey[] array = new TKey[_collection.Count];
				_collection.CopyTo(array, 0);
				return array;
			}
		}

		public DictionaryKeyCollectionDebugView(ICollection<TKey> collection)
		{
			_collection = collection ?? throw new ArgumentNullException("collection");
		}
	}
	internal sealed class DictionaryValueCollectionDebugView<TKey, TValue>
	{
		private readonly ICollection<TValue> _collection;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public TValue[] Items
		{
			get
			{
				TValue[] array = new TValue[_collection.Count];
				_collection.CopyTo(array, 0);
				return array;
			}
		}

		public DictionaryValueCollectionDebugView(ICollection<TValue> collection)
		{
			_collection = collection ?? throw new ArgumentNullException("collection");
		}
	}
	internal static class EnumerableHelpers
	{
		internal static void Reset<T>(ref T enumerator) where T : IEnumerator
		{
			enumerator.Reset();
		}

		internal static IEnumerator<T> GetEmptyEnumerator<T>()
		{
			return ((IEnumerable<T>)Array.Empty<T>()).GetEnumerator();
		}

		internal static T[] ToArray<T>(IEnumerable<T> source, out int length)
		{
			if (source is ICollection<T> collection)
			{
				int count = collection.Count;
				if (count != 0)
				{
					T[] array = new T[count];
					collection.CopyTo(array, 0);
					length = count;
					return array;
				}
			}
			else
			{
				using IEnumerator<T> enumerator = source.GetEnumerator();
				if (enumerator.MoveNext())
				{
					T[] array2 = new T[4]
					{
						enumerator.Current,
						default(T),
						default(T),
						default(T)
					};
					int num = 1;
					while (enumerator.MoveNext())
					{
						if (num == array2.Length)
						{
							int num2 = num << 1;
							if ((uint)num2 > 2147483591u)
							{
								num2 = ((2147483591 <= num) ? (num + 1) : 2147483591);
							}
							Array.Resize(ref array2, num2);
						}
						array2[num++] = enumerator.Current;
					}
					length = num;
					return array2;
				}
			}
			length = 0;
			return Array.Empty<T>();
		}
	}
	[DebuggerTypeProxy(typeof(System.Collections.Generic.IDictionaryDebugView<, >))]
	[DebuggerDisplay("Count = {Count}")]
	internal sealed class OrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IList<KeyValuePair<TKey, TValue>>, IReadOnlyList<KeyValuePair<TKey, TValue>>, IList
	{
		private struct Entry
		{
			public int Next;

			public uint HashCode;

			public TKey Key;

			public TValue Value;
		}

		[StructLayout(LayoutKind.Auto)]
		public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IEnumerator, IDisposable, IDictionaryEnumerator
		{
			private readonly OrderedDictionary<TKey, TValue> _dictionary;

			private readonly int _version;

			private readonly bool _useDictionaryEntry;

			private int _index;

			public KeyValuePair<TKey, TValue> Current { get; private set; }

			readonly object IEnumerator.Current
			{
				get
				{
					if (!_useDictionaryEntry)
					{
						return Current;
					}
					return new DictionaryEntry(Current.Key, Current.Value);
				}
			}

			readonly DictionaryEntry IDictionaryEnumerator.Entry => new DictionaryEntry(Current.Key, Current.Value);

			readonly object IDictionaryEnumerator.Key => Current.Key;

			readonly object IDictionaryEnumerator.Value => Current.Value;

			internal Enumerator(OrderedDictionary<TKey, TValue> dictionary, bool useDictionaryEntry)
			{
				_index = 0;
				_dictionary = dictionary;
				_version = _dictionary._version;
				_useDictionaryEntry = useDictionaryEntry;
			}

			public bool MoveNext()
			{
				OrderedDictionary<TKey, TValue> dictionary = _dictionary;
				if (_version != dictionary._version)
				{
					ThrowHelper.ThrowVersionCheckFailed();
				}
				if (_index < dictionary._count)
				{
					ref Entry reference = ref dictionary._entries[_index];
					Current = new KeyValuePair<TKey, TValue>(reference.Key, reference.Value);
					_index++;
					return true;
				}
				Current = default(KeyValuePair<TKey, TValue>);
				return false;
			}

			void IEnumerator.Reset()
			{
				if (_version != _dictionary._version)
				{
					ThrowHelper.ThrowVersionCheckFailed();
				}
				_index = 0;
				Current = default(KeyValuePair<TKey, TValue>);
			}

			readonly void IDisposable.Dispose()
			{
			}
		}

		[DebuggerTypeProxy(typeof(System.Collections.Generic.ICollectionDebugView<>))]
		[DebuggerDisplay("Count = {Count}")]
		public sealed class KeyCollection : IList<TKey>, ICollection<TKey>, IEnumerable<TKey>, IEnumerable, IReadOnlyList<TKey>, IReadOnlyCollection<TKey>, IList, ICollection
		{
			public struct Enumerator : IEnumerator<TKey>, IEnumerator, IDisposable
			{
				private OrderedDictionary<TKey, TValue>.Enumerator _enumerator;

				public TKey Current => _enumerator.Current.Key;

				object IEnumerator.Current => Current;

				internal Enumerator(OrderedDictionary<TKey, TValue> dictionary)
				{
					_enumerator = dictionary.GetEnumerator();
				}

				public bool MoveNext()
				{
					return _enumerator.MoveNext();
				}

				void IEnumerator.Reset()
				{
					System.Collections.Generic.EnumerableHelpers.Reset(ref _enumerator);
				}

				readonly void IDisposable.Dispose()
				{
				}
			}

			private readonly OrderedDictionary<TKey, TValue> _dictionary;

			public int Count => _dictionary.Count;

			bool ICollection<TKey>.IsReadOnly => true;

			bool IList.IsReadOnly => true;

			bool IList.IsFixedSize => false;

			bool ICollection.IsSynchronized => false;

			object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;

			TKey IList<TKey>.this[int index]
			{
				get
				{
					return _dictionary.GetAt(index).Key;
				}
				set
				{
					throw new NotSupportedException();
				}
			}

			object IList.this[int index]
			{
				get
				{
					return _dictionary.GetAt(index).Key;
				}
				set
				{
					throw new NotSupportedException();
				}
			}

			TKey IReadOnlyList<TKey>.this[int index] => _dictionary.GetAt(index).Key;

			internal KeyCollection(OrderedDictionary<TKey, TValue> dictionary)
			{
				_dictionary = dictionary;
			}

			public bool Contains(TKey key)
			{
				return _dictionary.ContainsKey(key);
			}

			bool IList.Contains(object value)
			{
				if (value is TKey key)
				{
					return Contains(key);
				}
				return false;
			}

			public void CopyTo(TKey[] array, int arrayIndex)
			{
				ThrowHelper.ThrowIfNull(array, "array");
				ThrowHelper.ThrowIfNegative(arrayIndex, "arrayIndex");
				OrderedDictionary<TKey, TValue> dictionary = _dictionary;
				int count = dictionary._count;
				if (array.Length - arrayIndex < count)
				{
					throw new ArgumentException(System.SR.Arg_ArrayPlusOffTooSmall, "array");
				}
				Entry[] entries = dictionary._entries;
				for (int i = 0; i < count; i++)
				{
					array[arrayIndex++] = entries[i].Key;
				}
			}

			void ICollection.CopyTo(Array array, int index)
			{
				ThrowHelper.ThrowIfNull(array, "array");
				if (array.Rank != 1)
				{
					throw new ArgumentException(System.SR.Arg_RankMultiDimNotSupported, "array");
				}
				if (array.GetLowerBound(0) != 0)
				{
					throw new ArgumentException(System.SR.Arg_NonZeroLowerBound, "array");
				}
				ThrowHelper.ThrowIfNegative(index, "index");
				if (array.Length - index < _dictionary.Count)
				{
					throw new ArgumentException(System.SR.Arg_ArrayPlusOffTooSmall);
				}
				if (array is TKey[] array2)
				{
					CopyTo(array2, index);
					return;
				}
				try
				{
					if (!(array is object[] array3))
					{
						throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array");
					}
					using Enumerator enumerator = GetEnumerator();
					while (enumerator.MoveNext())
					{
						TKey current = enumerator.Current;
						array3[index++] = current;
					}
				}
				catch (ArrayTypeMismatchException)
				{
					throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array");
				}
			}

			public Enumerator GetEnumerator()
			{
				return new Enumerator(_dictionary);
			}

			IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
			{
				if (Count != 0)
				{
					return GetEnumerator();
				}
				return System.Collections.Generic.EnumerableHelpers.GetEmptyEnumerator<TKey>();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<TKey>)this).GetEnumerator();
			}

			int IList<TKey>.IndexOf(TKey item)
			{
				return _dictionary.IndexOf(item);
			}

			void ICollection<TKey>.Add(TKey item)
			{
				throw new NotSupportedException();
			}

			void ICollection<TKey>.Clear()
			{
				throw new NotSupportedException();
			}

			void IList<TKey>.Insert(int index, TKey item)
			{
				throw new NotSupp

System.Threading.Tasks.Extensions.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Threading.Tasks.Extensions")]
[assembly: AssemblyDescription("System.Threading.Tasks.Extensions")]
[assembly: AssemblyDefaultAlias("System.Threading.Tasks.Extensions")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.28619.01")]
[assembly: AssemblyInformationalVersion("4.6.28619.01 @BuiltBy: dlab14-DDVSOWINAGE069 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/7601f4f6225089ffb291dc7d58293c7bbf5c5d4f")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyVersion("4.2.0.1")]
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
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowArgumentNullException(System.ExceptionArgument argument)
		{
			throw GetArgumentNullException(argument);
		}

		internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			throw GetArgumentOutOfRangeException(argument);
		}

		private static ArgumentNullException GetArgumentNullException(System.ExceptionArgument argument)
		{
			return new ArgumentNullException(GetArgumentName(argument));
		}

		private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			return new ArgumentOutOfRangeException(GetArgumentName(argument));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static string GetArgumentName(System.ExceptionArgument argument)
		{
			return argument.ToString();
		}
	}
	internal enum ExceptionArgument
	{
		task,
		source,
		state
	}
}
namespace System.Threading.Tasks
{
	[StructLayout(LayoutKind.Auto)]
	[AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))]
	public readonly struct ValueTask : IEquatable<ValueTask>
	{
		private sealed class ValueTaskSourceAsTask : TaskCompletionSource<bool>
		{
			private static readonly Action<object> s_completionAction = delegate(object state)
			{
				IValueTaskSource source;
				if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state);
					return;
				}
				valueTaskSourceAsTask._source = null;
				ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token);
				try
				{
					source.GetResult(valueTaskSourceAsTask._token);
					valueTaskSourceAsTask.TrySetResult(result: false);
				}
				catch (Exception exception)
				{
					if (status == ValueTaskSourceStatus.Canceled)
					{
						valueTaskSourceAsTask.TrySetCanceled();
					}
					else
					{
						valueTaskSourceAsTask.TrySetException(exception);
					}
				}
			};

			private IValueTaskSource _source;

			private readonly short _token;

			public ValueTaskSourceAsTask(IValueTaskSource source, short token)
			{
				_token = token;
				_source = source;
				source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None);
			}
		}

		private static readonly Task s_canceledTask = Task.Delay(-1, new CancellationToken(canceled: true));

		internal readonly object _obj;

		internal readonly short _token;

		internal readonly bool _continueOnCapturedContext;

		internal static Task CompletedTask { get; } = Task.Delay(0);


		public bool IsCompleted
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return true;
				}
				if (obj is Task task)
				{
					return task.IsCompleted;
				}
				return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending;
			}
		}

		public bool IsCompletedSuccessfully
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return true;
				}
				if (obj is Task task)
				{
					return task.Status == TaskStatus.RanToCompletion;
				}
				return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded;
			}
		}

		public bool IsFaulted
		{
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return false;
				}
				if (obj is Task task)
				{
					return task.IsFaulted;
				}
				return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted;
			}
		}

		public bool IsCanceled
		{
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return false;
				}
				if (obj is Task task)
				{
					return task.IsCanceled;
				}
				return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(Task task)
		{
			if (task == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task);
			}
			_obj = task;
			_continueOnCapturedContext = true;
			_token = 0;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(IValueTaskSource source, short token)
		{
			if (source == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source);
			}
			_obj = source;
			_token = token;
			_continueOnCapturedContext = true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private ValueTask(object obj, short token, bool continueOnCapturedContext)
		{
			_obj = obj;
			_token = token;
			_continueOnCapturedContext = continueOnCapturedContext;
		}

		public override int GetHashCode()
		{
			return _obj?.GetHashCode() ?? 0;
		}

		public override bool Equals(object obj)
		{
			if (obj is ValueTask)
			{
				return Equals((ValueTask)obj);
			}
			return false;
		}

		public bool Equals(ValueTask other)
		{
			if (_obj == other._obj)
			{
				return _token == other._token;
			}
			return false;
		}

		public static bool operator ==(ValueTask left, ValueTask right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ValueTask left, ValueTask right)
		{
			return !left.Equals(right);
		}

		public Task AsTask()
		{
			object obj = _obj;
			object obj2;
			if (obj != null)
			{
				obj2 = obj as Task;
				if (obj2 == null)
				{
					return GetTaskForValueTaskSource(Unsafe.As<IValueTaskSource>(obj));
				}
			}
			else
			{
				obj2 = CompletedTask;
			}
			return (Task)obj2;
		}

		public ValueTask Preserve()
		{
			if (_obj != null)
			{
				return new ValueTask(AsTask());
			}
			return this;
		}

		private Task GetTaskForValueTaskSource(IValueTaskSource t)
		{
			ValueTaskSourceStatus status = t.GetStatus(_token);
			if (status != 0)
			{
				try
				{
					t.GetResult(_token);
					return CompletedTask;
				}
				catch (Exception exception)
				{
					if (status == ValueTaskSourceStatus.Canceled)
					{
						return s_canceledTask;
					}
					TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
					taskCompletionSource.TrySetException(exception);
					return taskCompletionSource.Task;
				}
			}
			ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token);
			return valueTaskSourceAsTask.Task;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[StackTraceHidden]
		internal void ThrowIfCompletedUnsuccessfully()
		{
			object obj = _obj;
			if (obj != null)
			{
				if (obj is Task task)
				{
					task.GetAwaiter().GetResult();
				}
				else
				{
					Unsafe.As<IValueTaskSource>(obj).GetResult(_token);
				}
			}
		}

		public ValueTaskAwaiter GetAwaiter()
		{
			return new ValueTaskAwaiter(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext)
		{
			return new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _token, continueOnCapturedContext));
		}
	}
	[StructLayout(LayoutKind.Auto)]
	[AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))]
	public readonly struct ValueTask<TResult> : IEquatable<ValueTask<TResult>>
	{
		private sealed class ValueTaskSourceAsTask : TaskCompletionSource<TResult>
		{
			private static readonly Action<object> s_completionAction = delegate(object state)
			{
				IValueTaskSource<TResult> source;
				if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state);
					return;
				}
				valueTaskSourceAsTask._source = null;
				ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token);
				try
				{
					valueTaskSourceAsTask.TrySetResult(source.GetResult(valueTaskSourceAsTask._token));
				}
				catch (Exception exception)
				{
					if (status == ValueTaskSourceStatus.Canceled)
					{
						valueTaskSourceAsTask.TrySetCanceled();
					}
					else
					{
						valueTaskSourceAsTask.TrySetException(exception);
					}
				}
			};

			private IValueTaskSource<TResult> _source;

			private readonly short _token;

			public ValueTaskSourceAsTask(IValueTaskSource<TResult> source, short token)
			{
				_source = source;
				_token = token;
				source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None);
			}
		}

		private static Task<TResult> s_canceledTask;

		internal readonly object _obj;

		internal readonly TResult _result;

		internal readonly short _token;

		internal readonly bool _continueOnCapturedContext;

		public bool IsCompleted
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return true;
				}
				if (obj is Task<TResult> task)
				{
					return task.IsCompleted;
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending;
			}
		}

		public bool IsCompletedSuccessfully
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return true;
				}
				if (obj is Task<TResult> task)
				{
					return task.Status == TaskStatus.RanToCompletion;
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded;
			}
		}

		public bool IsFaulted
		{
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return false;
				}
				if (obj is Task<TResult> task)
				{
					return task.IsFaulted;
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted;
			}
		}

		public bool IsCanceled
		{
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return false;
				}
				if (obj is Task<TResult> task)
				{
					return task.IsCanceled;
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled;
			}
		}

		public TResult Result
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return _result;
				}
				if (obj is Task<TResult> task)
				{
					return task.GetAwaiter().GetResult();
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetResult(_token);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(TResult result)
		{
			_result = result;
			_obj = null;
			_continueOnCapturedContext = true;
			_token = 0;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(Task<TResult> task)
		{
			if (task == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task);
			}
			_obj = task;
			_result = default(TResult);
			_continueOnCapturedContext = true;
			_token = 0;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(IValueTaskSource<TResult> source, short token)
		{
			if (source == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source);
			}
			_obj = source;
			_token = token;
			_result = default(TResult);
			_continueOnCapturedContext = true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private ValueTask(object obj, TResult result, short token, bool continueOnCapturedContext)
		{
			_obj = obj;
			_result = result;
			_token = token;
			_continueOnCapturedContext = continueOnCapturedContext;
		}

		public override int GetHashCode()
		{
			if (_obj == null)
			{
				if (_result == null)
				{
					return 0;
				}
				return _result.GetHashCode();
			}
			return _obj.GetHashCode();
		}

		public override bool Equals(object obj)
		{
			if (obj is ValueTask<TResult>)
			{
				return Equals((ValueTask<TResult>)obj);
			}
			return false;
		}

		public bool Equals(ValueTask<TResult> other)
		{
			if (_obj == null && other._obj == null)
			{
				return EqualityComparer<TResult>.Default.Equals(_result, other._result);
			}
			if (_obj == other._obj)
			{
				return _token == other._token;
			}
			return false;
		}

		public static bool operator ==(ValueTask<TResult> left, ValueTask<TResult> right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ValueTask<TResult> left, ValueTask<TResult> right)
		{
			return !left.Equals(right);
		}

		public Task<TResult> AsTask()
		{
			object obj = _obj;
			if (obj == null)
			{
				return Task.FromResult(_result);
			}
			if (obj is Task<TResult> result)
			{
				return result;
			}
			return GetTaskForValueTaskSource(Unsafe.As<IValueTaskSource<TResult>>(obj));
		}

		public ValueTask<TResult> Preserve()
		{
			if (_obj != null)
			{
				return new ValueTask<TResult>(AsTask());
			}
			return this;
		}

		private Task<TResult> GetTaskForValueTaskSource(IValueTaskSource<TResult> t)
		{
			ValueTaskSourceStatus status = t.GetStatus(_token);
			if (status != 0)
			{
				try
				{
					return Task.FromResult(t.GetResult(_token));
				}
				catch (Exception exception)
				{
					if (status == ValueTaskSourceStatus.Canceled)
					{
						Task<TResult> task = s_canceledTask;
						if (task == null)
						{
							TaskCompletionSource<TResult> taskCompletionSource = new TaskCompletionSource<TResult>();
							taskCompletionSource.TrySetCanceled();
							task = (s_canceledTask = taskCompletionSource.Task);
						}
						return task;
					}
					TaskCompletionSource<TResult> taskCompletionSource2 = new TaskCompletionSource<TResult>();
					taskCompletionSource2.TrySetException(exception);
					return taskCompletionSource2.Task;
				}
			}
			ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token);
			return valueTaskSourceAsTask.Task;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTaskAwaiter<TResult> GetAwaiter()
		{
			return new ValueTaskAwaiter<TResult>(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext)
		{
			return new ConfiguredValueTaskAwaitable<TResult>(new ValueTask<TResult>(_obj, _result, _token, continueOnCapturedContext));
		}

		public override string ToString()
		{
			if (IsCompletedSuccessfully)
			{
				TResult result = Result;
				if (result != null)
				{
					return result.ToString();
				}
			}
			return string.Empty;
		}
	}
}
namespace System.Threading.Tasks.Sources
{
	[Flags]
	public enum ValueTaskSourceOnCompletedFlags
	{
		None = 0,
		UseSchedulingContext = 1,
		FlowExecutionContext = 2
	}
	public enum ValueTaskSourceStatus
	{
		Pending,
		Succeeded,
		Faulted,
		Canceled
	}
	public interface IValueTaskSource
	{
		ValueTaskSourceStatus GetStatus(short token);

		void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags);

		void GetResult(short token);
	}
	public interface IValueTaskSource<out TResult>
	{
		ValueTaskSourceStatus GetStatus(short token);

		void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags);

		TResult GetResult(short token);
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)]
	public sealed class AsyncMethodBuilderAttribute : Attribute
	{
		public Type BuilderType { get; }

		public AsyncMethodBuilderAttribute(Type builderType)
		{
			BuilderType = builderType;
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public struct AsyncValueTaskMethodBuilder
	{
		private AsyncTaskMethodBuilder _methodBuilder;

		private bool _haveResult;

		private bool _useBuilder;

		public ValueTask Task
		{
			get
			{
				if (_haveResult)
				{
					return default(ValueTask);
				}
				_useBuilder = true;
				return new ValueTask(_methodBuilder.Task);
			}
		}

		public static AsyncValueTaskMethodBuilder Create()
		{
			return default(AsyncValueTaskMethodBuilder);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
		{
			_methodBuilder.Start(ref stateMachine);
		}

		public void SetStateMachine(IAsyncStateMachine stateMachine)
		{
			_methodBuilder.SetStateMachine(stateMachine);
		}

		public void SetResult()
		{
			if (_useBuilder)
			{
				_methodBuilder.SetResult();
			}
			else
			{
				_haveResult = true;
			}
		}

		public void SetException(Exception exception)
		{
			_methodBuilder.SetException(exception);
		}

		public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_useBuilder = true;
			_methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine);
		}

		[SecuritySafeCritical]
		public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_useBuilder = true;
			_methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public struct AsyncValueTaskMethodBuilder<TResult>
	{
		private AsyncTaskMethodBuilder<TResult> _methodBuilder;

		private TResult _result;

		private bool _haveResult;

		private bool _useBuilder;

		public ValueTask<TResult> Task
		{
			get
			{
				if (_haveResult)
				{
					return new ValueTask<TResult>(_result);
				}
				_useBuilder = true;
				return new ValueTask<TResult>(_methodBuilder.Task);
			}
		}

		public static AsyncValueTaskMethodBuilder<TResult> Create()
		{
			return default(AsyncValueTaskMethodBuilder<TResult>);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
		{
			_methodBuilder.Start(ref stateMachine);
		}

		public void SetStateMachine(IAsyncStateMachine stateMachine)
		{
			_methodBuilder.SetStateMachine(stateMachine);
		}

		public void SetResult(TResult result)
		{
			if (_useBuilder)
			{
				_methodBuilder.SetResult(result);
				return;
			}
			_result = result;
			_haveResult = true;
		}

		public void SetException(Exception exception)
		{
			_methodBuilder.SetException(exception);
		}

		public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_useBuilder = true;
			_methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine);
		}

		[SecuritySafeCritical]
		public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_useBuilder = true;
			_methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public readonly struct ConfiguredValueTaskAwaitable
	{
		[StructLayout(LayoutKind.Auto)]
		public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion
		{
			private readonly ValueTask _value;

			public bool IsCompleted
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return _value.IsCompleted;
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal ConfiguredValueTaskAwaiter(ValueTask value)
			{
				_value = value;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			[StackTraceHidden]
			public void GetResult()
			{
				_value.ThrowIfCompletedUnsuccessfully();
			}

			public void OnCompleted(Action continuation)
			{
				object obj = _value._obj;
				if (obj is Task task)
				{
					task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
				}
				else if (obj != null)
				{
					Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None));
				}
				else
				{
					ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
				}
			}

			public void UnsafeOnCompleted(Action continuation)
			{
				object obj = _value._obj;
				if (obj is Task task)
				{
					task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
				}
				else if (obj != null)
				{
					Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
				}
				else
				{
					ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
				}
			}
		}

		private readonly ValueTask _value;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ConfiguredValueTaskAwaitable(ValueTask value)
		{
			_value = value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ConfiguredValueTaskAwaiter GetAwaiter()
		{
			return new ConfiguredValueTaskAwaiter(_value);
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public readonly struct ConfiguredValueTaskAwaitable<TResult>
	{
		[StructLayout(LayoutKind.Auto)]
		public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion
		{
			private readonly ValueTask<TResult> _value;

			public bool IsCompleted
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return _value.IsCompleted;
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal ConfiguredValueTaskAwaiter(ValueTask<TResult> value)
			{
				_value = value;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			[StackTraceHidden]
			public TResult GetResult()
			{
				return _value.Result;
			}

			public void OnCompleted(Action continuation)
			{
				object obj = _value._obj;
				if (obj is Task<TResult> task)
				{
					task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
				}
				else if (obj != null)
				{
					Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None));
				}
				else
				{
					ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
				}
			}

			public void UnsafeOnCompleted(Action continuation)
			{
				object obj = _value._obj;
				if (obj is Task<TResult> task)
				{
					task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
				}
				else if (obj != null)
				{
					Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
				}
				else
				{
					ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
				}
			}
		}

		private readonly ValueTask<TResult> _value;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ConfiguredValueTaskAwaitable(ValueTask<TResult> value)
		{
			_value = value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ConfiguredValueTaskAwaiter GetAwaiter()
		{
			return new ConfiguredValueTaskAwaiter(_value);
		}
	}
	public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion
	{
		internal static readonly Action<object> s_invokeActionDelegate = delegate(object state)
		{
			if (!(state is Action action))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state);
			}
			else
			{
				action();
			}
		};

		private readonly ValueTask _value;

		public bool IsCompleted
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return _value.IsCompleted;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ValueTaskAwaiter(ValueTask value)
		{
			_value = value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[StackTraceHidden]
		public void GetResult()
		{
			_value.ThrowIfCompletedUnsuccessfully();
		}

		public void OnCompleted(Action continuation)
		{
			object obj = _value._obj;
			if (obj is Task task)
			{
				task.GetAwaiter().OnCompleted(continuation);
			}
			else if (obj != null)
			{
				Unsafe.As<IValueTaskSource>(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext);
			}
			else
			{
				ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation);
			}
		}

		public void UnsafeOnCompleted(Action continuation)
		{
			object obj = _value._obj;
			if (obj is Task task)
			{
				task.GetAwaiter().UnsafeOnCompleted(continuation);
			}
			else if (obj != null)
			{
				Unsafe.As<IValueTaskSource>(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext);
			}
			else
			{
				ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation);
			}
		}
	}
	public readonly struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion, INotifyCompletion
	{
		private readonly ValueTask<TResult> _value;

		public bool IsCompleted
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return _value.IsCompleted;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ValueTaskAwaiter(ValueTask<TResult> value)
		{
			_value = value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[StackTraceHidden]
		public TResult GetResult()
		{
			return _value.Result;
		}

		public void OnCompleted(Action continuation)
		{
			object obj = _value._obj;
			if (obj is Task<TResult> task)
			{
				task.GetAwaiter().OnCompleted(continuation);
			}
			else if (obj != null)
			{
				Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext);
			}
			else
			{
				ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation);
			}
		}

		public void UnsafeOnCompleted(Action continuation)
		{
			object obj = _value._obj;
			if (obj is Task<TResult> task)
			{
				task.GetAwaiter().UnsafeOnCompleted(continuation);
			}
			else if (obj != null)
			{
				Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext);
			}
			else
			{
				ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation);
			}
		}
	}
	[AttributeUsage(AttributeTargets.All)]
	internal class __BlockReflectionAttribute : Attribute
	{
	}
}
namespace System.Diagnostics
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class StackTraceHiddenAttribute : Attribute
	{
	}
}

Tiltify-Client.dll

Decompiled a month ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.WebSockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Tiltify.Events;
using Tiltify.Exceptions;
using Tiltify.Models;
using Tiltify.RateLimiter;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Tiltify-Client")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Tiltify-Client")]
[assembly: AssemblyTitle("Tiltify-Client")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Tiltify
{
	public class ApiBase
	{
		internal const string BaseTiltifyAPI = "https://tiltify.com/api";

		private readonly ApiSettings settings;

		private readonly IRateLimiter rateLimiter;

		private readonly IHttpCallHandler http;

		private readonly JsonSerializerSettings jsonDeserializer = new JsonSerializerSettings
		{
			NullValueHandling = (NullValueHandling)1,
			MissingMemberHandling = (MissingMemberHandling)0
		};

		public ApiBase(ApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_001b: Expected O, but got Unknown
			this.settings = settings;
			this.rateLimiter = rateLimiter;
			this.http = http;
		}

		protected async Task<string> TiltifyGetAsync(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string customBase = null)
		{
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			string accessToken = settings.OAuthToken;
			return await rateLimiter.Perform(async () => (await http.GeneralRequestAsync(url, "GET", null, api, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<T> TiltifyGetGenericAsync<T>(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string customBase = null)
		{
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			string accessToken = settings.OAuthToken;
			return await rateLimiter.Perform(async () => JsonConvert.DeserializeObject<T>((await http.GeneralRequestAsync(url, "GET", null, api, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value, jsonDeserializer)).ConfigureAwait(continueOnCapturedContext: false);
		}

		private string ConstructResourceUrl(string resource = null, List<KeyValuePair<string, string>> getParams = null, ApiVersion api = ApiVersion.V3, string overrideUrl = null)
		{
			string text = "";
			if (overrideUrl == null)
			{
				if (resource == null)
				{
					throw new Exception("Cannot pass null resource with null override url");
				}
				if (api == ApiVersion.V3)
				{
					text = "https://tiltify.com/api/v3" + resource;
				}
			}
			else
			{
				text = ((resource == null) ? overrideUrl : (overrideUrl + resource));
			}
			if (getParams != null)
			{
				for (int i = 0; i < getParams.Count; i++)
				{
					text = ((i != 0) ? (text + "&" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value)) : (text + "?" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value)));
				}
			}
			return text;
		}
	}
	public class ApiSettings
	{
		public string OAuthToken { get; set; }
	}
	public enum ApiVersion
	{
		V3 = 3
	}
	public class Campaigns : ApiBase
	{
		public Campaigns(ApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetCampaignDonationsResponse> GetCampaignDonations(int campaignId)
		{
			return TiltifyGetGenericAsync<GetCampaignDonationsResponse>($"/campaigns/{campaignId}/donations", ApiVersion.V3);
		}
	}
	public interface IHttpCallHandler
	{
		Task<KeyValuePair<int, string>> GeneralRequestAsync(string url, string method, string payload = null, ApiVersion api = ApiVersion.V3, string accessToken = null);

		Task PutBytesAsync(string url, byte[] payload);

		Task<int> RequestReturnResponseCodeAsync(string url, string method, List<KeyValuePair<string, string>> getParams = null);
	}
	public interface IRateLimiter
	{
		Task Perform(Func<Task> perform, CancellationToken cancellationToken);

		Task Perform(Func<Task> perform);

		Task<T> Perform<T>(Func<Task<T>> perform);

		Task<T> Perform<T>(Func<Task<T>> perform, CancellationToken cancellationToken);

		Task Perform(Action perform, CancellationToken cancellationToken);

		Task Perform(Action perform);

		Task<T> Perform<T>(Func<T> perform);

		Task<T> Perform<T>(Func<T> perform, CancellationToken cancellationToken);
	}
	internal class Throttlers
	{
		public readonly BlockingCollection<Tuple<DateTime, string>> SendQueue = new BlockingCollection<Tuple<DateTime, string>>();

		public bool ResetThrottlerRunning;

		public int SentCount = 0;

		public Task ResetThrottler;

		private readonly TimeSpan _throttlingPeriod;

		private readonly WebSocketClient _client;

		public bool Reconnecting { get; set; } = false;


		public bool ShouldDispose { get; set; } = false;


		public CancellationTokenSource TokenSource { get; set; }

		public Throttlers(WebSocketClient client, TimeSpan throttlingPeriod)
		{
			_throttlingPeriod = throttlingPeriod;
			_client = client;
		}

		public void StartThrottlingWindowReset()
		{
			ResetThrottler = Task.Run(async delegate
			{
				ResetThrottlerRunning = true;
				while (!ShouldDispose && !Reconnecting)
				{
					Interlocked.Exchange(ref SentCount, 0);
					await Task.Delay(_throttlingPeriod, TokenSource.Token);
				}
				ResetThrottlerRunning = false;
				return Task.CompletedTask;
			});
		}

		public void IncrementSentCount()
		{
			Interlocked.Increment(ref SentCount);
		}

		public Task StartSenderTask()
		{
			StartThrottlingWindowReset();
			return Task.Run(async delegate
			{
				try
				{
					while (!ShouldDispose)
					{
						await Task.Delay(_client.Options.SendDelay);
						if (SentCount == _client.Options.MessagesAllowedInPeriod)
						{
							_client.MessageThrottled(new OnMessageThrottledEventArgs
							{
								Message = "Message Throttle Occured. Too Many Messages within the period specified in WebsocketClientOptions.",
								AllowedInPeriod = _client.Options.MessagesAllowedInPeriod,
								Period = _client.Options.ThrottlingPeriod,
								SentMessageCount = Interlocked.CompareExchange(ref SentCount, 0, 0)
							});
						}
						else if (_client.IsConnected && !ShouldDispose)
						{
							Tuple<DateTime, string> msg = SendQueue.Take(TokenSource.Token);
							if (!(msg.Item1.Add(_client.Options.SendCacheItemTimeout) < DateTime.UtcNow))
							{
								try
								{
									await _client.SendAsync(Encoding.UTF8.GetBytes(msg.Item2));
									IncrementSentCount();
								}
								catch (Exception ex3)
								{
									Exception ex2 = ex3;
									_client.SendFailed(new OnSendFailedEventArgs
									{
										Data = msg.Item2,
										Exception = ex2
									});
									break;
								}
							}
						}
					}
				}
				catch (OperationCanceledException)
				{
				}
				catch (Exception ex3)
				{
					Exception ex = ex3;
					_client.SendFailed(new OnSendFailedEventArgs
					{
						Data = "",
						Exception = ex
					});
					_client.Error(new OnErrorEventArgs
					{
						Exception = ex
					});
				}
			});
		}
	}
	public class Tiltify
	{
		private readonly ILogger<Tiltify> logger;

		public ApiSettings Settings { get; }

		public Campaigns Campaigns { get; }

		public Users Users { get; }

		public Tiltify(ILoggerFactory loggerFactory = null, IRateLimiter rateLimiter = null, ApiSettings settings = null, IHttpCallHandler http = null)
		{
			logger = loggerFactory?.CreateLogger<Tiltify>();
			rateLimiter = rateLimiter ?? BypassLimiter.CreateLimiterBypassInstance();
			http = http ?? new TiltifyhHttpClient(loggerFactory?.CreateLogger<TiltifyhHttpClient>());
			Settings = settings ?? new ApiSettings();
			Campaigns = new Campaigns(settings, rateLimiter, http);
			Users = new Users(settings, rateLimiter, http);
		}
	}
	public class TiltifyhHttpClient : IHttpCallHandler
	{
		private readonly ILogger<TiltifyhHttpClient> _logger;

		private readonly HttpClient _http;

		public TiltifyhHttpClient(ILogger<TiltifyhHttpClient> logger = null)
		{
			_logger = logger;
			_http = new HttpClient(new TiltifyHttpClientHandler(_logger));
		}

		public async Task PutBytesAsync(string url, byte[] payload)
		{
			HttpResponseMessage response = await _http.PutAsync(new Uri(url), new ByteArrayContent(payload)).ConfigureAwait(continueOnCapturedContext: false);
			if (!response.IsSuccessStatusCode)
			{
				HandleWebException(response);
			}
		}

		public async Task<KeyValuePair<int, string>> GeneralRequestAsync(string url, string method, string payload = null, ApiVersion api = ApiVersion.V3, string accessToken = null)
		{
			HttpRequestMessage request = new HttpRequestMessage
			{
				RequestUri = new Uri(url),
				Method = new HttpMethod(method)
			};
			if (string.IsNullOrWhiteSpace(accessToken))
			{
				throw new InvalidCredentialException("A Client-Id and OAuth token is required to use the Tiltify API.");
			}
			request.Headers.Add(HttpRequestHeader.Accept.ToString(), "application/json");
			request.Headers.Add(HttpRequestHeader.Authorization.ToString(), "Bearer " + FormatOAuth(accessToken));
			if (payload != null)
			{
				request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
			}
			HttpResponseMessage response = await _http.SendAsync(request).ConfigureAwait(continueOnCapturedContext: false);
			if (response.IsSuccessStatusCode)
			{
				return new KeyValuePair<int, string>(value: await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false), key: (int)response.StatusCode);
			}
			HandleWebException(response);
			return new KeyValuePair<int, string>(0, null);
		}

		public async Task<int> RequestReturnResponseCodeAsync(string url, string method, List<KeyValuePair<string, string>> getParams = null)
		{
			if (getParams != null)
			{
				for (int i = 0; i < getParams.Count; i++)
				{
					url = ((i != 0) ? (url + "&" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value)) : (url + "?" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value)));
				}
			}
			HttpRequestMessage request = new HttpRequestMessage
			{
				RequestUri = new Uri(url),
				Method = new HttpMethod(method)
			};
			return (int)(await _http.SendAsync(request).ConfigureAwait(continueOnCapturedContext: false)).StatusCode;
		}

		private static string FormatOAuth(string token)
		{
			return token.Contains(" ") ? token.Split(new char[1] { ' ' })[1] : token;
		}

		private void HandleWebException(HttpResponseMessage errorResp)
		{
			switch (errorResp.StatusCode)
			{
			case HttpStatusCode.BadRequest:
				throw new BadRequestException("Your request failed because either: \n 1. Your ClientID was invalid/not set. \n 2. Your refresh token was invalid. \n 3. You requested a username when the server was expecting a user ID.");
			case HttpStatusCode.Unauthorized:
			{
				HttpHeaderValueCollection<AuthenticationHeaderValue> wwwAuthenticate = errorResp.Headers.WwwAuthenticate;
				if (wwwAuthenticate == null || wwwAuthenticate.Count <= 0)
				{
					throw new BadScopeException("Your request was blocked due to bad credentials (Do you have the right scope for your access token?).");
				}
				throw new TokenExpiredException("Your request was blocked due to an expired Token. Please refresh your token and update your API instance settings.");
			}
			case HttpStatusCode.Forbidden:
				throw new BadTokenException("The token provided in the request did not match the associated user. Make sure the token you're using is from the resource owner.");
			case HttpStatusCode.NotFound:
				throw new BadResourceException("The resource you tried to access was not valid.");
			case HttpStatusCode.TooManyRequests:
			{
				errorResp.Headers.TryGetValues("Ratelimit-Reset", out IEnumerable<string> values);
				throw new TooManyRequestsException("You have reached your rate limit. Too many requests were made", values.FirstOrDefault());
			}
			case HttpStatusCode.BadGateway:
				throw new BadGatewayException("The API answered with a 502 Bad Gateway. Please retry your request");
			case HttpStatusCode.GatewayTimeout:
				throw new GatewayTimeoutException("The API answered with a 504 Gateway Timeout. Please retry your request");
			case HttpStatusCode.InternalServerError:
				throw new InternalServerErrorException("The API answered with a 500 Internal Server Error. Please retry your request");
			default:
				throw new HttpRequestException($"Something went wrong during the request! Please try again later. Status code: {errorResp.StatusCode}");
			}
		}
	}
	public class TiltifyHttpClientHandler : DelegatingHandler
	{
		private readonly ILogger<IHttpCallHandler> _logger;

		public TiltifyHttpClientHandler(ILogger<IHttpCallHandler> logger)
			: base(new HttpClientHandler())
		{
			_logger = logger;
		}

		protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			if (request.Content != null)
			{
				ILogger<IHttpCallHandler> logger = _logger;
				if (logger != null)
				{
					ILogger logger2 = logger;
					object obj = DateTime.Now;
					object obj2 = "Request";
					object obj3 = request.Method.ToString();
					object obj4 = request.RequestUri.ToString();
					string text = await request.Content.ReadAsStringAsync();
					logger2.LogInformation("Timestamp: {timestamp} Type: {type} Method: {method} Resource: {url} Content: {content}", obj, obj2, obj3, obj4, text);
				}
			}
			else
			{
				_logger?.LogInformation("Timestamp: {timestamp} Type: {type} Method: {method} Resource: {url}", DateTime.Now, "Request", request.Method.ToString(), request.RequestUri.ToString());
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			stopwatch.Stop();
			if (response.IsSuccessStatusCode)
			{
				if (response.Content != null)
				{
					ILogger<IHttpCallHandler> logger3 = _logger;
					if (logger3 != null)
					{
						ILogger logger4 = logger3;
						object obj5 = DateTime.Now;
						object obj6 = "Response";
						object requestUri = response.RequestMessage.RequestUri;
						object obj7 = (int)response.StatusCode;
						object obj8 = stopwatch.ElapsedMilliseconds;
						string text2 = await response.Content.ReadAsStringAsync();
						logger4.LogInformation("Timestamp: {timestamp} Type: {type} Resource: {url} Statuscode: {statuscode} Elapsed: {elapsed} ms Content: {content}", obj5, obj6, requestUri, obj7, obj8, text2);
					}
				}
				else
				{
					_logger?.LogInformation("Timestamp: {timestamp} Type: {type} Resource: {url} Statuscode: {statuscode} Elapsed: {elapsed} ms", DateTime.Now, "Response", response.RequestMessage.RequestUri, (int)response.StatusCode, stopwatch.ElapsedMilliseconds);
				}
			}
			else if (response.Content != null)
			{
				ILogger<IHttpCallHandler> logger5 = _logger;
				if (logger5 != null)
				{
					ILogger logger6 = logger5;
					object obj9 = DateTime.Now;
					object obj10 = "Response";
					object requestUri2 = response.RequestMessage.RequestUri;
					object obj11 = (int)response.StatusCode;
					object obj12 = stopwatch.ElapsedMilliseconds;
					string text3 = await response.Content.ReadAsStringAsync();
					logger6.LogError("Timestamp: {timestamp} Type: {type} Resource: {url} Statuscode: {statuscode} Elapsed: {elapsed} ms Content: {content}", obj9, obj10, requestUri2, obj11, obj12, text3);
				}
			}
			else
			{
				_logger?.LogError("Timestamp: {timestamp} Type: {type} Resource: {url} Statuscode: {statuscode} Elapsed: {elapsed} ms", DateTime.Now, "Response", response.RequestMessage.RequestUri, (int)response.StatusCode, stopwatch.ElapsedMilliseconds);
			}
			return response;
		}
	}
	public class TiltifyWebSocket
	{
		private readonly WebSocketClient _socket;

		private readonly List<PreviousRequest> _previousRequests = new List<PreviousRequest>();

		private readonly Semaphore _previousRequestsSemaphore = new Semaphore(1, 1);

		private readonly ILogger<TiltifyWebSocket> _logger;

		private readonly System.Timers.Timer _pingTimer = new System.Timers.Timer();

		private readonly System.Timers.Timer _pongTimer = new System.Timers.Timer();

		private bool _pongReceived = false;

		private readonly List<string> _topicList = new List<string>();

		private readonly Dictionary<string, string> _topicToChannelId = new Dictionary<string, string>();

		private int websocketMessageId = 16;

		private static readonly Random Random = new Random();

		public bool IsConnected => _socket.IsConnected;

		public event EventHandler<OnLogArgs> OnLog;

		public event EventHandler OnTiltifyServiceConnected;

		public event EventHandler OnTiltifyServiceClosed;

		private event EventHandler<OnTiltifyServiceErrorArgs> OnTiltifyServiceError;

		public event EventHandler<OnListenResponseArgs> OnListenResponse;

		public event EventHandler<OnCampaignDonationArgs> OnCampaignDonation;

		public TiltifyWebSocket(ILogger<TiltifyWebSocket> logger = null, WebSocketClientOptions options = null)
		{
			_logger = logger;
			_socket = new WebSocketClient(options);
			_socket.OnConnected += Socket_OnConnected;
			_socket.OnError += OnError;
			_socket.OnMessage += OnMessage;
			_socket.OnDisconnected += Socket_OnDisconnected;
			_pongTimer.Interval = 10000.0;
			_pongTimer.Elapsed += PongTimerTick;
		}

		private void OnError(object sender, OnErrorEventArgs e)
		{
			_logger?.LogError($"OnError in Tiltify Websocket connection occured! Exception: {e.Exception}");
			this.OnTiltifyServiceError?.Invoke(this, new OnTiltifyServiceErrorArgs
			{
				Exception = e.Exception
			});
		}

		private void OnMessage(object sender, OnMessageEventArgs e)
		{
			_logger?.LogDebug("Received Websocket OnMessage: " + e.Message);
			this.OnLog?.Invoke(this, new OnLogArgs
			{
				Data = e.Message
			});
			ParseMessage(e.Message);
		}

		private void Socket_OnDisconnected(object sender, EventArgs e)
		{
			_logger?.LogWarning("Tiltify Websocket connection closed");
			_pingTimer.Stop();
			_pongTimer.Stop();
			this.OnTiltifyServiceClosed?.Invoke(this, null);
		}

		private void Socket_OnConnected(object sender, EventArgs e)
		{
			_logger?.LogInformation("Tiltify Websocket connection established");
			_pingTimer.Interval = 30000.0;
			_pingTimer.Elapsed += PingTimerTick;
			_pingTimer.Start();
			this.OnTiltifyServiceConnected?.Invoke(this, null);
		}

		private void PingTimerTick(object sender, ElapsedEventArgs e)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			_pongReceived = false;
			string text = GenerateMessageId();
			JArray val = new JArray(new object[5]
			{
				null,
				text,
				"phoenix",
				"heartbeat",
				(object)new JObject()
			});
			_socket.Send(((object)val).ToString());
			_pongTimer.Start();
		}

		private void PongTimerTick(object sender, ElapsedEventArgs e)
		{
			_pongTimer.Stop();
			if (_pongReceived)
			{
				_pongReceived = false;
			}
			else
			{
				_socket.Close();
			}
		}

		private void ParseMessage(string message)
		{
			WebSocketResponse webSocketResponse = new WebSocketResponse(message);
			if (webSocketResponse.Topic == null)
			{
				return;
			}
			if (int.TryParse(webSocketResponse.JoinId, out var result))
			{
				int value = Math.Max(websocketMessageId, result);
				Interlocked.Exchange(ref websocketMessageId, value);
			}
			string[] array = webSocketResponse.Topic.Split(new char[1] { '.' });
			switch (webSocketResponse.Event?.ToLower())
			{
			case "phx_close":
				_socket.Close();
				return;
			case "phx_reply":
			{
				if ("phoenix".Equals(webSocketResponse.Topic))
				{
					_pongReceived = true;
					return;
				}
				if (_previousRequests.Count == 0)
				{
					break;
				}
				bool flag = false;
				_previousRequestsSemaphore.WaitOne();
				try
				{
					int num = 0;
					while (num < _previousRequests.Count)
					{
						PreviousRequest previousRequest = _previousRequests[num];
						if (string.Equals(previousRequest.MessageId, webSocketResponse.MessageId, StringComparison.CurrentCulture))
						{
							_previousRequests.RemoveAt(num);
							_topicToChannelId.TryGetValue(previousRequest.Topic, out var value2);
							this.OnListenResponse?.Invoke(this, new OnListenResponseArgs
							{
								Response = webSocketResponse,
								Topic = previousRequest.Topic,
								Successful = true,
								ChannelId = value2
							});
							flag = true;
						}
						else
						{
							num++;
						}
					}
				}
				finally
				{
					_previousRequestsSemaphore.Release();
				}
				if (flag)
				{
					return;
				}
				break;
			}
			case "donation":
			{
				if (array.Length < 3 || !"campaign".Equals(array[0]) || !"donation".Equals(array[2]))
				{
					break;
				}
				DonationInformation donation = webSocketResponse.Data.ToObject<DonationInformation>();
				this.OnCampaignDonation?.Invoke(this, new OnCampaignDonationArgs
				{
					Donation = donation
				});
				return;
			}
			case "reconnect":
				_socket.Close();
				break;
			}
			UnaccountedFor(message);
		}

		private string GenerateMessageId()
		{
			return Interlocked.Increment(ref websocketMessageId).ToString();
		}

		private void ListenToTopic(string topic)
		{
			_topicList.Add(topic);
		}

		private void ListenToTopics(params string[] topics)
		{
			foreach (string item in topics)
			{
				_topicList.Add(item);
			}
		}

		public void SendTopics(bool unlisten = false)
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			string text = GenerateMessageId();
			List<string> list = new List<string>();
			_previousRequestsSemaphore.WaitOne();
			try
			{
				foreach (string topic in _topicList)
				{
					_previousRequests.Add(new PreviousRequest(text, topic));
					list.Add(topic);
				}
			}
			finally
			{
				_previousRequestsSemaphore.Release();
			}
			foreach (string item in list)
			{
				JArray val = new JArray(new object[5]
				{
					text,
					text,
					item,
					(!unlisten) ? "phx_join" : "phx_leave",
					(object)new JObject()
				});
				_socket.Send(((object)val).ToString());
			}
			_topicList.Clear();
		}

		private void UnaccountedFor(string message)
		{
			_logger?.LogInformation("[Tiltify] [Unaccounted] " + message);
		}

		public void ListenToCampaignDonations(string campaignId)
		{
			string text = "campaign." + campaignId + ".donation";
			_topicToChannelId[text] = campaignId;
			ListenToTopic(text);
		}

		public void Connect()
		{
			_socket.Open();
		}

		public void Disconnect()
		{
			_socket.Close();
		}
	}
	public class Users : ApiBase
	{
		public Users(ApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetUserResponse> GetUser()
		{
			return TiltifyGetGenericAsync<GetUserResponse>("/user", ApiVersion.V3);
		}
	}
	public class WebSocketClient
	{
		private int NotConnectedCounter;

		private readonly Throttlers _throttlers;

		private CancellationTokenSource _tokenSource = new CancellationTokenSource();

		private bool _stopServices;

		private bool _networkServicesRunning;

		private Task[] _networkTasks;

		private Task _monitorTask;

		public TimeSpan DefaultKeepAliveInterval { get; set; }

		public int SendQueueLength => _throttlers.SendQueue.Count;

		public bool IsConnected
		{
			get
			{
				ClientWebSocket client = Client;
				return client != null && client.State == WebSocketState.Open;
			}
		}

		public WebSocketClientOptions Options { get; }

		public ClientWebSocket Client { get; private set; }

		private string Url { get; }

		public event EventHandler<OnConnectedEventArgs> OnConnected;

		public event EventHandler<OnDisconnectedEventArgs> OnDisconnected;

		public event EventHandler<OnErrorEventArgs> OnError;

		public event EventHandler<OnFatalErrorEventArgs> OnFatality;

		public event EventHandler<OnMessageEventArgs> OnMessage;

		public event EventHandler<OnMessageThrottledEventArgs> OnMessageThrottled;

		public event EventHandler<OnSendFailedEventArgs> OnSendFailed;

		public event EventHandler<OnStateChangedEventArgs> OnStateChanged;

		public event EventHandler<OnReconnectedEventArgs> OnReconnected;

		public WebSocketClient(WebSocketClientOptions options = null)
		{
			Options = options ?? new WebSocketClientOptions();
			Url = "wss://websockets.tiltify.com:443/socket/websocket?vsn=2.0.0";
			_throttlers = new Throttlers(this, Options.ThrottlingPeriod)
			{
				TokenSource = _tokenSource
			};
		}

		private void InitializeClient()
		{
			Client?.Abort();
			Client = new ClientWebSocket();
			if (_monitorTask == null)
			{
				_monitorTask = StartMonitorTask();
			}
			else if (_monitorTask.IsCompleted)
			{
				_monitorTask = StartMonitorTask();
			}
		}

		public bool Open()
		{
			try
			{
				if (IsConnected)
				{
					return true;
				}
				InitializeClient();
				Client.ConnectAsync(new Uri(Url), _tokenSource.Token).Wait(10000);
				if (!IsConnected)
				{
					return Open();
				}
				StartNetworkServices();
				return true;
			}
			catch (WebSocketException)
			{
				InitializeClient();
				return false;
			}
		}

		public void Close(bool callDisconnect = true)
		{
			Client?.Abort();
			_stopServices = callDisconnect;
			CleanupServices();
			InitializeClient();
			this.OnDisconnected?.Invoke(this, new OnDisconnectedEventArgs());
		}

		public void Reconnect()
		{
			Task.Run(delegate
			{
				Task.Delay(20).Wait();
				Close();
				if (Open())
				{
					this.OnReconnected?.Invoke(this, new OnReconnectedEventArgs());
				}
			});
		}

		public bool Send(string message)
		{
			try
			{
				if (!IsConnected || SendQueueLength >= Options.SendQueueCapacity)
				{
					return false;
				}
				_throttlers.SendQueue.Add(new Tuple<DateTime, string>(DateTime.UtcNow, message));
				return true;
			}
			catch (Exception exception)
			{
				this.OnError?.Invoke(this, new OnErrorEventArgs
				{
					Exception = exception
				});
				throw;
			}
		}

		private void StartNetworkServices()
		{
			_networkServicesRunning = true;
			_networkTasks = new Task[2]
			{
				StartListenerTask(),
				_throttlers.StartSenderTask()
			}.ToArray();
			if (_networkTasks.Any((Task c) => c.IsFaulted))
			{
				_networkServicesRunning = false;
				CleanupServices();
			}
		}

		public Task SendAsync(byte[] message)
		{
			return Client.SendAsync(new ArraySegment<byte>(message), WebSocketMessageType.Text, endOfMessage: true, _tokenSource.Token);
		}

		private Task StartListenerTask()
		{
			return Task.Run(async delegate
			{
				string message = "";
				while (IsConnected && _networkServicesRunning)
				{
					byte[] buffer = new byte[1024];
					WebSocketReceiveResult result;
					try
					{
						result = await Client.ReceiveAsync(new ArraySegment<byte>(buffer), _tokenSource.Token);
					}
					catch
					{
						InitializeClient();
						break;
					}
					if (result != null)
					{
						switch (result.MessageType)
						{
						case WebSocketMessageType.Close:
							Close();
							break;
						case WebSocketMessageType.Text:
							if (!result.EndOfMessage)
							{
								message += Encoding.UTF8.GetString(buffer).TrimEnd(new char[1]);
								continue;
							}
							message += Encoding.UTF8.GetString(buffer).TrimEnd(new char[1]);
							this.OnMessage?.Invoke(this, new OnMessageEventArgs
							{
								Message = message
							});
							break;
						default:
							throw new ArgumentOutOfRangeException();
						case WebSocketMessageType.Binary:
							break;
						}
						message = "";
					}
				}
			});
		}

		private Task StartMonitorTask()
		{
			return Task.Run(delegate
			{
				bool flag = false;
				int num = 0;
				try
				{
					bool isConnected = IsConnected;
					while (!_tokenSource.IsCancellationRequested)
					{
						if (isConnected == IsConnected)
						{
							Thread.Sleep(200);
							if (!IsConnected)
							{
								NotConnectedCounter++;
							}
							else
							{
								num++;
							}
							if (num >= 300)
							{
								num = 0;
							}
							switch (NotConnectedCounter)
							{
							case 25:
							case 75:
							case 150:
							case 300:
							case 600:
								Reconnect();
								break;
							default:
								if (NotConnectedCounter >= 1200 && NotConnectedCounter % 600 == 0)
								{
									Reconnect();
								}
								break;
							}
							if (NotConnectedCounter != 0 && IsConnected)
							{
								NotConnectedCounter = 0;
							}
						}
						else
						{
							this.OnStateChanged?.Invoke(this, new OnStateChangedEventArgs
							{
								IsConnected = (Client.State == WebSocketState.Open),
								WasConnected = isConnected
							});
							if (IsConnected)
							{
								this.OnConnected?.Invoke(this, new OnConnectedEventArgs());
							}
							if (!IsConnected && !_stopServices)
							{
								if (isConnected && Options.ReconnectionPolicy != null && !Options.ReconnectionPolicy.AreAttemptsComplete())
								{
									flag = true;
									break;
								}
								this.OnDisconnected?.Invoke(this, new OnDisconnectedEventArgs());
								if (Client.CloseStatus.HasValue && Client.CloseStatus != WebSocketCloseStatus.NormalClosure)
								{
									this.OnError?.Invoke(this, new OnErrorEventArgs
									{
										Exception = new Exception(Client.CloseStatus.ToString() + " " + Client.CloseStatusDescription)
									});
								}
							}
							isConnected = IsConnected;
						}
					}
				}
				catch (Exception exception)
				{
					this.OnError?.Invoke(this, new OnErrorEventArgs
					{
						Exception = exception
					});
				}
				if (flag && !_stopServices)
				{
					Reconnect();
				}
			}, _tokenSource.Token);
		}

		private void CleanupServices()
		{
			_tokenSource.Cancel();
			_tokenSource = new CancellationTokenSource();
			_throttlers.TokenSource = _tokenSource;
			if (_stopServices)
			{
				Task[] networkTasks = _networkTasks;
				if (networkTasks != null && networkTasks.Length != 0 && !Task.WaitAll(_networkTasks, 15000))
				{
					this.OnFatality?.Invoke(this, new OnFatalErrorEventArgs
					{
						Reason = "Fatal network error. Network services fail to shut down."
					});
					_stopServices = false;
					_throttlers.Reconnecting = false;
					_networkServicesRunning = false;
				}
			}
		}

		public void MessageThrottled(OnMessageThrottledEventArgs eventArgs)
		{
			this.OnMessageThrottled?.Invoke(this, eventArgs);
		}

		public void SendFailed(OnSendFailedEventArgs eventArgs)
		{
			this.OnSendFailed?.Invoke(this, eventArgs);
		}

		public void Error(OnErrorEventArgs eventArgs)
		{
			this.OnError?.Invoke(this, eventArgs);
		}

		public void Dispose()
		{
			Close();
			_throttlers.ShouldDispose = true;
			_tokenSource.Cancel();
			Thread.Sleep(500);
			_tokenSource.Dispose();
			Client?.Dispose();
			GC.Collect();
		}
	}
	public class WebSocketClientOptions
	{
		public int SendQueueCapacity { get; set; } = 10000;


		public TimeSpan SendCacheItemTimeout { get; set; } = TimeSpan.FromMinutes(30.0);


		public ushort SendDelay { get; set; } = 50;


		public ReconnectionPolicy ReconnectionPolicy { get; set; } = new ReconnectionPolicy(3000, (int?)10);


		public int DisconnectWait { get; set; } = 20000;


		public TimeSpan ThrottlingPeriod { get; set; } = TimeSpan.FromSeconds(30.0);


		public int MessagesAllowedInPeriod { get; set; } = 100;

	}
}
namespace Tiltify.RateLimiter
{
	public class BypassLimiter : IRateLimiter
	{
		public static BypassLimiter CreateLimiterBypassInstance()
		{
			return new BypassLimiter();
		}

		public Task Perform(Func<Task> perform)
		{
			return Perform(perform, CancellationToken.None);
		}

		public Task<T> Perform<T>(Func<Task<T>> perform)
		{
			return Perform(perform, CancellationToken.None);
		}

		public Task Perform(Func<Task> perform, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			return perform();
		}

		public Task<T> Perform<T>(Func<Task<T>> perform, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			return perform();
		}

		private static Func<Task> Transform(Action act)
		{
			return delegate
			{
				act();
				return Task.FromResult(0);
			};
		}

		private static Func<Task<T>> Transform<T>(Func<T> compute)
		{
			return () => Task.FromResult(compute());
		}

		public Task Perform(Action perform, CancellationToken cancellationToken)
		{
			Func<Task> perform2 = Transform(perform);
			return Perform(perform2, cancellationToken);
		}

		public Task Perform(Action perform)
		{
			Func<Task> perform2 = Transform(perform);
			return Perform(perform2);
		}

		public Task<T> Perform<T>(Func<T> perform)
		{
			Func<Task<T>> perform2 = Transform(perform);
			return Perform(perform2);
		}

		public Task<T> Perform<T>(Func<T> perform, CancellationToken cancellationToken)
		{
			Func<Task<T>> perform2 = Transform(perform);
			return Perform(perform2, cancellationToken);
		}
	}
	public class ComposedAwaitableConstraint : IAwaitableConstraint
	{
		private readonly IAwaitableConstraint _ac1;

		private readonly IAwaitableConstraint _ac2;

		private readonly SemaphoreSlim _semafore = new SemaphoreSlim(1, 1);

		internal ComposedAwaitableConstraint(IAwaitableConstraint ac1, IAwaitableConstraint ac2)
		{
			_ac1 = ac1;
			_ac2 = ac2;
		}

		public async Task<IDisposable> WaitForReadiness(CancellationToken cancellationToken)
		{
			await _semafore.WaitAsync(cancellationToken);
			IDisposable[] diposables;
			try
			{
				diposables = await Task.WhenAll<IDisposable>(_ac1.WaitForReadiness(cancellationToken), _ac2.WaitForReadiness(cancellationToken));
			}
			catch (Exception)
			{
				_semafore.Release();
				throw;
			}
			return new DisposeAction(delegate
			{
				IDisposable[] array = diposables;
				foreach (IDisposable disposable in array)
				{
					disposable.Dispose();
				}
				_semafore.Release();
			});
		}
	}
	public class CountByIntervalAwaitableConstraint : IAwaitableConstraint
	{
		public IReadOnlyList<DateTime> TimeStamps => _timeStamps.ToList();

		protected LimitedSizeStack<DateTime> _timeStamps { get; }

		private int _count { get; }

		private TimeSpan _timeSpan { get; }

		private SemaphoreSlim _semafore { get; } = new SemaphoreSlim(1, 1);


		private ITime _time { get; }

		public CountByIntervalAwaitableConstraint(int count, TimeSpan timeSpan, ITime time = null)
		{
			if (count <= 0)
			{
				throw new ArgumentException("count should be strictly positive", "count");
			}
			if (timeSpan.TotalMilliseconds <= 0.0)
			{
				throw new ArgumentException("timeSpan should be strictly positive", "timeSpan");
			}
			_count = count;
			_timeSpan = timeSpan;
			_timeStamps = new LimitedSizeStack<DateTime>(_count);
			_time = time ?? TimeSystem.StandardTime;
		}

		public async Task<IDisposable> WaitForReadiness(CancellationToken cancellationToken)
		{
			await _semafore.WaitAsync(cancellationToken);
			int count = 0;
			DateTime now = _time.GetTimeNow();
			DateTime target = now - _timeSpan;
			LinkedListNode<DateTime> element = _timeStamps.First;
			LinkedListNode<DateTime> last = null;
			while (element != null && element.Value > target)
			{
				last = element;
				element = element.Next;
				count++;
			}
			if (count < _count)
			{
				return new DisposeAction(OnEnded);
			}
			TimeSpan timetoWait = last.Value.Add(_timeSpan) - now;
			try
			{
				await _time.GetDelay(timetoWait, cancellationToken);
			}
			catch (Exception)
			{
				_semafore.Release();
				throw;
			}
			return new DisposeAction(OnEnded);
		}

		private void OnEnded()
		{
			DateTime timeNow = _time.GetTimeNow();
			_timeStamps.Push(timeNow);
			OnEnded(timeNow);
			_semafore.Release();
		}

		protected virtual void OnEnded(DateTime now)
		{
		}
	}
	public class DisposeAction : IDisposable
	{
		private Action _act;

		public DisposeAction(Action act)
		{
			_act = act;
		}

		public void Dispose()
		{
			_act?.Invoke();
			_act = null;
		}
	}
	public interface IAwaitableConstraint
	{
		Task<IDisposable> WaitForReadiness(CancellationToken cancellationToken);
	}
	public static class IAwaitableConstraintExtension
	{
		public static IAwaitableConstraint Compose(this IAwaitableConstraint ac1, IAwaitableConstraint ac2)
		{
			IAwaitableConstraint result;
			if (ac1 != ac2)
			{
				IAwaitableConstraint awaitableConstraint = new ComposedAwaitableConstraint(ac1, ac2);
				result = awaitableConstraint;
			}
			else
			{
				result = ac1;
			}
			return result;
		}
	}
	public interface ITime
	{
		DateTime GetTimeNow();

		Task GetDelay(TimeSpan timespan, CancellationToken cancellationToken);
	}
	public class LimitedSizeStack<T> : LinkedList<T>
	{
		private readonly int _maxSize;

		public LimitedSizeStack(int maxSize)
		{
			_maxSize = maxSize;
		}

		public void Push(T item)
		{
			AddFirst(item);
			if (base.Count > _maxSize)
			{
				RemoveLast();
			}
		}
	}
	public class PersistentCountByIntervalAwaitableConstraint : CountByIntervalAwaitableConstraint
	{
		private readonly Action<DateTime> _saveStateAction;

		public PersistentCountByIntervalAwaitableConstraint(int count, TimeSpan timeSpan, Action<DateTime> saveStateAction, IEnumerable<DateTime> initialTimeStamps, ITime time = null)
			: base(count, timeSpan, time)
		{
			_saveStateAction = saveStateAction;
			if (initialTimeStamps == null)
			{
				return;
			}
			foreach (DateTime initialTimeStamp in initialTimeStamps)
			{
				base._timeStamps.Push(initialTimeStamp);
			}
		}

		protected override void OnEnded(DateTime now)
		{
			_saveStateAction(now);
		}
	}
	public class TimeLimiter : IRateLimiter
	{
		private readonly IAwaitableConstraint _ac;

		public static TimeLimiter GetFromMaxCountByInterval(int maxCount, TimeSpan timeSpan)
		{
			return new TimeLimiter(new CountByIntervalAwaitableConstraint(maxCount, timeSpan));
		}

		public static TimeLimiter GetPersistentTimeLimiter(int maxCount, TimeSpan timeSpan, Action<DateTime> saveStateAction)
		{
			return GetPersistentTimeLimiter(maxCount, timeSpan, saveStateAction, null);
		}

		public static TimeLimiter GetPersistentTimeLimiter(int maxCount, TimeSpan timeSpan, Action<DateTime> saveStateAction, IEnumerable<DateTime> initialTimeStamps)
		{
			return new TimeLimiter(new PersistentCountByIntervalAwaitableConstraint(maxCount, timeSpan, saveStateAction, initialTimeStamps));
		}

		public static TimeLimiter Compose(params IAwaitableConstraint[] constraints)
		{
			IAwaitableConstraint awaitableConstraint = null;
			foreach (IAwaitableConstraint awaitableConstraint2 in constraints)
			{
				awaitableConstraint = ((awaitableConstraint == null) ? awaitableConstraint2 : awaitableConstraint.Compose(awaitableConstraint2));
			}
			return new TimeLimiter(awaitableConstraint);
		}

		internal TimeLimiter(IAwaitableConstraint ac)
		{
			_ac = ac;
		}

		public Task Perform(Func<Task> perform)
		{
			return Perform(perform, CancellationToken.None);
		}

		public Task<T> Perform<T>(Func<Task<T>> perform)
		{
			return Perform(perform, CancellationToken.None);
		}

		public async Task Perform(Func<Task> perform, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			using (await _ac.WaitForReadiness(cancellationToken))
			{
				await perform();
			}
		}

		public async Task<T> Perform<T>(Func<Task<T>> perform, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			using (await _ac.WaitForReadiness(cancellationToken))
			{
				return await perform();
			}
		}

		private static Func<Task> Transform(Action act)
		{
			return delegate
			{
				act();
				return Task.FromResult(0);
			};
		}

		private static Func<Task<T>> Transform<T>(Func<T> compute)
		{
			return () => Task.FromResult(compute());
		}

		public Task Perform(Action perform, CancellationToken cancellationToken)
		{
			Func<Task> perform2 = Transform(perform);
			return Perform(perform2, cancellationToken);
		}

		public Task Perform(Action perform)
		{
			Func<Task> perform2 = Transform(perform);
			return Perform(perform2);
		}

		public Task<T> Perform<T>(Func<T> perform)
		{
			Func<Task<T>> perform2 = Transform(perform);
			return Perform(perform2);
		}

		public Task<T> Perform<T>(Func<T> perform, CancellationToken cancellationToken)
		{
			Func<Task<T>> perform2 = Transform(perform);
			return Perform(perform2, cancellationToken);
		}
	}
	public class TimeSystem : ITime
	{
		public static ITime StandardTime { get; }

		static TimeSystem()
		{
			StandardTime = new TimeSystem();
		}

		private TimeSystem()
		{
		}

		DateTime ITime.GetTimeNow()
		{
			return DateTime.Now;
		}

		Task ITime.GetDelay(TimeSpan timespan, CancellationToken cancellationToken)
		{
			return Task.Delay(timespan, cancellationToken);
		}
	}
}
namespace Tiltify.Models
{
	public class DonationInformation
	{
		[JsonProperty(PropertyName = "id")]
		public int Id { get; protected set; }

		[JsonProperty(PropertyName = "event_id")]
		public int? CampaignId { get; protected set; }

		[JsonProperty(PropertyName = "challenge_id")]
		public int? ChallengeId { get; protected set; }

		[JsonProperty(PropertyName = "poll_option_id")]
		public int? PollOptionId { get; protected set; }

		[JsonProperty(PropertyName = "amount")]
		public double Amount { get; protected set; }

		[JsonProperty(PropertyName = "name")]
		public string Name { get; protected set; }

		[JsonProperty(PropertyName = "comment")]
		public string Comment { get; protected set; }

		[JsonProperty(PropertyName = "completedAt")]
		public long CompletedAt { get; protected set; }

		[JsonProperty(PropertyName = "reward_id")]
		public int? RewardId { get; protected set; }

		[JsonProperty(PropertyName = "rewardId")]
		private int? RewardIdAltKey
		{
			set
			{
				RewardId = value;
			}
		}
	}
	public class GetCampaignDonationsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public DonationInformation[] Data { get; protected set; }
	}
	public class GetUserResponse
	{
		[JsonProperty(PropertyName = "data")]
		public UserInformation Data { get; protected set; }
	}
	internal class PreviousRequest
	{
		public string MessageId { get; }

		public string Topic { get; }

		public PreviousRequest(string messageId, string topic = "none set")
		{
			MessageId = messageId;
			Topic = topic;
		}
	}
	public class ReconnectionPolicy
	{
		private readonly int _reconnectStepInterval;

		private readonly int? _initMaxAttempts;

		private int _minReconnectInterval;

		private readonly int _maxReconnectInterval;

		private int? _maxAttempts;

		private int _attemptsMade;

		public ReconnectionPolicy()
		{
			_reconnectStepInterval = 3000;
			_minReconnectInterval = 3000;
			_maxReconnectInterval = 30000;
			_maxAttempts = null;
			_initMaxAttempts = null;
			_attemptsMade = 0;
		}

		public void SetMaxAttempts(int attempts)
		{
			_maxAttempts = attempts;
		}

		public void Reset()
		{
			_attemptsMade = 0;
			_minReconnectInterval = _reconnectStepInterval;
			_maxAttempts = _initMaxAttempts;
		}

		public void SetAttemptsMade(int count)
		{
			_attemptsMade = count;
		}

		public ReconnectionPolicy(int minReconnectInterval, int maxReconnectInterval, int? maxAttempts)
		{
			_reconnectStepInterval = minReconnectInterval;
			_minReconnectInterval = ((minReconnectInterval > maxReconnectInterval) ? maxReconnectInterval : minReconnectInterval);
			_maxReconnectInterval = maxReconnectInterval;
			_maxAttempts = maxAttempts;
			_initMaxAttempts = maxAttempts;
			_attemptsMade = 0;
		}

		public ReconnectionPolicy(int minReconnectInterval, int maxReconnectInterval)
		{
			_reconnectStepInterval = minReconnectInterval;
			_minReconnectInterval = ((minReconnectInterval > maxReconnectInterval) ? maxReconnectInterval : minReconnectInterval);
			_maxReconnectInterval = maxReconnectInterval;
			_maxAttempts = null;
			_initMaxAttempts = null;
			_attemptsMade = 0;
		}

		public ReconnectionPolicy(int reconnectInterval)
		{
			_reconnectStepInterval = reconnectInterval;
			_minReconnectInterval = reconnectInterval;
			_maxReconnectInterval = reconnectInterval;
			_maxAttempts = null;
			_initMaxAttempts = null;
			_attemptsMade = 0;
		}

		public ReconnectionPolicy(int reconnectInterval, int? maxAttempts)
		{
			_reconnectStepInterval = reconnectInterval;
			_minReconnectInterval = reconnectInterval;
			_maxReconnectInterval = reconnectInterval;
			_maxAttempts = maxAttempts;
			_initMaxAttempts = maxAttempts;
			_attemptsMade = 0;
		}

		internal void ProcessValues()
		{
			_attemptsMade++;
			if (_minReconnectInterval < _maxReconnectInterval)
			{
				_minReconnectInterval += _reconnectStepInterval;
			}
			if (_minReconnectInterval > _maxReconnectInterval)
			{
				_minReconnectInterval = _maxReconnectInterval;
			}
		}

		public int GetReconnectInterval()
		{
			return _minReconnectInterval;
		}

		public bool AreAttemptsComplete()
		{
			return _attemptsMade == _maxAttempts;
		}
	}
	public class UserInformation
	{
		[JsonProperty(PropertyName = "id")]
		public int Id { get; protected set; }

		[JsonProperty(PropertyName = "username")]
		public string Username { get; protected set; }

		[JsonProperty(PropertyName = "slug")]
		public string Slug { get; protected set; }

		[JsonProperty(PropertyName = "thumbnail")]
		public ThumbnailInformation Comment { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public string Status { get; protected set; }
	}
	public class ThumbnailInformation
	{
		[JsonProperty(PropertyName = "src")]
		public string Src { get; protected set; }

		[JsonProperty(PropertyName = "alt")]
		public string Alt { get; protected set; }

		[JsonProperty(PropertyName = "width")]
		public int Width { get; protected set; }

		[JsonProperty(PropertyName = "height")]
		public int Height { get; protected set; }
	}
	public class WebSocketResponse
	{
		public string JoinId { get; }

		public string MessageId { get; }

		public string Topic { get; }

		public string Event { get; }

		public JToken Data { get; }

		public WebSocketResponse(string json)
		{
			JArray val = JArray.Parse(json);
			JoinId = ((object)val[0])?.ToString();
			MessageId = ((object)val[1]).ToString();
			Topic = ((object)val[2]).ToString();
			Event = ((object)val[3]).ToString();
			Data = val[4];
		}
	}
}
namespace Tiltify.Exceptions
{
	public class BadGatewayException : Exception
	{
		public BadGatewayException(string data)
			: base(data)
		{
		}
	}
	public class BadParameterException : Exception
	{
		public BadParameterException(string badParamData)
			: base(badParamData)
		{
		}
	}
	public class BadRequestException : Exception
	{
		public BadRequestException(string apiData)
			: base(apiData)
		{
		}
	}
	public class BadResourceException : Exception
	{
		public BadResourceException(string apiData)
			: base(apiData)
		{
		}
	}
	public class BadScopeException : Exception
	{
		public BadScopeException(string data)
			: base(data)
		{
		}
	}
	public class BadTokenException : Exception
	{
		public BadTokenException(string data)
			: base(data)
		{
		}
	}
	public class ClientIdAndOAuthTokenRequired : Exception
	{
		public ClientIdAndOAuthTokenRequired(string explanation)
			: base(explanation)
		{
		}
	}
	public class GatewayTimeoutException : Exception
	{
		public GatewayTimeoutException(string data)
			: base(data)
		{
		}
	}
	public class InternalServerErrorException : Exception
	{
		public InternalServerErrorException(string data)
			: base(data)
		{
		}
	}
	public class InvalidCredentialException : Exception
	{
		public InvalidCredentialException(string data)
			: base(data)
		{
		}
	}
	public class TokenExpiredException : Exception
	{
		public TokenExpiredException(string data)
			: base(data)
		{
		}
	}
	public sealed class TooManyRequestsException : Exception
	{
		public TooManyRequestsException(string data, string resetTime)
			: base(data)
		{
			if (double.TryParse(resetTime, out var result))
			{
				Data.Add("Ratelimit-Reset", result);
			}
		}
	}
	public class UnexpectedResponseException : Exception
	{
		public UnexpectedResponseException(string data)
			: base(data)
		{
		}
	}
}
namespace Tiltify.Events
{
	public class OnCampaignDonationArgs : EventArgs
	{
		public DonationInformation Donation;
	}
	public class OnConnectedEventArgs : EventArgs
	{
	}
	public class OnDisconnectedEventArgs : EventArgs
	{
	}
	public class OnErrorEventArgs : EventArgs
	{
		public Exception Exception { get; set; }
	}
	public class OnFatalErrorEventArgs : EventArgs
	{
		public string Reason;
	}
	public class OnListenResponseArgs : EventArgs
	{
		public string Topic;

		public WebSocketResponse Response;

		public bool Successful;

		public string ChannelId;
	}
	public class OnLogArgs : EventArgs
	{
		public string Data { get; set; }
	}
	public class OnMessageEventArgs : EventArgs
	{
		public string Message;
	}
	public class OnMessageThrottledEventArgs : EventArgs
	{
		public string Message { get; set; }

		public int SentMessageCount { get; set; }

		public TimeSpan Period { get; set; }

		public int AllowedInPeriod { get; set; }
	}
	public class OnReconnectedEventArgs : EventArgs
	{
	}
	public class OnSendFailedEventArgs : EventArgs
	{
		public string Data;

		public Exception Exception;
	}
	public class OnStateChangedEventArgs : EventArgs
	{
		public bool IsConnected;

		public bool WasConnected;
	}
	public class OnTiltifyServiceErrorArgs : EventArgs
	{
		public Exception Exception { get; set; }
	}
}

TwitchLib.Api.Core.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using TwitchLib.Api.Core.Common;
using TwitchLib.Api.Core.Enums;
using TwitchLib.Api.Core.Exceptions;
using TwitchLib.Api.Core.Extensions.RateLimiter;
using TwitchLib.Api.Core.Interfaces;
using TwitchLib.Api.Core.Internal;
using TwitchLib.Api.Core.Models;
using TwitchLib.Api.Core.Models.Undocumented.Chatters;
using TwitchLib.Api.Core.RateLimiter;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2022")]
[assembly: AssemblyDescription("Project containing the core of TwitchLib.Api")]
[assembly: AssemblyFileVersion("3.10.0")]
[assembly: AssemblyInformationalVersion("3.10.0+92a4359ed145876af4e8e108e267004dcb0babab")]
[assembly: AssemblyProduct("TwitchLib.Api.Core")]
[assembly: AssemblyTitle("TwitchLib.Api.Core")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/swiftyspiffy/TwitchLib")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("3.10.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 TwitchLib.Api.Core
{
	public class ApiBase
	{
		private class TwitchLibJsonSerializer
		{
			private class LowercaseContractResolver : DefaultContractResolver
			{
				protected override string ResolvePropertyName(string propertyName)
				{
					return propertyName.ToLower();
				}
			}

			private readonly JsonSerializerSettings _settings = new JsonSerializerSettings
			{
				ContractResolver = (IContractResolver)(object)new LowercaseContractResolver(),
				NullValueHandling = (NullValueHandling)1
			};

			public string SerializeObject(object o)
			{
				return JsonConvert.SerializeObject(o, (Formatting)1, _settings);
			}
		}

		private readonly TwitchLibJsonSerializer _jsonSerializer;

		protected readonly IApiSettings Settings;

		private readonly IRateLimiter _rateLimiter;

		private readonly IHttpCallHandler _http;

		internal const string BaseHelix = "https://api.twitch.tv/helix";

		internal const string BaseAuth = "https://id.twitch.tv/oauth2";

		private DateTime? _serverBasedAccessTokenExpiry;

		private string _serverBasedAccessToken;

		private readonly JsonSerializerSettings _twitchLibJsonDeserializer = new JsonSerializerSettings
		{
			NullValueHandling = (NullValueHandling)1,
			MissingMemberHandling = (MissingMemberHandling)0
		};

		public ApiBase(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_001b: Expected O, but got Unknown
			Settings = settings;
			_rateLimiter = rateLimiter;
			_http = http;
			_jsonSerializer = new TwitchLibJsonSerializer();
		}

		public async ValueTask<string> GetAccessTokenAsync(string accessToken = null)
		{
			if (!string.IsNullOrWhiteSpace(accessToken))
			{
				return accessToken;
			}
			if (!string.IsNullOrWhiteSpace(Settings.AccessToken))
			{
				return Settings.AccessToken;
			}
			if (!string.IsNullOrWhiteSpace(Settings.Secret) && !string.IsNullOrWhiteSpace(Settings.ClientId) && !Settings.SkipAutoServerTokenGeneration)
			{
				if (!_serverBasedAccessTokenExpiry.HasValue || _serverBasedAccessTokenExpiry - TimeSpan.FromMinutes(1.0) < DateTime.Now)
				{
					return await GenerateServerBasedAccessToken().ConfigureAwait(continueOnCapturedContext: false);
				}
				return _serverBasedAccessToken;
			}
			return null;
		}

		internal async Task<string> GenerateServerBasedAccessToken()
		{
			KeyValuePair<int, string> result = await _http.GeneralRequestAsync("https://id.twitch.tv/oauth2/token?client_id=" + Settings.ClientId + "&client_secret=" + Settings.Secret + "&grant_type=client_credentials", "POST", (string)null, (ApiVersion)1, Settings.ClientId, (string)null).ConfigureAwait(continueOnCapturedContext: false);
			if (result.Key == 200)
			{
				JObject data = JObject.Parse(result.Value);
				int offset = int.Parse(((object)((JToken)data).SelectToken("expires_in"))?.ToString() ?? string.Empty);
				_serverBasedAccessTokenExpiry = DateTime.Now + TimeSpan.FromSeconds(offset);
				_serverBasedAccessToken = ((object)((JToken)data).SelectToken("access_token"))?.ToString();
				return _serverBasedAccessToken;
			}
			return null;
		}

		internal void ForceAccessTokenAndClientIdForHelix(string clientId, string accessToken, ApiVersion api)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			if ((int)api != 6 || (!string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(accessToken)))
			{
				return;
			}
			throw new ClientIdAndOAuthTokenRequired("As of May 1, all calls to Twitch's Helix API require Client-ID and OAuth access token be set. Example: api.Settings.AccessToken = \"twitch-oauth-access-token-here\"; api.Settings.ClientId = \"twitch-client-id-here\";");
		}

		protected async Task<string> TwitchGetAsync(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<string>((Func<Task<string>>)(async () => (await _http.GeneralRequestAsync(url, "GET", (string)null, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value)).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<T> TwitchGetGenericAsync<T>(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<T>((Func<Task<T>>)(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "GET", (string)null, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value, _twitchLibJsonDeserializer))).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<T> TwitchPatchGenericAsync<T>(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<T>((Func<Task<T>>)(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "PATCH", payload, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value, _twitchLibJsonDeserializer))).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<KeyValuePair<int, string>> TwitchPatchAsync(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<KeyValuePair<int, string>>((Func<Task<KeyValuePair<int, string>>>)(async () => await _http.GeneralRequestAsync(url, "PATCH", payload, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false))).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<KeyValuePair<int, string>> TwitchDeleteAsync(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<KeyValuePair<int, string>>((Func<Task<KeyValuePair<int, string>>>)(async () => await _http.GeneralRequestAsync(url, "DELETE", (string)null, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false))).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<T> TwitchPostGenericAsync<T>(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<T>((Func<Task<T>>)(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "POST", payload, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value, _twitchLibJsonDeserializer))).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<T> TwitchPostGenericModelAsync<T>(string resource, ApiVersion api, RequestModel model, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, null, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<T>((Func<Task<T>>)(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "POST", (model != null) ? _jsonSerializer.SerializeObject(model) : "", api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value, _twitchLibJsonDeserializer))).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<T> TwitchDeleteGenericAsync<T>(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<T>((Func<Task<T>>)(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "DELETE", (string)null, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value, _twitchLibJsonDeserializer))).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<T> TwitchPutGenericAsync<T>(string resource, ApiVersion api, string payload = null, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<T>((Func<Task<T>>)(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "PUT", payload, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value, _twitchLibJsonDeserializer))).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<string> TwitchPutAsync(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<string>((Func<Task<string>>)(async () => (await _http.GeneralRequestAsync(url, "PUT", payload, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value)).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected async Task<KeyValuePair<int, string>> TwitchPostAsync(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			string url = ConstructResourceUrl(resource, getParams, api, customBase);
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<KeyValuePair<int, string>>((Func<Task<KeyValuePair<int, string>>>)(async () => await _http.GeneralRequestAsync(url, "POST", payload, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false))).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected Task PutBytesAsync(string url, byte[] payload)
		{
			return _http.PutBytesAsync(url, payload);
		}

		internal Task<int> RequestReturnResponseCode(string url, string method, List<KeyValuePair<string, string>> getParams = null)
		{
			return _http.RequestReturnResponseCodeAsync(url, method, getParams);
		}

		protected async Task<T> GetGenericAsync<T>(string url, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, ApiVersion api = 6, string clientId = null)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (getParams != null)
			{
				for (int i = 0; i < getParams.Count; i++)
				{
					if (i == 0)
					{
						url = url + "?" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value);
					}
					else
					{
						url = url + "&" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value);
					}
				}
			}
			if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
			{
				clientId = Settings.ClientId;
			}
			accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(continueOnCapturedContext: false);
			ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
			return await _rateLimiter.Perform<T>((Func<Task<T>>)(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "GET", (string)null, api, clientId, accessToken).ConfigureAwait(continueOnCapturedContext: false)).Value, _twitchLibJsonDeserializer))).ConfigureAwait(continueOnCapturedContext: false);
		}

		internal Task<T> GetSimpleGenericAsync<T>(string url, List<KeyValuePair<string, string>> getParams = null)
		{
			if (getParams != null)
			{
				for (int i = 0; i < getParams.Count; i++)
				{
					if (i == 0)
					{
						url = url + "?" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value);
					}
					else
					{
						url = url + "&" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value);
					}
				}
			}
			return _rateLimiter.Perform<T>((Func<Task<T>>)(async () => JsonConvert.DeserializeObject<T>(await SimpleRequestAsync(url).ConfigureAwait(continueOnCapturedContext: false), _twitchLibJsonDeserializer)));
		}

		private Task<string> SimpleRequestAsync(string url)
		{
			TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
			WebClient client = new WebClient();
			client.DownloadStringCompleted += DownloadStringCompletedEventHandler;
			client.DownloadString(new Uri(url));
			return tcs.Task;
			void DownloadStringCompletedEventHandler(object sender, DownloadStringCompletedEventArgs args)
			{
				if (args.Cancelled)
				{
					tcs.SetCanceled();
				}
				else if (args.Error != null)
				{
					tcs.SetException(args.Error);
				}
				else
				{
					tcs.SetResult(args.Result);
				}
				client.DownloadStringCompleted -= DownloadStringCompletedEventHandler;
			}
		}

		private string ConstructResourceUrl(string resource = null, List<KeyValuePair<string, string>> getParams = null, ApiVersion api = 6, string overrideUrl = null)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			string text = "";
			if (overrideUrl == null)
			{
				if (resource == null)
				{
					throw new Exception("Cannot pass null resource with null override url");
				}
				if ((int)api != 1)
				{
					if ((int)api == 6)
					{
						text = "https://api.twitch.tv/helix" + resource;
					}
				}
				else
				{
					text = "https://id.twitch.tv/oauth2" + resource;
				}
			}
			else
			{
				text = ((resource == null) ? overrideUrl : (overrideUrl + resource));
			}
			if (getParams != null)
			{
				for (int i = 0; i < getParams.Count; i++)
				{
					text = ((i != 0) ? (text + "&" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value)) : (text + "?" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value)));
				}
			}
			return text;
		}
	}
	public class ApiSettings : IApiSettings, INotifyPropertyChanged
	{
		private string _clientId;

		private string _secret;

		private string _accessToken;

		private bool _skipDynamicScopeValidation;

		private bool _skipAutoServerTokenGeneration;

		private List<AuthScopes> _scopes;

		public string ClientId
		{
			get
			{
				return _clientId;
			}
			set
			{
				if (value != _clientId)
				{
					_clientId = value;
					NotifyPropertyChanged("ClientId");
				}
			}
		}

		public string Secret
		{
			get
			{
				return _secret;
			}
			set
			{
				if (value != _secret)
				{
					_secret = value;
					NotifyPropertyChanged("Secret");
				}
			}
		}

		public string AccessToken
		{
			get
			{
				return _accessToken;
			}
			set
			{
				if (value != _accessToken)
				{
					_accessToken = value;
					NotifyPropertyChanged("AccessToken");
				}
			}
		}

		public bool SkipDynamicScopeValidation
		{
			get
			{
				return _skipDynamicScopeValidation;
			}
			set
			{
				if (value != _skipDynamicScopeValidation)
				{
					_skipDynamicScopeValidation = value;
					NotifyPropertyChanged("SkipDynamicScopeValidation");
				}
			}
		}

		public bool SkipAutoServerTokenGeneration
		{
			get
			{
				return _skipAutoServerTokenGeneration;
			}
			set
			{
				if (value != _skipAutoServerTokenGeneration)
				{
					_skipAutoServerTokenGeneration = value;
					NotifyPropertyChanged("SkipAutoServerTokenGeneration");
				}
			}
		}

		public List<AuthScopes> Scopes
		{
			get
			{
				return _scopes;
			}
			set
			{
				if (value != _scopes)
				{
					_scopes = value;
					NotifyPropertyChanged("Scopes");
				}
			}
		}

		public event PropertyChangedEventHandler PropertyChanged;

		private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
		{
			this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
		}
	}
}
namespace TwitchLib.Api.Core.Undocumented
{
	public class Undocumented : ApiBase
	{
		public Undocumented(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		[Obsolete("Please use the new official Helix GetChatters Endpoint (api.Helix.Chat.GetChattersAsync) instead of this undocumented and unsupported endpoint.")]
		public async Task<List<ChatterFormatted>> GetChattersAsync(string channelName)
		{
			ChattersResponse resp = await GetGenericAsync<ChattersResponse>("https://tmi.twitch.tv/group/user/" + channelName.ToLower() + "/chatters", null, null, (ApiVersion)6);
			List<ChatterFormatted> chatters = ((IEnumerable<string>)resp.Chatters.Staff).Select((Func<string, ChatterFormatted>)((string chatter) => new ChatterFormatted(chatter, (UserType)6))).ToList();
			chatters.AddRange(((IEnumerable<string>)resp.Chatters.Admins).Select((Func<string, ChatterFormatted>)((string chatter) => new ChatterFormatted(chatter, (UserType)5))));
			chatters.AddRange(((IEnumerable<string>)resp.Chatters.GlobalMods).Select((Func<string, ChatterFormatted>)((string chatter) => new ChatterFormatted(chatter, (UserType)3))));
			chatters.AddRange(((IEnumerable<string>)resp.Chatters.Moderators).Select((Func<string, ChatterFormatted>)((string chatter) => new ChatterFormatted(chatter, (UserType)2))));
			chatters.AddRange(((IEnumerable<string>)resp.Chatters.Viewers).Select((Func<string, ChatterFormatted>)((string chatter) => new ChatterFormatted(chatter, (UserType)0))));
			chatters.AddRange(((IEnumerable<string>)resp.Chatters.VIP).Select((Func<string, ChatterFormatted>)((string chatter) => new ChatterFormatted(chatter, (UserType)1))));
			foreach (ChatterFormatted chatter2 in chatters.Where((ChatterFormatted chatter) => string.Equals(chatter.Username, channelName, StringComparison.InvariantCultureIgnoreCase)))
			{
				chatter2.UserType = (UserType)4;
			}
			return chatters;
		}

		public async Task<bool> IsUsernameAvailableAsync(string username)
		{
			int resp = await RequestReturnResponseCode(getParams: new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("users_service", "true")
			}, url: "https://passport.twitch.tv/usernames/" + username, method: "HEAD").ConfigureAwait(continueOnCapturedContext: false);
			return resp switch
			{
				200 => false, 
				204 => true, 
				_ => throw new BadResourceException("Unexpected response from resource. Expecting response code 200 or 204, received: " + resp, null), 
			};
		}
	}
}
namespace TwitchLib.Api.Core.RateLimiter
{
	public class BypassLimiter : IRateLimiter
	{
		public Task Perform(Func<Task> perform)
		{
			return Perform(perform, CancellationToken.None);
		}

		public Task<T> Perform<T>(Func<Task<T>> perform)
		{
			return Perform(perform, CancellationToken.None);
		}

		public Task Perform(Func<Task> perform, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			return perform();
		}

		public Task<T> Perform<T>(Func<Task<T>> perform, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			return perform();
		}

		private static Func<Task> Transform(Action act)
		{
			return delegate
			{
				act();
				return Task.FromResult(0);
			};
		}

		private static Func<Task<T>> Transform<T>(Func<T> compute)
		{
			return () => Task.FromResult(compute());
		}

		public Task Perform(Action perform, CancellationToken cancellationToken)
		{
			Func<Task> perform2 = Transform(perform);
			return Perform(perform2, cancellationToken);
		}

		public Task Perform(Action perform)
		{
			Func<Task> perform2 = Transform(perform);
			return Perform(perform2);
		}

		public Task<T> Perform<T>(Func<T> perform)
		{
			Func<Task<T>> perform2 = Transform(perform);
			return Perform(perform2);
		}

		public Task<T> Perform<T>(Func<T> perform, CancellationToken cancellationToken)
		{
			Func<Task<T>> perform2 = Transform(perform);
			return Perform(perform2, cancellationToken);
		}

		public static BypassLimiter CreateLimiterBypassInstance()
		{
			return new BypassLimiter();
		}
	}
	public class ComposedAwaitableConstraint : IAwaitableConstraint
	{
		private IAwaitableConstraint _ac1;

		private IAwaitableConstraint _ac2;

		private readonly SemaphoreSlim _semafore = new SemaphoreSlim(1, 1);

		internal ComposedAwaitableConstraint(IAwaitableConstraint ac1, IAwaitableConstraint ac2)
		{
			_ac1 = ac1;
			_ac2 = ac2;
		}

		public async Task<IDisposable> WaitForReadiness(CancellationToken cancellationToken)
		{
			await _semafore.WaitAsync(cancellationToken);
			IDisposable[] diposables;
			try
			{
				diposables = await Task.WhenAll<IDisposable>(_ac1.WaitForReadiness(cancellationToken), _ac2.WaitForReadiness(cancellationToken));
			}
			catch (Exception)
			{
				_semafore.Release();
				throw;
			}
			return new DisposeAction(delegate
			{
				IDisposable[] array = diposables;
				foreach (IDisposable disposable in array)
				{
					disposable.Dispose();
				}
				_semafore.Release();
			});
		}
	}
	public class CountByIntervalAwaitableConstraint : IAwaitableConstraint
	{
		public IReadOnlyList<DateTime> TimeStamps => _timeStamps.ToList();

		protected LimitedSizeStack<DateTime> _timeStamps { get; }

		private int _count { get; }

		private TimeSpan _timeSpan { get; }

		private SemaphoreSlim _semafore { get; } = new SemaphoreSlim(1, 1);


		private ITime _time { get; }

		public CountByIntervalAwaitableConstraint(int count, TimeSpan timeSpan, ITime time = null)
		{
			if (count <= 0)
			{
				throw new ArgumentException("count should be strictly positive", "count");
			}
			if (timeSpan.TotalMilliseconds <= 0.0)
			{
				throw new ArgumentException("timeSpan should be strictly positive", "timeSpan");
			}
			_count = count;
			_timeSpan = timeSpan;
			_timeStamps = new LimitedSizeStack<DateTime>(_count);
			_time = time ?? TimeSystem.StandardTime;
		}

		public async Task<IDisposable> WaitForReadiness(CancellationToken cancellationToken)
		{
			await _semafore.WaitAsync(cancellationToken);
			int count = 0;
			DateTime now = _time.GetTimeNow();
			DateTime target = now - _timeSpan;
			LinkedListNode<DateTime> element = _timeStamps.First;
			LinkedListNode<DateTime> last = null;
			while (element != null && element.Value > target)
			{
				last = element;
				element = element.Next;
				count++;
			}
			if (count < _count)
			{
				return new DisposeAction(OnEnded);
			}
			TimeSpan timetoWait = last.Value.Add(_timeSpan) - now;
			try
			{
				await _time.GetDelay(timetoWait, cancellationToken);
			}
			catch (Exception)
			{
				_semafore.Release();
				throw;
			}
			return new DisposeAction(OnEnded);
		}

		private void OnEnded()
		{
			DateTime timeNow = _time.GetTimeNow();
			_timeStamps.Push(timeNow);
			OnEnded(timeNow);
			_semafore.Release();
		}

		protected virtual void OnEnded(DateTime now)
		{
		}
	}
	public class DisposeAction : IDisposable
	{
		private Action _act;

		public DisposeAction(Action act)
		{
			_act = act;
		}

		public void Dispose()
		{
			_act?.Invoke();
			_act = null;
		}
	}
	public class LimitedSizeStack<T> : LinkedList<T>
	{
		private readonly int _maxSize;

		public LimitedSizeStack(int maxSize)
		{
			_maxSize = maxSize;
		}

		public void Push(T item)
		{
			AddFirst(item);
			if (base.Count > _maxSize)
			{
				RemoveLast();
			}
		}
	}
	public class PersistentCountByIntervalAwaitableConstraint : CountByIntervalAwaitableConstraint
	{
		private readonly Action<DateTime> _saveStateAction;

		public PersistentCountByIntervalAwaitableConstraint(int count, TimeSpan timeSpan, Action<DateTime> saveStateAction, IEnumerable<DateTime> initialTimeStamps, ITime time = null)
			: base(count, timeSpan, time)
		{
			_saveStateAction = saveStateAction;
			if (initialTimeStamps == null)
			{
				return;
			}
			foreach (DateTime initialTimeStamp in initialTimeStamps)
			{
				base._timeStamps.Push(initialTimeStamp);
			}
		}

		protected override void OnEnded(DateTime now)
		{
			_saveStateAction(now);
		}
	}
	public class TimeLimiter : IRateLimiter
	{
		private readonly IAwaitableConstraint _ac;

		internal TimeLimiter(IAwaitableConstraint ac)
		{
			_ac = ac;
		}

		public Task Perform(Func<Task> perform)
		{
			return Perform(perform, CancellationToken.None);
		}

		public Task<T> Perform<T>(Func<Task<T>> perform)
		{
			return Perform(perform, CancellationToken.None);
		}

		public async Task Perform(Func<Task> perform, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			using (await _ac.WaitForReadiness(cancellationToken))
			{
				await perform();
			}
		}

		public async Task<T> Perform<T>(Func<Task<T>> perform, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			using (await _ac.WaitForReadiness(cancellationToken))
			{
				return await perform();
			}
		}

		private static Func<Task> Transform(Action act)
		{
			return delegate
			{
				act();
				return Task.FromResult(0);
			};
		}

		private static Func<Task<T>> Transform<T>(Func<T> compute)
		{
			return () => Task.FromResult(compute());
		}

		public Task Perform(Action perform, CancellationToken cancellationToken)
		{
			Func<Task> perform2 = Transform(perform);
			return Perform(perform2, cancellationToken);
		}

		public Task Perform(Action perform)
		{
			Func<Task> perform2 = Transform(perform);
			return Perform(perform2);
		}

		public Task<T> Perform<T>(Func<T> perform)
		{
			Func<Task<T>> perform2 = Transform(perform);
			return Perform(perform2);
		}

		public Task<T> Perform<T>(Func<T> perform, CancellationToken cancellationToken)
		{
			Func<Task<T>> perform2 = Transform(perform);
			return Perform(perform2, cancellationToken);
		}

		public static TimeLimiter GetFromMaxCountByInterval(int maxCount, TimeSpan timeSpan)
		{
			return new TimeLimiter((IAwaitableConstraint)(object)new CountByIntervalAwaitableConstraint(maxCount, timeSpan));
		}

		public static TimeLimiter GetPersistentTimeLimiter(int maxCount, TimeSpan timeSpan, Action<DateTime> saveStateAction)
		{
			return GetPersistentTimeLimiter(maxCount, timeSpan, saveStateAction, null);
		}

		public static TimeLimiter GetPersistentTimeLimiter(int maxCount, TimeSpan timeSpan, Action<DateTime> saveStateAction, IEnumerable<DateTime> initialTimeStamps)
		{
			return new TimeLimiter((IAwaitableConstraint)(object)new PersistentCountByIntervalAwaitableConstraint(maxCount, timeSpan, saveStateAction, initialTimeStamps));
		}

		public static TimeLimiter Compose(params IAwaitableConstraint[] constraints)
		{
			IAwaitableConstraint val = null;
			foreach (IAwaitableConstraint val2 in constraints)
			{
				val = ((val == null) ? val2 : val.Compose(val2));
			}
			return new TimeLimiter(val);
		}
	}
	public class TimeSystem : ITime
	{
		public static ITime StandardTime { get; }

		static TimeSystem()
		{
			StandardTime = (ITime)(object)new TimeSystem();
		}

		private TimeSystem()
		{
		}

		DateTime ITime.GetTimeNow()
		{
			return DateTime.Now;
		}

		Task ITime.GetDelay(TimeSpan timespan, CancellationToken cancellationToken)
		{
			return Task.Delay(timespan, cancellationToken);
		}
	}
}
namespace TwitchLib.Api.Core.Internal
{
	public class TwitchHttpClientHandler : DelegatingHandler
	{
		private readonly ILogger<IHttpCallHandler> _logger;

		public TwitchHttpClientHandler(ILogger<IHttpCallHandler> logger)
			: base(new HttpClientHandler
			{
				AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate)
			})
		{
			_logger = logger;
		}

		protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			if (request.Content != null)
			{
				ILogger<IHttpCallHandler> logger = _logger;
				if (logger != null)
				{
					ILogger logger2 = logger;
					object obj = DateTime.Now;
					object obj2 = "Request";
					object obj3 = request.Method.ToString();
					object obj4 = request.RequestUri.ToString();
					string text = await request.Content.ReadAsStringAsync();
					logger2.LogInformation("Timestamp: {timestamp} Type: {type} Method: {method} Resource: {url} Content: {content}", obj, obj2, obj3, obj4, text);
				}
			}
			else
			{
				_logger?.LogInformation("Timestamp: {timestamp} Type: {type} Method: {method} Resource: {url}", DateTime.Now, "Request", request.Method.ToString(), request.RequestUri.ToString());
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			stopwatch.Stop();
			if (response.IsSuccessStatusCode)
			{
				if (response.Content != null)
				{
					ILogger<IHttpCallHandler> logger3 = _logger;
					if (logger3 != null)
					{
						ILogger logger4 = logger3;
						object obj5 = DateTime.Now;
						object obj6 = "Response";
						object requestUri = response.RequestMessage.RequestUri;
						object obj7 = (int)response.StatusCode;
						object obj8 = stopwatch.ElapsedMilliseconds;
						string text2 = await response.Content.ReadAsStringAsync();
						logger4.LogInformation("Timestamp: {timestamp} Type: {type} Resource: {url} Statuscode: {statuscode} Elapsed: {elapsed} ms Content: {content}", obj5, obj6, requestUri, obj7, obj8, text2);
					}
				}
				else
				{
					_logger?.LogInformation("Timestamp: {timestamp} Type: {type} Resource: {url} Statuscode: {statuscode} Elapsed: {elapsed} ms", DateTime.Now, "Response", response.RequestMessage.RequestUri, (int)response.StatusCode, stopwatch.ElapsedMilliseconds);
				}
			}
			else if (response.Content != null)
			{
				ILogger<IHttpCallHandler> logger5 = _logger;
				if (logger5 != null)
				{
					ILogger logger6 = logger5;
					object obj9 = DateTime.Now;
					object obj10 = "Response";
					object requestUri2 = response.RequestMessage.RequestUri;
					object obj11 = (int)response.StatusCode;
					object obj12 = stopwatch.ElapsedMilliseconds;
					string text3 = await response.Content.ReadAsStringAsync();
					logger6.LogError("Timestamp: {timestamp} Type: {type} Resource: {url} Statuscode: {statuscode} Elapsed: {elapsed} ms Content: {content}", obj9, obj10, requestUri2, obj11, obj12, text3);
				}
			}
			else
			{
				_logger?.LogError("Timestamp: {timestamp} Type: {type} Resource: {url} Statuscode: {statuscode} Elapsed: {elapsed} ms", DateTime.Now, "Response", response.RequestMessage.RequestUri, (int)response.StatusCode, stopwatch.ElapsedMilliseconds);
			}
			return response;
		}
	}
}
namespace TwitchLib.Api.Core.HttpCallHandlers
{
	public class TwitchHttpClient : IHttpCallHandler
	{
		private readonly ILogger<TwitchHttpClient> _logger;

		private readonly HttpClient _http;

		public TwitchHttpClient(ILogger<TwitchHttpClient> logger = null)
		{
			_logger = logger;
			_http = new HttpClient(new TwitchHttpClientHandler((ILogger<IHttpCallHandler>)_logger));
		}

		public async Task PutBytesAsync(string url, byte[] payload)
		{
			HttpResponseMessage response = await _http.PutAsync(new Uri(url), new ByteArrayContent(payload)).ConfigureAwait(continueOnCapturedContext: false);
			if (!response.IsSuccessStatusCode)
			{
				HandleWebException(response);
			}
		}

		public async Task<KeyValuePair<int, string>> GeneralRequestAsync(string url, string method, string payload = null, ApiVersion api = 6, string clientId = null, string accessToken = null)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			HttpRequestMessage request = new HttpRequestMessage
			{
				RequestUri = new Uri(url),
				Method = new HttpMethod(method)
			};
			if ((int)api == 6)
			{
				if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(accessToken))
				{
					throw new InvalidCredentialException("A Client-Id and OAuth token is required to use the Twitch API.");
				}
				request.Headers.Add("Client-ID", clientId);
			}
			string authPrefix = "OAuth";
			if ((int)api == 6 || (int)api == 1)
			{
				request.Headers.Add(HttpRequestHeader.Accept.ToString(), "application/json");
				authPrefix = "Bearer";
			}
			if (!string.IsNullOrWhiteSpace(accessToken))
			{
				request.Headers.Add(HttpRequestHeader.Authorization.ToString(), authPrefix + " " + Helpers.FormatOAuth(accessToken));
			}
			if (payload != null)
			{
				request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
			}
			HttpResponseMessage response = await _http.SendAsync(request).ConfigureAwait(continueOnCapturedContext: false);
			if (response.IsSuccessStatusCode)
			{
				return new KeyValuePair<int, string>(value: await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false), key: (int)response.StatusCode);
			}
			HandleWebException(response);
			return new KeyValuePair<int, string>(0, null);
		}

		public async Task<int> RequestReturnResponseCodeAsync(string url, string method, List<KeyValuePair<string, string>> getParams = null)
		{
			if (getParams != null)
			{
				for (int i = 0; i < getParams.Count; i++)
				{
					url = ((i != 0) ? (url + "&" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value)) : (url + "?" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value)));
				}
			}
			HttpRequestMessage request = new HttpRequestMessage
			{
				RequestUri = new Uri(url),
				Method = new HttpMethod(method)
			};
			return (int)(await _http.SendAsync(request).ConfigureAwait(continueOnCapturedContext: false)).StatusCode;
		}

		private void HandleWebException(HttpResponseMessage errorResp)
		{
			switch (errorResp.StatusCode)
			{
			case HttpStatusCode.BadRequest:
				throw new BadRequestException("Your request failed because either: \n 1. Your ClientID was invalid/not set. \n 2. Your refresh token was invalid. \n 3. You requested a username when the server was expecting a user ID.", errorResp);
			case HttpStatusCode.Unauthorized:
			{
				HttpHeaderValueCollection<AuthenticationHeaderValue> wwwAuthenticate = errorResp.Headers.WwwAuthenticate;
				if (wwwAuthenticate == null || wwwAuthenticate.Count <= 0)
				{
					throw new BadScopeException("Your request was blocked due to bad credentials (Do you have the right scope for your access token?).", errorResp);
				}
				throw new TokenExpiredException("Your request was blocked due to an expired Token. Please refresh your token and update your API instance settings.", errorResp);
			}
			case HttpStatusCode.NotFound:
				throw new BadResourceException("The resource you tried to access was not valid.", errorResp);
			case HttpStatusCode.TooManyRequests:
			{
				errorResp.Headers.TryGetValues("Ratelimit-Reset", out IEnumerable<string> values);
				throw new TooManyRequestsException("You have reached your rate limit. Too many requests were made", values.FirstOrDefault(), errorResp);
			}
			case HttpStatusCode.BadGateway:
				throw new BadGatewayException("The API answered with a 502 Bad Gateway. Please retry your request", errorResp);
			case HttpStatusCode.GatewayTimeout:
				throw new GatewayTimeoutException("The API answered with a 504 Gateway Timeout. Please retry your request", errorResp);
			case HttpStatusCode.InternalServerError:
				throw new InternalServerErrorException("The API answered with a 500 Internal Server Error. Please retry your request", errorResp);
			case HttpStatusCode.Forbidden:
				throw new BadTokenException("The token provided in the request did not match the associated user. Make sure the token you're using is from the resource owner (streamer? viewer?)", errorResp);
			default:
				throw new HttpRequestException("Something went wrong during the request! Please try again later");
			}
		}
	}
	[Obsolete("The WebRequest handler is deprecated and is not updated to be working with Helix correctly")]
	public class TwitchWebRequest : IHttpCallHandler
	{
		private readonly ILogger<TwitchWebRequest> _logger;

		public TwitchWebRequest(ILogger<TwitchWebRequest> logger = null)
		{
			_logger = logger;
		}

		public Task PutBytesAsync(string url, byte[] payload)
		{
			return Task.Factory.StartNew(delegate
			{
				try
				{
					using WebClient webClient = new WebClient();
					webClient.UploadData(new Uri(url), "PUT", payload);
				}
				catch (WebException e)
				{
					HandleWebException(e);
				}
			});
		}

		public async Task<KeyValuePair<int, string>> GeneralRequestAsync(string url, string method, string payload = null, ApiVersion api = 6, string clientId = null, string accessToken = null)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			HttpWebRequest request = WebRequest.CreateHttp(url);
			if (string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(accessToken))
			{
				throw new InvalidCredentialException("A Client-Id or OAuth token is required to use the Twitch API. If you previously set them in InitializeAsync, please be sure to await the method.");
			}
			if (!string.IsNullOrEmpty(clientId))
			{
				request.Headers["Client-ID"] = clientId;
			}
			request.Method = method;
			request.ContentType = "application/json";
			string authPrefix = "OAuth";
			if ((int)api == 6)
			{
				request.Accept = "application/json";
				authPrefix = "Bearer";
			}
			else if ((int)api > 0)
			{
				request.Accept = $"application/vnd.twitchtv.v{(int)api}+json";
			}
			if (!string.IsNullOrEmpty(accessToken))
			{
				request.Headers["Authorization"] = authPrefix + " " + Helpers.FormatOAuth(accessToken);
			}
			if (payload != null)
			{
				using StreamWriter writer = new StreamWriter(await request.GetRequestStreamAsync().ConfigureAwait(continueOnCapturedContext: false));
				await writer.WriteAsync(payload).ConfigureAwait(continueOnCapturedContext: false);
			}
			try
			{
				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
				using StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException());
				return new KeyValuePair<int, string>(value: await reader.ReadToEndAsync().ConfigureAwait(continueOnCapturedContext: false), key: (int)response.StatusCode);
			}
			catch (WebException ex)
			{
				HandleWebException(ex);
			}
			return new KeyValuePair<int, string>(0, null);
		}

		public Task<int> RequestReturnResponseCodeAsync(string url, string method, List<KeyValuePair<string, string>> getParams = null)
		{
			return Task.Factory.StartNew(delegate
			{
				if (getParams != null)
				{
					for (int i = 0; i < getParams.Count; i++)
					{
						if (i == 0)
						{
							url = url + "?" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value);
						}
						else
						{
							url = url + "&" + getParams[i].Key + "=" + Uri.EscapeDataString(getParams[i].Value);
						}
					}
				}
				HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
				httpWebRequest.Method = method;
				HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
				return (int)httpWebResponse.StatusCode;
			});
		}

		private void HandleWebException(WebException e)
		{
			if (!(e.Response is HttpWebResponse httpWebResponse))
			{
				throw e;
			}
			switch (httpWebResponse.StatusCode)
			{
			case HttpStatusCode.BadRequest:
				throw new BadRequestException("Your request failed because either: \n 1. Your ClientID was invalid/not set. \n 2. Your refresh token was invalid. \n 3. You requested a username when the server was expecting a user ID.", null);
			case HttpStatusCode.Unauthorized:
			{
				string[] values = httpWebResponse.Headers.GetValues("WWW-Authenticate");
				if ((values != null && values.Length == 0) || string.IsNullOrEmpty((values != null) ? values[0] : null))
				{
					throw new BadScopeException("Your request was blocked due to bad credentials (do you have the right scope for your access token?).", null);
				}
				if (values[0].Contains("error='invalid_token'"))
				{
					throw new TokenExpiredException("Your request was blocked du to an expired Token. Please refresh your token and update your API instance settings.", null);
				}
				break;
			}
			case HttpStatusCode.NotFound:
				throw new BadResourceException("The resource you tried to access was not valid.", null);
			case HttpStatusCode.TooManyRequests:
			{
				string resetTime = httpWebResponse.Headers.Get("Ratelimit-Reset");
				throw new TooManyRequestsException("You have reached your rate limit. Too many requests were made", resetTime, null);
			}
			default:
				throw e;
			}
		}
	}
}
namespace TwitchLib.Api.Core.Extensions.System
{
	public static class DateTimeExtensions
	{
		public static string ToRfc3339String(this DateTime dateTime)
		{
			return dateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo);
		}
	}
	public static class IEnumerableExtensions
	{
		public static void AddTo<T>(this IEnumerable<T> source, List<T> destination)
		{
			if (source != null)
			{
				destination.AddRange(source);
			}
		}
	}
}
namespace TwitchLib.Api.Core.Extensions.RateLimiter
{
	public static class IAwaitableConstraintExtension
	{
		public static IAwaitableConstraint Compose(this IAwaitableConstraint ac1, IAwaitableConstraint ac2)
		{
			IAwaitableConstraint result;
			if (ac1 != ac2)
			{
				IAwaitableConstraint val = (IAwaitableConstraint)(object)new ComposedAwaitableConstraint(ac1, ac2);
				result = val;
			}
			else
			{
				result = ac1;
			}
			return result;
		}
	}
}
namespace TwitchLib.Api.Core.Exceptions
{
	public class BadGatewayException : HttpResponseException
	{
		public BadGatewayException(string data, HttpResponseMessage httpResponse)
			: base(data, httpResponse)
		{
		}
	}
	public class BadParameterException : Exception
	{
		public BadParameterException(string badParamData)
			: base(badParamData)
		{
		}
	}
	public class BadRequestException : HttpResponseException
	{
		public BadRequestException(string apiData, HttpResponseMessage httpResponse)
			: base(apiData, httpResponse)
		{
		}
	}
	public class BadResourceException : HttpResponseException
	{
		public BadResourceException(string apiData, HttpResponseMessage httpResponse)
			: base(apiData, httpResponse)
		{
		}
	}
	public class BadScopeException : HttpResponseException
	{
		public BadScopeException(string data, HttpResponseMessage httpResponse)
			: base(data, httpResponse)
		{
		}
	}
	public class BadTokenException : HttpResponseException
	{
		public BadTokenException(string data, HttpResponseMessage httpResponse)
			: base(data, httpResponse)
		{
		}
	}
	public class ClientIdAndOAuthTokenRequired : Exception
	{
		public ClientIdAndOAuthTokenRequired(string explanation)
			: base(explanation)
		{
		}
	}
	public class GatewayTimeoutException : HttpResponseException
	{
		public GatewayTimeoutException(string data, HttpResponseMessage httpResponse)
			: base(data, httpResponse)
		{
		}
	}
	public class HttpResponseException : Exception
	{
		public HttpResponseMessage HttpResponse { get; }

		public HttpResponseException(string apiData, HttpResponseMessage httpResponse)
			: base(apiData)
		{
			HttpResponse = httpResponse;
		}
	}
	public class InternalServerErrorException : HttpResponseException
	{
		public InternalServerErrorException(string data, HttpResponseMessage httpResponse)
			: base(data, httpResponse)
		{
		}
	}
	public class InvalidCredentialException : Exception
	{
		public InvalidCredentialException(string data)
			: base(data)
		{
		}
	}
	public class TokenExpiredException : HttpResponseException
	{
		public TokenExpiredException(string data, HttpResponseMessage httpResponse)
			: base(data, httpResponse)
		{
		}
	}
	public sealed class TooManyRequestsException : HttpResponseException
	{
		public TooManyRequestsException(string data, string resetTime, HttpResponseMessage httpResponse)
			: base(data, httpResponse)
		{
			if (double.TryParse(resetTime, out var result))
			{
				Data.Add("Ratelimit-Reset", result);
			}
		}
	}
	public class UnexpectedResponseException : HttpResponseException
	{
		public UnexpectedResponseException(string data, HttpResponseMessage httpResponse)
			: base(data, httpResponse)
		{
		}
	}
}
namespace TwitchLib.Api.Core.Common
{
	public static class Helpers
	{
		public static string FormatOAuth(string token)
		{
			return token.Contains(" ") ? token.Split(' ')[1] : token;
		}

		public static string AuthScopesToString(AuthScopes scope)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Expected I4, but got Unknown
			if (1 == 0)
			{
			}
			string result = (int)scope switch
			{
				1 => "chat:read", 
				3 => "channel:moderate", 
				2 => "chat:edit", 
				4 => "whispers:read", 
				5 => "whispers:edit", 
				6 => "analytics:read:extensions", 
				7 => "analytics:read:games", 
				8 => "bits:read", 
				9 => "channel:bot", 
				11 => "channel:manage:ads", 
				10 => "channel:edit:commercial", 
				12 => "channel:manage:broadcast", 
				13 => "channel:manage:extensions", 
				14 => "channel:manage:moderators", 
				17 => "channel:manage:redemptions", 
				15 => "channel:manage:polls", 
				16 => "channel:manage:predictions", 
				18 => "channel:manage:schedule", 
				21 => "channel:manage:videos", 
				22 => "channel:manage:vips", 
				19 => "channel:manage:guest_star", 
				20 => "channel:manage:raids", 
				23 => "channel:read:ads", 
				24 => "channel:read:charity", 
				25 => "channel:read:editors", 
				26 => "channel:read:goals", 
				27 => "channel:read:hype_train", 
				28 => "channel:read:polls", 
				29 => "channel:read:predictions", 
				30 => "channel:read:redemptions", 
				32 => "channel:read:stream_key", 
				33 => "channel:read:subscriptions", 
				34 => "channel:read:vips", 
				31 => "channel:read:guest_star", 
				35 => "clips:edit", 
				36 => "moderation:read", 
				55 => "user:bot", 
				56 => "user:edit", 
				57 => "user:edit:follows", 
				61 => "user:read:blocked_users", 
				62 => "user:read:broadcast", 
				63 => "user:read:chat", 
				64 => "user:read:email", 
				65 => "user:read:follows", 
				67 => "user:read:subscriptions", 
				58 => "user:manage:blocked_users", 
				59 => "user:manage:chat_color", 
				60 => "user:manage:whispers", 
				68 => "user:write:chat", 
				37 => "moderator:manage:announcements", 
				38 => "moderator:manage:automod", 
				39 => "moderator:manage:automod_settings", 
				40 => "moderator:manage:banned_users", 
				41 => "moderator:manage:blocked_terms", 
				42 => "moderator:manage:chat_messages", 
				43 => "moderator:manage:chat_settings", 
				47 => "moderator:read:automod_settings", 
				48 => "moderator:read:blocked_terms", 
				49 => "moderator:read:chat_settings", 
				50 => "moderator:read:chatters", 
				51 => "moderator:read:followers", 
				52 => "moderator:read:guest_star", 
				53 => "moderator:read:shield_mode", 
				54 => "moderator:read:shoutouts", 
				44 => "moderator:manage:guest_star", 
				45 => "moderator:manage:shield_mode", 
				46 => "moderator:manage:shoutouts", 
				0 => string.Empty, 
				69 => string.Empty, 
				_ => string.Empty, 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		public static AuthScopes StringToScope(string scope)
		{
			//IL_0bb4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b07: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bbe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a65: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b6f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0af7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0abf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b97: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ac7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b17: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a7a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a73: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ab7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bd7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aaf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a6c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0beb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0baf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bc3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a8f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bcd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0be6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c09: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b9f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bc8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a5e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a88: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ae7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b0f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b5f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c34: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c35: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b2f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bb9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b27: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b87: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a81: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c0e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0be1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bf5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b7f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b47: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ad7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c18: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b8f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ba7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b67: Unknown result type (might be due to invalid IL or missing references)
			//IL_0acf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c1d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b77: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a97: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bd2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b1f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bfa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b37: Unknown result type (might be due to invalid IL or missing references)
			//IL_0adf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bdc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c13: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aa7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b4f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b3f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c04: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c38: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c22: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a9f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bf0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b57: Unknown result type (might be due to invalid IL or missing references)
			if (1 == 0)
			{
			}
			AuthScopes result = (AuthScopes)(scope switch
			{
				"chat:read" => 1, 
				"channel:moderate" => 3, 
				"chat:edit" => 2, 
				"whispers:read" => 4, 
				"whispers:edit" => 5, 
				"analytics:read:extensions" => 6, 
				"analytics:read:games" => 7, 
				"bits:read" => 8, 
				"channel:bot" => 9, 
				"channel:edit:commercial" => 10, 
				"channel:manage:ads" => 11, 
				"channel:manage:broadcast" => 12, 
				"channel:manage:extensions" => 13, 
				"channel:manage:moderators" => 14, 
				"channel:manage:redemptions" => 17, 
				"channel:manage:polls" => 15, 
				"channel:manage:predictions" => 16, 
				"channel:manage:schedule" => 18, 
				"channel:manage:videos" => 21, 
				"channel:manage:vips" => 22, 
				"channel:manage:guest_star" => 19, 
				"channel:manage:raids" => 20, 
				"channel:read:ads" => 23, 
				"channel:read:charity" => 24, 
				"channel:read:editors" => 25, 
				"channel:read:goals" => 26, 
				"channel:read:hype_train" => 27, 
				"channel:read:polls" => 28, 
				"channel:read:predictions" => 29, 
				"channel:read:redemptions" => 30, 
				"channel:read:stream_key" => 32, 
				"channel:read:subscriptions" => 33, 
				"channel:read:vips" => 34, 
				"channel:read:guest_star" => 31, 
				"clips:edit" => 35, 
				"moderation:read" => 36, 
				"user:bot" => 55, 
				"user:edit" => 56, 
				"user:edit:follows" => 57, 
				"user:read:blocked_users" => 61, 
				"user:read:broadcast" => 62, 
				"user:read:chat" => 63, 
				"user:read:email" => 64, 
				"user:read:follows" => 65, 
				"user:read:subscriptions" => 67, 
				"user:manage:blocked_users" => 58, 
				"user:manage:chat_color" => 59, 
				"user:manage:whispers" => 60, 
				"moderator:manage:announcements" => 37, 
				"moderator:manage:automod" => 38, 
				"moderator:manage:automod_settings" => 39, 
				"moderator:manage:banned_users" => 40, 
				"moderator:manage:blocked_terms" => 41, 
				"moderator:manage:chat_messages" => 42, 
				"moderator:manage:chat_settings" => 43, 
				"moderator:manage:guest_star" => 44, 
				"moderator:manage:shield_mode" => 45, 
				"moderator:manage:shoutouts" => 46, 
				"moderator:read:automod_settings" => 47, 
				"moderator:read:blocked_terms" => 48, 
				"moderator:read:chat_settings" => 49, 
				"moderator:read:chatters" => 50, 
				"moderator:read:followers" => 51, 
				"moderator:read:guest_star" => 52, 
				"moderator:read:shield_mode" => 53, 
				"moderator:read:shoutouts" => 54, 
				"" => 69, 
				_ => throw new Exception("Unknown scope"), 
			});
			if (1 == 0)
			{
			}
			return result;
		}

		public static string Base64Encode(string plainText)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(plainText);
			return Convert.ToBase64String(bytes);
		}
	}
}

TwitchLib.Api.Core.Enums.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2022")]
[assembly: AssemblyDescription("Project containing the enums of TwitchLib.Api")]
[assembly: AssemblyFileVersion("3.10.0")]
[assembly: AssemblyInformationalVersion("3.10.0+92a4359ed145876af4e8e108e267004dcb0babab")]
[assembly: AssemblyProduct("TwitchLib.Api.Core.Enums")]
[assembly: AssemblyTitle("TwitchLib.Api.Core.Enums")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/swiftyspiffy/TwitchLib")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("3.10.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 TwitchLib.Api.Core.Enums
{
	public enum ApiVersion
	{
		Auth = 1,
		Helix = 6,
		Void = 0
	}
	public enum AuthScopes
	{
		Any,
		Chat_Read,
		Chat_Edit,
		Channel_Moderate,
		Whisper_Read,
		Whisper_Edit,
		Analytics_Read_Extensions,
		Analytics_Read_Games,
		Bits_Read,
		Channel_Bot,
		Channel_Edit_Commercial,
		Channel_Manage_Ads,
		Channel_Manage_Broadcast,
		Channel_Manage_Extensions,
		Channel_Manage_Moderators,
		Channel_Manage_Polls,
		Channel_Manage_Predictions,
		Channel_Manage_Redemptions,
		Channel_Manage_Schedule,
		Channel_Manage_Guest_Star,
		Channel_Manage_Raids,
		Channel_Manage_Videos,
		Channel_Manage_VIPs,
		Channel_Read_Ads,
		Channel_Read_Charity,
		Channel_Read_Editors,
		Channel_Read_Goals,
		Channel_Read_Hype_Train,
		Channel_Read_Polls,
		Channel_Read_Predictions,
		Channel_Read_Redemptions,
		Channel_Read_Guest_Star,
		Channel_Read_Stream_Key,
		Channel_Read_Subscriptions,
		Channel_Read_VIPs,
		Clips_Edit,
		Moderation_Read,
		Moderator_Manage_Announcements,
		Moderator_Manage_Automod,
		Moderator_Manage_Automod_Settings,
		Moderator_Manage_Banned_Users,
		Moderator_Manage_Blocked_Terms,
		Moderator_Manage_Chat_Messages,
		Moderator_Manage_Chat_Settings,
		Moderator_Manage_Guest_Star,
		Moderator_Manage_Shield_Mode,
		Moderator_Manage_Shoutouts,
		Moderator_Read_Automod_Settings,
		Moderator_Read_Blocked_Terms,
		Moderator_Read_Chat_Settings,
		Moderator_Read_Chatters,
		Moderator_Read_Followers,
		Moderator_Read_Guest_Star,
		Moderator_Read_Shield_Mode,
		Moderator_Read_Shoutouts,
		User_Bot,
		User_Edit,
		[Obsolete("Deprecated")]
		User_Edit_Follows,
		User_Manage_BlockedUsers,
		User_Manage_Chat_Color,
		User_Manage_Whispers,
		User_Read_BlockedUsers,
		User_Read_Broadcast,
		User_Read_Chat,
		User_Read_Email,
		User_Read_Follows,
		User_Read_Moderated_Channels,
		User_Read_Subscriptions,
		User_Write_Chat,
		None
	}
	public enum BadgeColor
	{
		Red = 10000,
		Blue = 5000,
		Green = 1000,
		Purple = 100,
		Gray = 1
	}
	public enum BitsLeaderboardPeriodEnum
	{
		Day,
		Week,
		Month,
		Year,
		All
	}
	public enum BlockUserReasonEnum
	{
		Spam,
		Harassment,
		Other
	}
	public enum BlockUserSourceContextEnum
	{
		Chat,
		Whisper
	}
	public enum CodeStatusEnum
	{
		SUCCESSFULLY_REDEEMED,
		ALREADY_CLAIMED,
		EXPIRED,
		USER_NOT_ELIGIBLE,
		NOT_FOUND,
		INACTIVE,
		UNUSED,
		INCORRECT_FORMAT,
		INTERNAL_ERROR
	}
	public enum ContentClassificationLabelEnum
	{
		DrugsIntoxication,
		SexualThemes,
		ViolentGraphic,
		Gambling,
		ProfanityVulgarity
	}
	public enum CustomRewardRedemptionStatus
	{
		UNFULFILLED,
		FULFILLED,
		CANCELED
	}
	public enum DropEntitlementUpdateStatus
	{
		SUCCESS,
		UNAUTHORIZED,
		UPDATE_FAILED,
		INVALID_ID,
		NOT_FOUND
	}
	public enum EventSubTransportMethod
	{
		Webhook,
		Websocket,
		Conduit
	}
	public enum ExtensionState
	{
		InTest,
		InReview,
		Rejected,
		Approved,
		Released,
		Deprecated,
		PendingAction,
		AssetsUploaded,
		Deleted
	}
	public enum ExtensionType
	{
		Panel,
		Overlay,
		Component
	}
	public enum FulfillmentStatus
	{
		CLAIMED,
		FULFILLED
	}
	public enum LogType
	{
		Normal,
		Failure,
		Success
	}
	public enum ManageHeldAutoModMessageActionEnum
	{
		ALLOW,
		DENY
	}
	public enum Period
	{
		Day,
		Week,
		Month,
		All
	}
	public enum PollStatusEnum
	{
		TERMINATED,
		ARCHIVED
	}
	public enum PredictionEndStatus
	{
		RESOLVED,
		CANCELED,
		LOCKED
	}
	public enum PredictionStatus
	{
		ACTIVE,
		RESOLVED,
		CANCELED,
		LOCKED
	}
	public abstract class StringEnum
	{
		public string Value { get; }

		protected StringEnum(string value)
		{
			Value = value;
		}

		public override string ToString()
		{
			return Value;
		}
	}
	public enum UserType : byte
	{
		Viewer,
		VIP,
		Moderator,
		GlobalModerator,
		Broadcaster,
		Admin,
		Staff
	}
	public enum VideoSort
	{
		Time,
		Trending,
		Views
	}
	public enum VideoType
	{
		All,
		Upload,
		Archive,
		Highlight
	}
}

TwitchLib.Api.Core.Interfaces.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using TwitchLib.Api.Core.Enums;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2022")]
[assembly: AssemblyDescription("Project containing all of the interfaces used in TwitchLib.Api")]
[assembly: AssemblyFileVersion("3.10.0")]
[assembly: AssemblyInformationalVersion("3.10.0+92a4359ed145876af4e8e108e267004dcb0babab")]
[assembly: AssemblyProduct("TwitchLib.Api.Core.Interfaces")]
[assembly: AssemblyTitle("TwitchLib.Api.Core.Interfaces")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/swiftyspiffy/TwitchLib")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("3.10.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 TwitchLib.Api.Core.Interfaces
{
	public interface IApiSettings
	{
		string AccessToken { get; set; }

		string Secret { get; set; }

		string ClientId { get; set; }

		bool SkipDynamicScopeValidation { get; set; }

		bool SkipAutoServerTokenGeneration { get; set; }

		List<AuthScopes> Scopes { get; set; }

		event PropertyChangedEventHandler PropertyChanged;
	}
	public interface IAwaitableConstraint
	{
		Task<IDisposable> WaitForReadiness(CancellationToken cancellationToken);
	}
	public interface IFollow
	{
		DateTime CreatedAt { get; }

		bool Notifications { get; }

		IUser User { get; }
	}
	public interface IFollows
	{
		int Total { get; }

		string Cursor { get; }

		IFollow[] Follows { get; }
	}
	public interface IHttpCallHandler
	{
		Task<KeyValuePair<int, string>> GeneralRequestAsync(string url, string method, string payload = null, ApiVersion api = 6, string clientId = null, string accessToken = null);

		Task PutBytesAsync(string url, byte[] payload);

		Task<int> RequestReturnResponseCodeAsync(string url, string method, List<KeyValuePair<string, string>> getParams = null);
	}
	public interface IRateLimiter
	{
		Task Perform(Func<Task> perform, CancellationToken cancellationToken);

		Task Perform(Func<Task> perform);

		Task<T> Perform<T>(Func<Task<T>> perform);

		Task<T> Perform<T>(Func<Task<T>> perform, CancellationToken cancellationToken);

		Task Perform(Action perform, CancellationToken cancellationToken);

		Task Perform(Action perform);

		Task<T> Perform<T>(Func<T> perform);

		Task<T> Perform<T>(Func<T> perform, CancellationToken cancellationToken);
	}
	public interface ITime
	{
		DateTime GetTimeNow();

		Task GetDelay(TimeSpan timespan, CancellationToken cancellationToken);
	}
	public interface IUser
	{
		string Id { get; }

		string Bio { get; }

		DateTime CreatedAt { get; }

		string DisplayName { get; }

		string Logo { get; }

		string Name { get; }

		string Type { get; }

		DateTime UpdatedAt { get; }
	}
}

TwitchLib.Api.Core.Models.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using TwitchLib.Api.Core.Enums;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2022")]
[assembly: AssemblyDescription("Project containing the core models used in TwitchLib.Api")]
[assembly: AssemblyFileVersion("3.10.0")]
[assembly: AssemblyInformationalVersion("3.10.0+92a4359ed145876af4e8e108e267004dcb0babab")]
[assembly: AssemblyProduct("TwitchLib.Api.Core.Models")]
[assembly: AssemblyTitle("TwitchLib.Api.Core.Models")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/swiftyspiffy/TwitchLib")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("3.10.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 TwitchLib.Api.Core.Models
{
	public abstract class RequestModel
	{
	}
}
namespace TwitchLib.Api.Core.Models.Undocumented.Chatters
{
	public class ChatterFormatted
	{
		public string Username { get; protected set; }

		public UserType UserType { get; set; }

		public ChatterFormatted(string username, UserType userType)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Username = username;
			UserType = userType;
		}
	}
	public class Chatters
	{
		[JsonProperty(PropertyName = "moderators")]
		public string[] Moderators { get; protected set; }

		[JsonProperty(PropertyName = "staff")]
		public string[] Staff { get; protected set; }

		[JsonProperty(PropertyName = "admins")]
		public string[] Admins { get; protected set; }

		[JsonProperty(PropertyName = "global_mods")]
		public string[] GlobalMods { get; protected set; }

		[JsonProperty(PropertyName = "vips")]
		public string[] VIP { get; protected set; }

		[JsonProperty(PropertyName = "viewers")]
		public string[] Viewers { get; protected set; }
	}
	public class ChattersResponse
	{
		[JsonProperty(PropertyName = "chatter_count")]
		public int ChatterCount { get; protected set; }

		[JsonProperty(PropertyName = "chatters")]
		public Chatters Chatters { get; protected set; }
	}
}

TwitchLib.Api.dll

Decompiled a month ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using System.Timers;
using System.Web;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TwitchLib.Api.Auth;
using TwitchLib.Api.Core;
using TwitchLib.Api.Core.Common;
using TwitchLib.Api.Core.Enums;
using TwitchLib.Api.Core.Exceptions;
using TwitchLib.Api.Core.HttpCallHandlers;
using TwitchLib.Api.Core.Interfaces;
using TwitchLib.Api.Core.RateLimiter;
using TwitchLib.Api.Core.Undocumented;
using TwitchLib.Api.Events;
using TwitchLib.Api.Helix;
using TwitchLib.Api.Helix.Models.Channels.GetChannelFollowers;
using TwitchLib.Api.Helix.Models.Helpers;
using TwitchLib.Api.Helix.Models.Streams.GetStreams;
using TwitchLib.Api.Helix.Models.Users.GetUsers;
using TwitchLib.Api.Interfaces;
using TwitchLib.Api.Services.Core;
using TwitchLib.Api.Services.Core.FollowerService;
using TwitchLib.Api.Services.Core.LiveStreamMonitor;
using TwitchLib.Api.Services.Events;
using TwitchLib.Api.Services.Events.FollowerService;
using TwitchLib.Api.Services.Events.LiveStreamMonitor;
using TwitchLib.Api.ThirdParty;
using TwitchLib.Api.ThirdParty.AuthorizationFlow;
using TwitchLib.Api.ThirdParty.ModLookup;
using TwitchLib.Api.ThirdParty.UsernameChange;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2022")]
[assembly: AssemblyDescription("Api component of TwitchLib. This component allows you to access the Twitch API, as well as undocumented and third party APIs.")]
[assembly: AssemblyFileVersion("3.10.0")]
[assembly: AssemblyInformationalVersion("3.10.0+92a4359ed145876af4e8e108e267004dcb0babab")]
[assembly: AssemblyProduct("TwitchLib.Api")]
[assembly: AssemblyTitle("TwitchLib.Api")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/swiftyspiffy/TwitchLib")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("3.10.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 TwitchLib.Api
{
	public class TwitchAPI : ITwitchAPI
	{
		private readonly ILogger<TwitchAPI> _logger;

		public IApiSettings Settings { get; }

		public TwitchLib.Api.Auth.Auth Auth { get; }

		public Helix Helix { get; }

		public TwitchLib.Api.ThirdParty.ThirdParty ThirdParty { get; }

		public Undocumented Undocumented { get; }

		public TwitchAPI(ILoggerFactory loggerFactory = null, IRateLimiter rateLimiter = null, IApiSettings settings = null, IHttpCallHandler http = null)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			_logger = loggerFactory?.CreateLogger<TwitchAPI>();
			rateLimiter = (IRateLimiter)(((object)rateLimiter) ?? ((object)BypassLimiter.CreateLimiterBypassInstance()));
			http = (IHttpCallHandler)(((object)http) ?? ((object)new TwitchHttpClient(loggerFactory?.CreateLogger<TwitchHttpClient>())));
			Settings = (IApiSettings)(((object)settings) ?? ((object)new ApiSettings()));
			Auth = new TwitchLib.Api.Auth.Auth(Settings, rateLimiter, http);
			Helix = new Helix(loggerFactory, rateLimiter, Settings, http);
			ThirdParty = new TwitchLib.Api.ThirdParty.ThirdParty(Settings, rateLimiter, http);
			Undocumented = new Undocumented(Settings, rateLimiter, http);
			Settings.PropertyChanged += SettingsPropertyChanged;
		}

		private void SettingsPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			switch (e.PropertyName)
			{
			case "AccessToken":
				Helix.Settings.AccessToken = Settings.AccessToken;
				break;
			case "Secret":
				Helix.Settings.Secret = Settings.Secret;
				break;
			case "ClientId":
				Helix.Settings.ClientId = Settings.ClientId;
				break;
			case "SkipDynamicScopeValidation":
				Helix.Settings.SkipDynamicScopeValidation = Settings.SkipDynamicScopeValidation;
				break;
			case "SkipAutoServerTokenGeneration":
				Helix.Settings.SkipAutoServerTokenGeneration = Settings.SkipAutoServerTokenGeneration;
				break;
			case "Scopes":
				Helix.Settings.Scopes = Settings.Scopes;
				break;
			}
		}
	}
}
namespace TwitchLib.Api.ThirdParty
{
	public class ThirdParty
	{
		public class UsernameChangeApi : ApiBase
		{
			public UsernameChangeApi(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
				: base(settings, rateLimiter, http)
			{
			}

			public Task<List<UsernameChangeListing>> GetUsernameChangesAsync(string username)
			{
				List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
				{
					new KeyValuePair<string, string>("q", username),
					new KeyValuePair<string, string>("format", "json")
				};
				return ((ApiBase)this).GetGenericAsync<List<UsernameChangeListing>>("https://twitch-tools.rootonline.de/username_changelogs_search.php", list, (string)null, (ApiVersion)0, (string)null);
			}
		}

		public class ModLookupApi : ApiBase
		{
			public ModLookupApi(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
				: base(settings, rateLimiter, http)
			{
			}

			public Task<ModLookupResponse> GetChannelsModdedForByNameAsync(string username, int offset = 0, int limit = 100, bool useTls12 = true)
			{
				if (useTls12)
				{
					ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
				}
				List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
				{
					new KeyValuePair<string, string>("offset", offset.ToString()),
					new KeyValuePair<string, string>("limit", limit.ToString())
				};
				return ((ApiBase)this).GetGenericAsync<ModLookupResponse>("https://twitchstuff.3v.fi/modlookup/api/user/" + username, list, (string)null, (ApiVersion)0, (string)null);
			}

			public Task<TopResponse> GetChannelsModdedForByTopAsync(bool useTls12 = true)
			{
				if (useTls12)
				{
					ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
				}
				return ((ApiBase)this).GetGenericAsync<TopResponse>("https://twitchstuff.3v.fi/modlookup/api/top", (List<KeyValuePair<string, string>>)null, (string)null, (ApiVersion)6, (string)null);
			}

			public Task<StatsResponse> GetChannelsModdedForStatsAsync(bool useTls12 = true)
			{
				if (useTls12)
				{
					ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
				}
				return ((ApiBase)this).GetGenericAsync<StatsResponse>("https://twitchstuff.3v.fi/modlookup/api/stats", (List<KeyValuePair<string, string>>)null, (string)null, (ApiVersion)6, (string)null);
			}
		}

		public class AuthorizationFlowApi : ApiBase
		{
			private const string BaseUrl = "https://twitchtokengenerator.com/api";

			private string _apiId;

			private Timer _pingTimer;

			public event EventHandler<OnUserAuthorizationDetectedArgs> OnUserAuthorizationDetected;

			public event EventHandler<OnAuthorizationFlowErrorArgs> OnError;

			public AuthorizationFlowApi(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
				: base(settings, rateLimiter, http)
			{
			}

			public CreatedFlow CreateFlow(string applicationTitle, IEnumerable<AuthScopes> scopes)
			{
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				string text = null;
				foreach (AuthScopes scope in scopes)
				{
					text = ((text != null) ? (text + "+" + Helpers.AuthScopesToString(scope)) : Helpers.AuthScopesToString(scope));
				}
				string address = "https://twitchtokengenerator.com/api/create/" + Helpers.Base64Encode(applicationTitle) + "/" + text;
				string text2 = new WebClient().DownloadString(address);
				return JsonConvert.DeserializeObject<CreatedFlow>(text2);
			}

			public RefreshTokenResponse RefreshToken(string refreshToken)
			{
				string address = "https://twitchtokengenerator.com/api/refresh/" + refreshToken;
				string text = new WebClient().DownloadString(address);
				return JsonConvert.DeserializeObject<RefreshTokenResponse>(text);
			}

			public void BeginPingingStatus(string id, int intervalMs = 5000)
			{
				_apiId = id;
				_pingTimer = new Timer(intervalMs);
				_pingTimer.Elapsed += OnPingTimerElapsed;
				_pingTimer.Start();
			}

			public PingResponse PingStatus(string id = null)
			{
				if (id != null)
				{
					_apiId = id;
				}
				string jsonStr = new WebClient().DownloadString("https://twitchtokengenerator.com/api/status/" + _apiId);
				return new PingResponse(jsonStr);
			}

			private void OnPingTimerElapsed(object sender, ElapsedEventArgs e)
			{
				PingResponse pingResponse = PingStatus();
				if (pingResponse.Success)
				{
					_pingTimer.Stop();
					this.OnUserAuthorizationDetected?.Invoke(null, new OnUserAuthorizationDetectedArgs
					{
						Id = pingResponse.Id,
						Scopes = pingResponse.Scopes,
						Token = pingResponse.Token,
						Username = pingResponse.Username,
						Refresh = pingResponse.Refresh,
						ClientId = pingResponse.ClientId
					});
				}
				else if (pingResponse.Error != 3)
				{
					_pingTimer.Stop();
					this.OnError?.Invoke(null, new OnAuthorizationFlowErrorArgs
					{
						Error = pingResponse.Error,
						Message = pingResponse.Message
					});
				}
			}
		}

		public UsernameChangeApi UsernameChange { get; }

		public ModLookupApi ModLookup { get; }

		public AuthorizationFlowApi AuthorizationFlow { get; }

		public ThirdParty(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
		{
			UsernameChange = new UsernameChangeApi(settings, rateLimiter, http);
			ModLookup = new ModLookupApi(settings, rateLimiter, http);
			AuthorizationFlow = new AuthorizationFlowApi(settings, rateLimiter, http);
		}
	}
}
namespace TwitchLib.Api.ThirdParty.UsernameChange
{
	public class UsernameChangeListing
	{
		[JsonProperty(PropertyName = "userid")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "username_old")]
		public string UsernameOld { get; protected set; }

		[JsonProperty(PropertyName = "username_new")]
		public string UsernameNew { get; protected set; }

		[JsonProperty(PropertyName = "found_at")]
		public DateTime FoundAt { get; protected set; }
	}
	public class UsernameChangeResponse
	{
		public UsernameChangeListing[] UsernameChangeListings { get; protected set; }
	}
}
namespace TwitchLib.Api.ThirdParty.ModLookup
{
	public class ModLookupListing
	{
		[JsonProperty(PropertyName = "name")]
		public string Name { get; protected set; }

		[JsonProperty(PropertyName = "followers")]
		public int Followers { get; protected set; }

		[JsonProperty(PropertyName = "views")]
		public int Views { get; protected set; }

		[JsonProperty(PropertyName = "partnered")]
		public bool Partnered { get; protected set; }
	}
	public class ModLookupResponse
	{
		[JsonProperty(PropertyName = "status")]
		public int Status { get; protected set; }

		[JsonProperty(PropertyName = "user")]
		public string User { get; protected set; }

		[JsonProperty(PropertyName = "count")]
		public int Count { get; protected set; }

		[JsonProperty(PropertyName = "channels")]
		public ModLookupListing[] Channels { get; protected set; }
	}
	public class Stats
	{
		[JsonProperty(PropertyName = "relations")]
		public int Relations { get; protected set; }

		[JsonProperty(PropertyName = "channels_total")]
		public int ChannelsTotal { get; protected set; }

		[JsonProperty(PropertyName = "users")]
		public int Users { get; protected set; }

		[JsonProperty(PropertyName = "channels_no_mods")]
		public int ChannelsNoMods { get; protected set; }

		[JsonProperty(PropertyName = "channels_only_broadcaster")]
		public int ChannelsOnlyBroadcaster { get; protected set; }
	}
	public class StatsResponse
	{
		[JsonProperty(PropertyName = "status")]
		public int Status { get; protected set; }

		[JsonProperty(PropertyName = "stats")]
		public Stats Stats { get; protected set; }
	}
	public class Top
	{
		[JsonProperty(PropertyName = "modcount")]
		public ModLookupListing[] ModCount { get; protected set; }

		[JsonProperty(PropertyName = "views")]
		public ModLookupListing[] Views { get; protected set; }

		[JsonProperty(PropertyName = "followers")]
		public ModLookupListing[] Followers { get; protected set; }
	}
	public class TopResponse
	{
		[JsonProperty(PropertyName = "status")]
		public int Status { get; protected set; }

		[JsonProperty(PropertyName = "top")]
		public Top Top { get; protected set; }
	}
}
namespace TwitchLib.Api.ThirdParty.AuthorizationFlow
{
	public class CreatedFlow
	{
		[JsonProperty(PropertyName = "message")]
		public string Url { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }
	}
	public class PingResponse
	{
		public bool Success { get; protected set; }

		public string Id { get; protected set; }

		public int Error { get; protected set; }

		public string Message { get; protected set; }

		public List<AuthScopes> Scopes { get; protected set; }

		public string Token { get; protected set; }

		public string Refresh { get; protected set; }

		public string Username { get; protected set; }

		public string ClientId { get; protected set; }

		public PingResponse(string jsonStr)
		{
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			JObject val = JObject.Parse(jsonStr);
			Success = bool.Parse(((object)((JToken)val).SelectToken("success")).ToString());
			if (!Success)
			{
				Error = int.Parse(((object)((JToken)val).SelectToken("error")).ToString());
				Message = ((object)((JToken)val).SelectToken("message")).ToString();
				return;
			}
			Scopes = new List<AuthScopes>();
			foreach (JToken item in (IEnumerable<JToken>)((JToken)val).SelectToken("scopes"))
			{
				Scopes.Add(Helpers.StringToScope(((object)item).ToString()));
			}
			Token = ((object)((JToken)val).SelectToken("token")).ToString();
			Refresh = ((object)((JToken)val).SelectToken("refresh")).ToString();
			Username = ((object)((JToken)val).SelectToken("username")).ToString();
			ClientId = ((object)((JToken)val).SelectToken("client_id")).ToString();
		}
	}
	public class RefreshTokenResponse
	{
		[JsonProperty(PropertyName = "token")]
		public string Token { get; protected set; }

		[JsonProperty(PropertyName = "refresh")]
		public string Refresh { get; protected set; }

		[JsonProperty(PropertyName = "client_id")]
		public string ClientId { get; protected set; }
	}
}
namespace TwitchLib.Api.Services
{
	public class ApiService
	{
		protected readonly ITwitchAPI _api;

		private readonly ServiceTimer _serviceTimer;

		public List<string> ChannelsToMonitor { get; private set; }

		public int IntervalInSeconds => _serviceTimer.IntervalInSeconds;

		public bool Enabled => _serviceTimer.Enabled;

		public event EventHandler<OnServiceStartedArgs> OnServiceStarted;

		public event EventHandler<OnServiceStoppedArgs> OnServiceStopped;

		public event EventHandler<OnServiceTickArgs> OnServiceTick;

		public event EventHandler<OnChannelsSetArgs> OnChannelsSet;

		protected ApiService(ITwitchAPI api, int checkIntervalInSeconds)
		{
			if (checkIntervalInSeconds < 1)
			{
				throw new ArgumentException("The interval must be 1 second or more.", "checkIntervalInSeconds");
			}
			_api = api ?? throw new ArgumentNullException("api");
			_serviceTimer = new ServiceTimer(OnServiceTimerTick, checkIntervalInSeconds);
		}

		public virtual void Start()
		{
			if (ChannelsToMonitor == null)
			{
				throw new InvalidOperationException("You must atleast add 1 channel to service before starting it.");
			}
			if (_serviceTimer.Enabled)
			{
				throw new InvalidOperationException("The service has already been started.");
			}
			_serviceTimer.Start();
			this.OnServiceStarted?.Invoke(this, new OnServiceStartedArgs());
		}

		public virtual void Stop()
		{
			if (!_serviceTimer.Enabled)
			{
				throw new InvalidOperationException("The service hasn't started yet, or has already been stopped.");
			}
			_serviceTimer.Stop();
			this.OnServiceStopped?.Invoke(this, new OnServiceStoppedArgs());
		}

		protected virtual void SetChannels(List<string> channelsToMonitor)
		{
			if (channelsToMonitor == null)
			{
				throw new ArgumentNullException("channelsToMonitor");
			}
			if (channelsToMonitor.Count == 0)
			{
				throw new ArgumentException("The provided list is empty.", "channelsToMonitor");
			}
			ChannelsToMonitor = channelsToMonitor;
			this.OnChannelsSet?.Invoke(this, new OnChannelsSetArgs
			{
				Channels = channelsToMonitor
			});
		}

		protected virtual Task OnServiceTimerTick()
		{
			this.OnServiceTick?.Invoke(this, new OnServiceTickArgs());
			return Task.CompletedTask;
		}
	}
	public class FollowerService : ApiService
	{
		private readonly Dictionary<string, DateTime> _lastFollowerDates = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);

		private readonly bool _invokeEventsOnStartup;

		private TwitchLib.Api.Services.Core.FollowerService.CoreMonitor _monitor;

		private TwitchLib.Api.Services.Core.FollowerService.IdBasedMonitor _idBasedMonitor;

		private TwitchLib.Api.Services.Core.FollowerService.NameBasedMonitor _nameBasedMonitor;

		public Dictionary<string, List<ChannelFollower>> KnownFollowers { get; } = new Dictionary<string, List<ChannelFollower>>(StringComparer.OrdinalIgnoreCase);


		public int QueryCountPerRequest { get; }

		public int CacheSize { get; }

		private TwitchLib.Api.Services.Core.FollowerService.IdBasedMonitor IdBasedMonitor => _idBasedMonitor ?? (_idBasedMonitor = new TwitchLib.Api.Services.Core.FollowerService.IdBasedMonitor(_api));

		private TwitchLib.Api.Services.Core.FollowerService.NameBasedMonitor NameBasedMonitor => _nameBasedMonitor ?? (_nameBasedMonitor = new TwitchLib.Api.Services.Core.FollowerService.NameBasedMonitor(_api));

		public event EventHandler<OnNewFollowersDetectedArgs> OnNewFollowersDetected;

		public FollowerService(ITwitchAPI api, int checkIntervalInSeconds = 60, int queryCountPerRequest = 100, int cacheSize = 1000, bool invokeEventsOnStartup = false)
			: base(api, checkIntervalInSeconds)
		{
			if (queryCountPerRequest < 1 || queryCountPerRequest > 100)
			{
				throw new ArgumentException("Twitch doesn't support less than 1 or more than 100 followers per request.", "queryCountPerRequest");
			}
			if (cacheSize < queryCountPerRequest)
			{
				throw new ArgumentException("The cache size must be at least the size of the queryCountPerRequest parameter.", "cacheSize");
			}
			QueryCountPerRequest = queryCountPerRequest;
			CacheSize = cacheSize;
			_invokeEventsOnStartup = invokeEventsOnStartup;
		}

		public void ClearCache()
		{
			KnownFollowers.Clear();
			_lastFollowerDates.Clear();
			_nameBasedMonitor?.ClearCache();
			_nameBasedMonitor = null;
			_idBasedMonitor = null;
		}

		public void SetChannelsById(List<string> channelsToMonitor)
		{
			SetChannels(channelsToMonitor);
			_monitor = IdBasedMonitor;
		}

		public void SetChannelsByName(List<string> channelsToMonitor)
		{
			SetChannels(channelsToMonitor);
			_monitor = NameBasedMonitor;
		}

		public async Task UpdateLatestFollowersAsync(bool callEvents = true)
		{
			if (base.ChannelsToMonitor == null)
			{
				return;
			}
			foreach (string channel in base.ChannelsToMonitor)
			{
				List<ChannelFollower> latestFollowers = await GetLatestFollowersAsync(channel);
				if (latestFollowers.Count == 0)
				{
					return;
				}
				List<ChannelFollower> newFollowers;
				if (!KnownFollowers.TryGetValue(channel, out var knownFollowers))
				{
					newFollowers = latestFollowers;
					KnownFollowers[channel] = latestFollowers.Take(CacheSize).ToList();
					_lastFollowerDates[channel] = DateTime.Parse(latestFollowers.First().FollowedAt);
					if (!_invokeEventsOnStartup)
					{
						return;
					}
				}
				else
				{
					HashSet<string> existingFollowerIds = new HashSet<string>(knownFollowers.Select((ChannelFollower f) => f.UserId));
					DateTime latestKnownFollowerDate = _lastFollowerDates[channel];
					newFollowers = new List<ChannelFollower>();
					foreach (ChannelFollower follower in latestFollowers)
					{
						if (existingFollowerIds.Add(follower.UserId))
						{
							DateTime followedAt = DateTime.Parse(follower.FollowedAt);
							if (!(followedAt < latestKnownFollowerDate))
							{
								newFollowers.Add(follower);
								latestKnownFollowerDate = followedAt;
								knownFollowers.Add(follower);
							}
						}
					}
					existingFollowerIds.Clear();
					existingFollowerIds.TrimExcess();
					if (knownFollowers.Count > CacheSize)
					{
						knownFollowers.RemoveRange(0, knownFollowers.Count - CacheSize);
					}
					if (newFollowers.Count <= 0)
					{
						return;
					}
					_lastFollowerDates[channel] = latestKnownFollowerDate;
				}
				if (!callEvents)
				{
					return;
				}
				this.OnNewFollowersDetected?.Invoke(this, new OnNewFollowersDetectedArgs
				{
					Channel = channel,
					NewFollowers = newFollowers
				});
				knownFollowers = null;
			}
		}

		protected override async Task OnServiceTimerTick()
		{
			try
			{
				await base.OnServiceTimerTick();
				await UpdateLatestFollowersAsync();
			}
			catch
			{
			}
		}

		private async Task<List<ChannelFollower>> GetLatestFollowersAsync(string channel)
		{
			return (await _monitor.GetUsersFollowsAsync(channel, QueryCountPerRequest)).Data.ToList();
		}
	}
	public class LiveStreamMonitorService : ApiService
	{
		private TwitchLib.Api.Services.Core.LiveStreamMonitor.CoreMonitor _monitor;

		private TwitchLib.Api.Services.Core.LiveStreamMonitor.IdBasedMonitor _idBasedMonitor;

		private TwitchLib.Api.Services.Core.LiveStreamMonitor.NameBasedMonitor _nameBasedMonitor;

		public Dictionary<string, Stream> LiveStreams { get; } = new Dictionary<string, Stream>(StringComparer.OrdinalIgnoreCase);


		public int MaxStreamRequestCountPerRequest { get; }

		private TwitchLib.Api.Services.Core.LiveStreamMonitor.IdBasedMonitor IdBasedMonitor => _idBasedMonitor ?? (_idBasedMonitor = new TwitchLib.Api.Services.Core.LiveStreamMonitor.IdBasedMonitor(_api));

		private TwitchLib.Api.Services.Core.LiveStreamMonitor.NameBasedMonitor NameBasedMonitor => _nameBasedMonitor ?? (_nameBasedMonitor = new TwitchLib.Api.Services.Core.LiveStreamMonitor.NameBasedMonitor(_api));

		public event EventHandler<OnStreamOnlineArgs> OnStreamOnline;

		public event EventHandler<OnStreamOfflineArgs> OnStreamOffline;

		public event EventHandler<OnStreamUpdateArgs> OnStreamUpdate;

		public LiveStreamMonitorService(ITwitchAPI api, int checkIntervalInSeconds = 60, int maxStreamRequestCountPerRequest = 100)
			: base(api, checkIntervalInSeconds)
		{
			if (maxStreamRequestCountPerRequest < 1 || maxStreamRequestCountPerRequest > 100)
			{
				throw new ArgumentException("Twitch doesn't support less than 1 or more than 100 streams per request.", "maxStreamRequestCountPerRequest");
			}
			MaxStreamRequestCountPerRequest = maxStreamRequestCountPerRequest;
		}

		public void ClearCache()
		{
			LiveStreams.Clear();
			_nameBasedMonitor?.ClearCache();
			_nameBasedMonitor = null;
			_idBasedMonitor = null;
		}

		public void SetChannelsById(List<string> channelsToMonitor)
		{
			SetChannels(channelsToMonitor);
			_monitor = IdBasedMonitor;
		}

		public void SetChannelsByName(List<string> channelsToMonitor)
		{
			SetChannels(channelsToMonitor);
			_monitor = NameBasedMonitor;
		}

		public async Task UpdateLiveStreamersAsync(bool callEvents = true)
		{
			List<Stream> result = await GetLiveStreamersAsync();
			foreach (string channel in base.ChannelsToMonitor)
			{
				IEnumerable<Stream> source = result;
				Stream liveStream = source.FirstOrDefault(await _monitor.CompareStream(channel));
				if (liveStream != null)
				{
					HandleLiveStreamUpdate(channel, liveStream, callEvents);
				}
				else
				{
					HandleOfflineStreamUpdate(channel, callEvents);
				}
			}
		}

		protected override async Task OnServiceTimerTick()
		{
			try
			{
				await base.OnServiceTimerTick();
				await UpdateLiveStreamersAsync();
			}
			catch
			{
			}
		}

		private void HandleLiveStreamUpdate(string channel, Stream liveStream, bool callEvents)
		{
			bool flag = LiveStreams.ContainsKey(channel);
			LiveStreams[channel] = liveStream;
			if (callEvents)
			{
				if (!flag)
				{
					this.OnStreamOnline?.Invoke(this, new OnStreamOnlineArgs
					{
						Channel = channel,
						Stream = liveStream
					});
				}
				else
				{
					this.OnStreamUpdate?.Invoke(this, new OnStreamUpdateArgs
					{
						Channel = channel,
						Stream = liveStream
					});
				}
			}
		}

		private void HandleOfflineStreamUpdate(string channel, bool callEvents)
		{
			if (LiveStreams.TryGetValue(channel, out var value))
			{
				LiveStreams.Remove(channel);
				if (callEvents)
				{
					this.OnStreamOffline?.Invoke(this, new OnStreamOfflineArgs
					{
						Channel = channel,
						Stream = value
					});
				}
			}
		}

		private async Task<List<Stream>> GetLiveStreamersAsync()
		{
			List<Stream> livestreamers = new List<Stream>();
			double pages = Math.Ceiling((double)base.ChannelsToMonitor.Count / (double)MaxStreamRequestCountPerRequest);
			for (int i = 0; (double)i < pages; i++)
			{
				List<string> selectedSet = base.ChannelsToMonitor.Skip(i * MaxStreamRequestCountPerRequest).Take(MaxStreamRequestCountPerRequest).ToList();
				GetStreamsResponse resultset = await _monitor.GetStreamsAsync(selectedSet);
				if (resultset.Streams != null)
				{
					livestreamers.AddRange(resultset.Streams);
				}
			}
			return livestreamers;
		}
	}
}
namespace TwitchLib.Api.Services.Events
{
	public class OnChannelsSetArgs : EventArgs
	{
		public List<string> Channels;
	}
	public class OnServiceStartedArgs : EventArgs
	{
	}
	public class OnServiceStoppedArgs : EventArgs
	{
	}
	public class OnServiceTickArgs : EventArgs
	{
	}
}
namespace TwitchLib.Api.Services.Events.LiveStreamMonitor
{
	public class OnStreamOfflineArgs : EventArgs
	{
		public string Channel;

		public Stream Stream;
	}
	public class OnStreamOnlineArgs : EventArgs
	{
		public string Channel;

		public Stream Stream;
	}
	public class OnStreamUpdateArgs : EventArgs
	{
		public string Channel;

		public Stream Stream;
	}
}
namespace TwitchLib.Api.Services.Events.FollowerService
{
	public class OnNewFollowersDetectedArgs : EventArgs
	{
		public string Channel;

		public List<ChannelFollower> NewFollowers;
	}
}
namespace TwitchLib.Api.Services.Core
{
	internal class ServiceTimer : Timer
	{
		public delegate Task ServiceTimerTick();

		private readonly ServiceTimerTick _serviceTimerTickAsyncCallback;

		public int IntervalInSeconds { get; }

		public ServiceTimer(ServiceTimerTick serviceTimerTickAsyncCallback, int intervalInSeconds = 60)
		{
			_serviceTimerTickAsyncCallback = serviceTimerTickAsyncCallback;
			base.Interval = intervalInSeconds * 1000;
			IntervalInSeconds = intervalInSeconds;
			base.Elapsed += async delegate(object sender, ElapsedEventArgs e)
			{
				await TimerElapsedAsync(sender, e);
			};
		}

		private async Task TimerElapsedAsync(object sender, ElapsedEventArgs e)
		{
			await _serviceTimerTickAsyncCallback();
		}
	}
}
namespace TwitchLib.Api.Services.Core.LiveStreamMonitor
{
	internal abstract class CoreMonitor
	{
		protected readonly ITwitchAPI _api;

		public abstract Task<GetStreamsResponse> GetStreamsAsync(List<string> channels, string accessToken = null);

		public abstract Task<Func<Stream, bool>> CompareStream(string channel, string accessToken = null);

		protected CoreMonitor(ITwitchAPI api)
		{
			_api = api;
		}
	}
	internal class IdBasedMonitor : CoreMonitor
	{
		public IdBasedMonitor(ITwitchAPI api)
			: base(api)
		{
		}

		public override Task<Func<Stream, bool>> CompareStream(string channel, string accessToken = null)
		{
			return Task.FromResult<Func<Stream, bool>>((Stream stream) => stream.UserId == channel);
		}

		public override Task<GetStreamsResponse> GetStreamsAsync(List<string> channels, string accessToken = null)
		{
			return _api.Helix.Streams.GetStreamsAsync((string)null, channels.Count, (List<string>)null, (List<string>)null, channels, (List<string>)null, accessToken, (string)null);
		}
	}
	internal class NameBasedMonitor : CoreMonitor
	{
		private readonly ConcurrentDictionary<string, string> _channelToId = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		public NameBasedMonitor(ITwitchAPI api)
			: base(api)
		{
		}

		public override async Task<Func<Stream, bool>> CompareStream(string channel, string accessToken = null)
		{
			if (!_channelToId.TryGetValue(channel, out var channelId))
			{
				User? obj = (await _api.Helix.Users.GetUsersAsync((List<string>)null, new List<string> { channel }, accessToken)).Users.FirstOrDefault();
				channelId = ((obj != null) ? obj.Id : null);
				_channelToId[channel] = channelId ?? throw new InvalidOperationException("No channel with the name \"" + channel + "\" could be found.");
			}
			return (Stream stream) => stream.UserId == channelId;
		}

		public override Task<GetStreamsResponse> GetStreamsAsync(List<string> channels, string accessToken = null)
		{
			return _api.Helix.Streams.GetStreamsAsync((string)null, channels.Count, (List<string>)null, (List<string>)null, (List<string>)null, channels, accessToken, (string)null);
		}

		public void ClearCache()
		{
			_channelToId.Clear();
		}
	}
}
namespace TwitchLib.Api.Services.Core.FollowerService
{
	internal abstract class CoreMonitor
	{
		protected readonly ITwitchAPI _api;

		public abstract Task<GetChannelFollowersResponse> GetUsersFollowsAsync(string channel, int queryCount);

		protected CoreMonitor(ITwitchAPI api)
		{
			_api = api;
		}
	}
	internal class IdBasedMonitor : CoreMonitor
	{
		public IdBasedMonitor(ITwitchAPI api)
			: base(api)
		{
		}

		public override Task<GetChannelFollowersResponse> GetUsersFollowsAsync(string channel, int queryCount)
		{
			return _api.Helix.Channels.GetChannelFollowersAsync(channel, (string)null, queryCount, (string)null, (string)null);
		}
	}
	internal class NameBasedMonitor : CoreMonitor
	{
		private readonly ConcurrentDictionary<string, string> _channelToId = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		public NameBasedMonitor(ITwitchAPI api)
			: base(api)
		{
		}

		public override async Task<GetChannelFollowersResponse> GetUsersFollowsAsync(string channel, int queryCount)
		{
			if (!_channelToId.TryGetValue(channel, out var channelId))
			{
				User? obj = (await _api.Helix.Users.GetUsersAsync((List<string>)null, new List<string> { channel }, (string)null)).Users.FirstOrDefault();
				channelId = ((obj != null) ? obj.Id : null);
				_channelToId[channel] = channelId ?? throw new InvalidOperationException("No channel with the name \"" + channel + "\" could be found.");
			}
			return await _api.Helix.Channels.GetChannelFollowersAsync(channelId, (string)null, queryCount, (string)null, (string)null);
		}

		public void ClearCache()
		{
			_channelToId.Clear();
		}
	}
}
namespace TwitchLib.Api.Interfaces
{
	public interface ITwitchAPI
	{
		IApiSettings Settings { get; }

		TwitchLib.Api.Auth.Auth Auth { get; }

		Helix Helix { get; }

		TwitchLib.Api.ThirdParty.ThirdParty ThirdParty { get; }

		Undocumented Undocumented { get; }
	}
}
namespace TwitchLib.Api.Helpers
{
	public static class ExtensionAnalyticsHelper
	{
		public static async Task<List<ExtensionAnalytics>> HandleUrlAsync(string url)
		{
			IEnumerable<string> data = ExtractData(await GetContentsAsync(url));
			return data.Select((Func<string, ExtensionAnalytics>)((string line) => new ExtensionAnalytics(line))).ToList();
		}

		private static IEnumerable<string> ExtractData(IEnumerable<string> cnts)
		{
			return cnts.Where((string line) => line.Any(char.IsDigit)).ToList();
		}

		private static async Task<string[]> GetContentsAsync(string url)
		{
			HttpClient client = new HttpClient();
			return (await client.GetStringAsync(url)).Split(new string[1] { Environment.NewLine }, StringSplitOptions.None);
		}
	}
}
namespace TwitchLib.Api.Events
{
	public class OnAuthorizationFlowErrorArgs
	{
		public int Error { get; set; }

		public string Message { get; set; }
	}
	public class OnUserAuthorizationDetectedArgs
	{
		public string Id { get; set; }

		public List<AuthScopes> Scopes { get; set; }

		public string Username { get; set; }

		public string Token { get; set; }

		public string Refresh { get; set; }

		public string ClientId { get; set; }
	}
}
namespace TwitchLib.Api.Auth
{
	public class Auth : ApiBase
	{
		public Auth(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<RefreshResponse> RefreshAuthTokenAsync(string refreshToken, string clientSecret, string clientId = null)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			string text = clientId ?? base.Settings.ClientId;
			if (string.IsNullOrWhiteSpace(refreshToken))
			{
				throw new BadParameterException("The refresh token is not valid. It is not allowed to be null, empty or filled with whitespaces.");
			}
			if (string.IsNullOrWhiteSpace(clientSecret))
			{
				throw new BadParameterException("The client secret is not valid. It is not allowed to be null, empty or filled with whitespaces.");
			}
			if (string.IsNullOrWhiteSpace(text))
			{
				throw new BadParameterException("The clientId is not valid. It is not allowed to be null, empty or filled with whitespaces.");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("grant_type", "refresh_token"),
				new KeyValuePair<string, string>("refresh_token", refreshToken),
				new KeyValuePair<string, string>("client_id", text),
				new KeyValuePair<string, string>("client_secret", clientSecret)
			};
			return ((ApiBase)this).TwitchPostGenericAsync<RefreshResponse>("/token", (ApiVersion)1, (string)null, list, (string)null, text, (string)null);
		}

		public string GetAuthorizationCodeUrl(string redirectUri, IEnumerable<AuthScopes> scopes, bool forceVerify = false, string state = null, string clientId = null)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			string text = clientId ?? base.Settings.ClientId;
			string text2 = null;
			foreach (AuthScopes scope in scopes)
			{
				text2 = ((text2 != null) ? (text2 + "+" + Helpers.AuthScopesToString(scope)) : Helpers.AuthScopesToString(scope));
			}
			if (string.IsNullOrWhiteSpace(text))
			{
				throw new BadParameterException("The clientId is not valid. It is not allowed to be null, empty or filled with whitespaces.");
			}
			return "https://id.twitch.tv/oauth2/authorize?client_id=" + text + "&redirect_uri=" + HttpUtility.UrlEncode(redirectUri) + "&response_type=code&scope=" + text2 + "&state=" + state + "&force_verify=" + forceVerify.ToString().ToLower();
		}

		public Task<AuthCodeResponse> GetAccessTokenFromCodeAsync(string code, string clientSecret, string redirectUri, string clientId = null)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			string text = clientId ?? base.Settings.ClientId;
			if (string.IsNullOrWhiteSpace(code))
			{
				throw new BadParameterException("The code is not valid. It is not allowed to be null, empty or filled with whitespaces.");
			}
			if (string.IsNullOrWhiteSpace(clientSecret))
			{
				throw new BadParameterException("The client secret is not valid. It is not allowed to be null, empty or filled with whitespaces.");
			}
			if (string.IsNullOrWhiteSpace(redirectUri))
			{
				throw new BadParameterException("The redirectUri is not valid. It is not allowed to be null, empty or filled with whitespaces.");
			}
			if (string.IsNullOrWhiteSpace(text))
			{
				throw new BadParameterException("The clientId is not valid. It is not allowed to be null, empty or filled with whitespaces.");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("grant_type", "authorization_code"),
				new KeyValuePair<string, string>("code", code),
				new KeyValuePair<string, string>("client_id", text),
				new KeyValuePair<string, string>("client_secret", clientSecret),
				new KeyValuePair<string, string>("redirect_uri", redirectUri)
			};
			return ((ApiBase)this).TwitchPostGenericAsync<AuthCodeResponse>("/token", (ApiVersion)1, (string)null, list, (string)null, text, (string)null);
		}

		public async Task<ValidateAccessTokenResponse> ValidateAccessTokenAsync(string accessToken = null)
		{
			try
			{
				return await ((ApiBase)this).TwitchGetGenericAsync<ValidateAccessTokenResponse>("/validate", (ApiVersion)1, (List<KeyValuePair<string, string>>)null, accessToken, (string)null, (string)null);
			}
			catch (BadScopeException)
			{
				return null;
			}
		}
	}
	public class AuthCodeResponse
	{
		[JsonProperty(PropertyName = "access_token")]
		public string AccessToken { get; protected set; }

		[JsonProperty(PropertyName = "refresh_token")]
		public string RefreshToken { get; protected set; }

		[JsonProperty(PropertyName = "expires_in")]
		public int ExpiresIn { get; protected set; }

		[JsonProperty(PropertyName = "scope")]
		public string[] Scopes { get; protected set; }

		[JsonProperty(PropertyName = "token_type")]
		public string TokenType { get; set; }
	}
	public class RefreshResponse
	{
		[JsonProperty(PropertyName = "access_token")]
		public string AccessToken { get; protected set; }

		[JsonProperty(PropertyName = "refresh_token")]
		public string RefreshToken { get; protected set; }

		[JsonProperty(PropertyName = "expires_in")]
		public int ExpiresIn { get; protected set; }

		[JsonProperty(PropertyName = "scope")]
		public string[] Scopes { get; protected set; }
	}
	public class ValidateAccessTokenResponse
	{
		[JsonProperty(PropertyName = "client_id")]
		public string ClientId { get; protected set; }

		[JsonProperty(PropertyName = "login")]
		public string Login { get; protected set; }

		[JsonProperty(PropertyName = "scopes")]
		public List<string> Scopes { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "expires_in")]
		public int ExpiresIn { get; protected set; }
	}
}

TwitchLib.Api.Helix.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using System.Web;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TwitchLib.Api.Core;
using TwitchLib.Api.Core.Enums;
using TwitchLib.Api.Core.Exceptions;
using TwitchLib.Api.Core.Extensions.System;
using TwitchLib.Api.Core.HttpCallHandlers;
using TwitchLib.Api.Core.Interfaces;
using TwitchLib.Api.Core.RateLimiter;
using TwitchLib.Api.Helix.Models.Analytics;
using TwitchLib.Api.Helix.Models.Bits;
using TwitchLib.Api.Helix.Models.Bits.ExtensionBitsProducts;
using TwitchLib.Api.Helix.Models.ChannelPoints.CreateCustomReward;
using TwitchLib.Api.Helix.Models.ChannelPoints.GetCustomReward;
using TwitchLib.Api.Helix.Models.ChannelPoints.GetCustomRewardRedemption;
using TwitchLib.Api.Helix.Models.ChannelPoints.UpdateCustomReward;
using TwitchLib.Api.Helix.Models.ChannelPoints.UpdateCustomRewardRedemptionStatus;
using TwitchLib.Api.Helix.Models.ChannelPoints.UpdateRedemptionStatus;
using TwitchLib.Api.Helix.Models.Channels.GetAdSchedule;
using TwitchLib.Api.Helix.Models.Channels.GetChannelEditors;
using TwitchLib.Api.Helix.Models.Channels.GetChannelFollowers;
using TwitchLib.Api.Helix.Models.Channels.GetChannelInformation;
using TwitchLib.Api.Helix.Models.Channels.GetChannelVIPs;
using TwitchLib.Api.Helix.Models.Channels.GetFollowedChannels;
using TwitchLib.Api.Helix.Models.Channels.ModifyChannelInformation;
using TwitchLib.Api.Helix.Models.Channels.SendChatMessage;
using TwitchLib.Api.Helix.Models.Channels.SnoozeNextAd;
using TwitchLib.Api.Helix.Models.Channels.StartCommercial;
using TwitchLib.Api.Helix.Models.Charity.GetCharityCampaign;
using TwitchLib.Api.Helix.Models.Charity.GetCharityCampaignDonations;
using TwitchLib.Api.Helix.Models.Chat;
using TwitchLib.Api.Helix.Models.Chat.Badges.GetChannelChatBadges;
using TwitchLib.Api.Helix.Models.Chat.Badges.GetGlobalChatBadges;
using TwitchLib.Api.Helix.Models.Chat.ChatSettings;
using TwitchLib.Api.Helix.Models.Chat.Emotes.GetChannelEmotes;
using TwitchLib.Api.Helix.Models.Chat.Emotes.GetEmoteSets;
using TwitchLib.Api.Helix.Models.Chat.Emotes.GetGlobalEmotes;
using TwitchLib.Api.Helix.Models.Chat.Emotes.GetUserEmotes;
using TwitchLib.Api.Helix.Models.Chat.GetChatters;
using TwitchLib.Api.Helix.Models.Chat.GetUserChatColor;
using TwitchLib.Api.Helix.Models.Clips.CreateClip;
using TwitchLib.Api.Helix.Models.Clips.GetClips;
using TwitchLib.Api.Helix.Models.ContentClassificationLabels;
using TwitchLib.Api.Helix.Models.Entitlements.GetDropsEntitlements;
using TwitchLib.Api.Helix.Models.Entitlements.UpdateDropsEntitlements;
using TwitchLib.Api.Helix.Models.EventSub;
using TwitchLib.Api.Helix.Models.EventSub.Conduits.CreateConduits;
using TwitchLib.Api.Helix.Models.EventSub.Conduits.GetConduits;
using TwitchLib.Api.Helix.Models.EventSub.Conduits.Shards.GetConduitShards;
using TwitchLib.Api.Helix.Models.EventSub.Conduits.Shards.UpdateConduitShards;
using TwitchLib.Api.Helix.Models.EventSub.Conduits.UpdateConduits;
using TwitchLib.Api.Helix.Models.Extensions.LiveChannels;
using TwitchLib.Api.Helix.Models.Extensions.ReleasedExtensions;
using TwitchLib.Api.Helix.Models.Extensions.Transactions;
using TwitchLib.Api.Helix.Models.Games;
using TwitchLib.Api.Helix.Models.Goals;
using TwitchLib.Api.Helix.Models.GuestStar.CreateGuestStarSession;
using TwitchLib.Api.Helix.Models.GuestStar.GetChannelGuestStarSettings;
using TwitchLib.Api.Helix.Models.GuestStar.GetGuestStarInvites;
using TwitchLib.Api.Helix.Models.GuestStar.GetGuestStarSession;
using TwitchLib.Api.Helix.Models.GuestStar.UpdateChannelGuestStarSettings;
using TwitchLib.Api.Helix.Models.HypeTrain;
using TwitchLib.Api.Helix.Models.Moderation.AutomodSettings;
using TwitchLib.Api.Helix.Models.Moderation.BanUser;
using TwitchLib.Api.Helix.Models.Moderation.BlockedTerms;
using TwitchLib.Api.Helix.Models.Moderation.CheckAutoModStatus;
using TwitchLib.Api.Helix.Models.Moderation.CheckAutoModStatus.Request;
using TwitchLib.Api.Helix.Models.Moderation.GetBannedEvents;
using TwitchLib.Api.Helix.Models.Moderation.GetBannedUsers;
using TwitchLib.Api.Helix.Models.Moderation.GetModeratedChannels;
using TwitchLib.Api.Helix.Models.Moderation.GetModeratorEvents;
using TwitchLib.Api.Helix.Models.Moderation.GetModerators;
using TwitchLib.Api.Helix.Models.Moderation.ShieldModeStatus;
using TwitchLib.Api.Helix.Models.Moderation.ShieldModeStatus.GetShieldModeStatus;
using TwitchLib.Api.Helix.Models.Moderation.ShieldModeStatus.UpdateShieldModeStatus;
using TwitchLib.Api.Helix.Models.Moderation.UnbanRequests.GetUnbanRequests;
using TwitchLib.Api.Helix.Models.Moderation.UnbanRequests.ResolveUnbanRequests;
using TwitchLib.Api.Helix.Models.Moderation.WarnChatUser;
using TwitchLib.Api.Helix.Models.Moderation.WarnChatUser.Request;
using TwitchLib.Api.Helix.Models.Polls.CreatePoll;
using TwitchLib.Api.Helix.Models.Polls.EndPoll;
using TwitchLib.Api.Helix.Models.Polls.GetPolls;
using TwitchLib.Api.Helix.Models.Predictions.CreatePrediction;
using TwitchLib.Api.Helix.Models.Predictions.EndPrediction;
using TwitchLib.Api.Helix.Models.Predictions.GetPredictions;
using TwitchLib.Api.Helix.Models.Raids.StartRaid;
using TwitchLib.Api.Helix.Models.Schedule.CreateChannelStreamSegment;
using TwitchLib.Api.Helix.Models.Schedule.GetChannelStreamSchedule;
using TwitchLib.Api.Helix.Models.Schedule.UpdateChannelStreamSegment;
using TwitchLib.Api.Helix.Models.Search;
using TwitchLib.Api.Helix.Models.Streams.CreateStreamMarker;
using TwitchLib.Api.Helix.Models.Streams.GetFollowedStreams;
using TwitchLib.Api.Helix.Models.Streams.GetStreamKey;
using TwitchLib.Api.Helix.Models.Streams.GetStreamMarkers;
using TwitchLib.Api.Helix.Models.Streams.GetStreamTags;
using TwitchLib.Api.Helix.Models.Streams.GetStreams;
using TwitchLib.Api.Helix.Models.Subscriptions;
using TwitchLib.Api.Helix.Models.Tags;
using TwitchLib.Api.Helix.Models.Teams;
using TwitchLib.Api.Helix.Models.Users.GetUserActiveExtensions;
using TwitchLib.Api.Helix.Models.Users.GetUserBlockList;
using TwitchLib.Api.Helix.Models.Users.GetUserExtensions;
using TwitchLib.Api.Helix.Models.Users.GetUserFollows;
using TwitchLib.Api.Helix.Models.Users.GetUsers;
using TwitchLib.Api.Helix.Models.Users.Internal;
using TwitchLib.Api.Helix.Models.Users.UpdateUserExtensions;
using TwitchLib.Api.Helix.Models.Videos.DeleteVideos;
using TwitchLib.Api.Helix.Models.Videos.GetVideos;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2022")]
[assembly: AssemblyDescription("Project containing the Helix section of TwitchLib.Api")]
[assembly: AssemblyFileVersion("3.10.0")]
[assembly: AssemblyInformationalVersion("3.10.0+92a4359ed145876af4e8e108e267004dcb0babab")]
[assembly: AssemblyProduct("TwitchLib.Api.Helix")]
[assembly: AssemblyTitle("TwitchLib.Api.Helix")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/swiftyspiffy/TwitchLib")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("3.10.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 TwitchLib.Api.Helix
{
	public class Analytics : ApiBase
	{
		public Analytics(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetGameAnalyticsResponse> GetGameAnalyticsAsync(string gameId = null, DateTime? startedAt = null, DateTime? endedAt = null, int first = 20, string after = null, string type = null, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (!string.IsNullOrWhiteSpace(gameId))
			{
				list.Add(new KeyValuePair<string, string>("game_id", gameId));
			}
			if (startedAt.HasValue && endedAt.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("started_at", DateTimeExtensions.ToRfc3339String(startedAt.Value)));
				list.Add(new KeyValuePair<string, string>("ended_at", DateTimeExtensions.ToRfc3339String(endedAt.Value)));
			}
			if (!string.IsNullOrWhiteSpace(type))
			{
				list.Add(new KeyValuePair<string, string>("type", type));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetGameAnalyticsResponse>("/analytics/games", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetExtensionAnalyticsResponse> GetExtensionAnalyticsAsync(string extensionId, DateTime? startedAt = null, DateTime? endedAt = null, int first = 20, string after = null, string type = null, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (!string.IsNullOrWhiteSpace(extensionId))
			{
				list.Add(new KeyValuePair<string, string>("extension_id", extensionId));
			}
			if (startedAt.HasValue && endedAt.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("started_at", DateTimeExtensions.ToRfc3339String(startedAt.Value)));
				list.Add(new KeyValuePair<string, string>("ended_at", DateTimeExtensions.ToRfc3339String(endedAt.Value)));
			}
			if (!string.IsNullOrWhiteSpace(type))
			{
				list.Add(new KeyValuePair<string, string>("type", type));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetExtensionAnalyticsResponse>("/analytics/extensions", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}
	}
	public class Bits : ApiBase
	{
		public Bits(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetCheermotesResponse> GetCheermotesAsync(string broadcasterId = null, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			if (!string.IsNullOrWhiteSpace(broadcasterId))
			{
				list.Add(new KeyValuePair<string, string>("broadcaster_id", broadcasterId));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetCheermotesResponse>("/bits/cheermotes", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetBitsLeaderboardResponse> GetBitsLeaderboardAsync(int count = 10, BitsLeaderboardPeriodEnum period = 4, DateTime? startedAt = null, string userid = null, string accessToken = null)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected I4, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("count", count.ToString())
			};
			switch ((int)period)
			{
			case 0:
				list.Add(new KeyValuePair<string, string>("period", "day"));
				break;
			case 1:
				list.Add(new KeyValuePair<string, string>("period", "week"));
				break;
			case 2:
				list.Add(new KeyValuePair<string, string>("period", "month"));
				break;
			case 3:
				list.Add(new KeyValuePair<string, string>("period", "year"));
				break;
			case 4:
				list.Add(new KeyValuePair<string, string>("period", "all"));
				break;
			default:
				throw new ArgumentOutOfRangeException("period", period, null);
			}
			if (startedAt.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("started_at", DateTimeExtensions.ToRfc3339String(startedAt.Value)));
			}
			if (!string.IsNullOrWhiteSpace(userid))
			{
				list.Add(new KeyValuePair<string, string>("user_id", userid));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetBitsLeaderboardResponse>("/bits/leaderboard", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetExtensionBitsProductsResponse> GetExtensionBitsProductsAsync(bool shouldIncludeAll = false, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("should_include_all", shouldIncludeAll.ToString().ToLower())
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetExtensionBitsProductsResponse>("/bits/extensions", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<UpdateExtensionBitsProductResponse> UpdateExtensionBitsProductAsync(ExtensionBitsProduct extensionBitsProduct, string accessToken = null)
		{
			return ((ApiBase)this).TwitchPutGenericAsync<UpdateExtensionBitsProductResponse>("/bits/extensions", (ApiVersion)6, ((object)extensionBitsProduct).ToString(), (List<KeyValuePair<string, string>>)null, accessToken, (string)null, (string)null);
		}
	}
	public class ChannelPoints : ApiBase
	{
		public ChannelPoints(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<CreateCustomRewardsResponse> CreateCustomRewardsAsync(string broadcasterId, CreateCustomRewardsRequest request, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchPostGenericAsync<CreateCustomRewardsResponse>("/channel_points/custom_rewards", (ApiVersion)6, JsonConvert.SerializeObject((object)request), list, accessToken, (string)null, (string)null);
		}

		public Task DeleteCustomRewardAsync(string broadcasterId, string rewardId, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("id", rewardId)
			};
			return ((ApiBase)this).TwitchDeleteAsync("/channel_points/custom_rewards", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetCustomRewardsResponse> GetCustomRewardAsync(string broadcasterId, List<string> rewardIds = null, bool onlyManageableRewards = false, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("only_manageable_rewards", onlyManageableRewards.ToString().ToLower())
			};
			if (rewardIds != null && rewardIds.Count > 0)
			{
				list.AddRange(rewardIds.Select((string rewardId) => new KeyValuePair<string, string>("id", rewardId)));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetCustomRewardsResponse>("/channel_points/custom_rewards", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<UpdateCustomRewardResponse> UpdateCustomRewardAsync(string broadcasterId, string rewardId, UpdateCustomRewardRequest request, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("id", rewardId)
			};
			return ((ApiBase)this).TwitchPatchGenericAsync<UpdateCustomRewardResponse>("/channel_points/custom_rewards", (ApiVersion)6, JsonConvert.SerializeObject((object)request), list, accessToken, (string)null, (string)null);
		}

		public Task<GetCustomRewardRedemptionResponse> GetCustomRewardRedemptionAsync(string broadcasterId, string rewardId, List<string> redemptionIds = null, string status = null, string sort = null, string after = null, string first = null, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("reward_id", rewardId)
			};
			if (redemptionIds != null && redemptionIds.Count > 0)
			{
				list.AddRange(redemptionIds.Select((string redemptionId) => new KeyValuePair<string, string>("id", redemptionId)));
			}
			if (!string.IsNullOrWhiteSpace(status))
			{
				list.Add(new KeyValuePair<string, string>("status", status));
			}
			if (!string.IsNullOrWhiteSpace(sort))
			{
				list.Add(new KeyValuePair<string, string>("sort", sort));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			if (!string.IsNullOrWhiteSpace(first))
			{
				list.Add(new KeyValuePair<string, string>("first", first));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetCustomRewardRedemptionResponse>("/channel_points/custom_rewards/redemptions", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<UpdateRedemptionStatusResponse> UpdateRedemptionStatusAsync(string broadcasterId, string rewardId, List<string> redemptionIds, UpdateCustomRewardRedemptionStatusRequest request, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("reward_id", rewardId)
			};
			list.AddRange(redemptionIds.Select((string redemptionId) => new KeyValuePair<string, string>("id", redemptionId)));
			return ((ApiBase)this).TwitchPatchGenericAsync<UpdateRedemptionStatusResponse>("/channel_points/custom_rewards/redemptions", (ApiVersion)6, JsonConvert.SerializeObject((object)request), list, accessToken, (string)null, (string)null);
		}
	}
	public class Channels : ApiBase
	{
		public Channels(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetChannelInformationResponse> GetChannelInformationAsync(string broadcasterId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetChannelInformationResponse>("/channels", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public async Task<bool> ModifyChannelInformationAsync(string broadcasterId, ModifyChannelInformationRequest request, string accessToken = null)
		{
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			List<KeyValuePair<string, string>> getParams = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return (await ((ApiBase)this).TwitchPatchAsync("/channels", (ApiVersion)6, JsonConvert.SerializeObject((object)request), getParams, accessToken, (string)null, (string)null)).Key == 204;
		}

		public Task<GetChannelEditorsResponse> GetChannelEditorsAsync(string broadcasterId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetChannelEditorsResponse>("/channels/editors", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetChannelVIPsResponse> GetVIPsAsync(string broadcasterId, List<string> userIds = null, int first = 20, string after = null, string accessToken = null)
		{
			//IL_0010: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (first > 100 && first <= 0)
			{
				throw new BadParameterException("first must be greater than 0 and less then 101");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (userIds != null)
			{
				if (userIds.Count == 0)
				{
					throw new BadParameterException("userIds must contain at least 1 userId if a list is included in the call");
				}
				list.AddRange(userIds.Select((string userId) => new KeyValuePair<string, string>("userId", userId)));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetChannelVIPsResponse>("/channels/vips", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task AddChannelVIPAsync(string broadcasterId, string userId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrEmpty(userId))
			{
				throw new BadParameterException("userId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("user_id", userId)
			};
			return ((ApiBase)this).TwitchPostAsync("/channels/vips", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}

		public Task RemoveChannelVIPAsync(string broadcasterId, string userId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrEmpty(userId))
			{
				throw new BadParameterException("userId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("user_id", userId)
			};
			return ((ApiBase)this).TwitchDeleteAsync("/channels/vips", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetFollowedChannelsResponse> GetFollowedChannelsAsync(string userId, string broadcasterId = null, int first = 20, string after = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(userId))
			{
				throw new BadParameterException("userId must be set");
			}
			if (first < 1 || first > 100)
			{
				throw new BadParameterException("first cannot be less than 1 or greater than 100");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("user_id", userId)
			};
			if (!string.IsNullOrWhiteSpace(broadcasterId))
			{
				list.Add(new KeyValuePair<string, string>("broadcaster_id", broadcasterId));
			}
			if (first != 20)
			{
				list.Add(new KeyValuePair<string, string>("first", first.ToString()));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetFollowedChannelsResponse>("/channels/followed", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetChannelFollowersResponse> GetChannelFollowersAsync(string broadcasterId, string userId = null, int first = 20, string after = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (first < 1 || first > 100)
			{
				throw new BadParameterException("first cannot be less than 1 or greater than 100");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			if (!string.IsNullOrWhiteSpace(userId))
			{
				list.Add(new KeyValuePair<string, string>("user_id", userId));
			}
			if (first != 20)
			{
				list.Add(new KeyValuePair<string, string>("first", first.ToString()));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetChannelFollowersResponse>("/channels/followers", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetAdScheduleResponse> GetAdScheduleAsync(string broadcasterId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetAdScheduleResponse>("/channels/ads", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<SnoozeNextAdResponse> SnoozeNextAdAsync(string broadcasterId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchPostGenericAsync<SnoozeNextAdResponse>("/channels/ads/schedule/snooze", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}

		public Task<StartCommercialResponse> StartCommercialAsync(StartCommercialRequest request, string accessToken = null)
		{
			return ((ApiBase)this).TwitchPostGenericAsync<StartCommercialResponse>("/channels/commercial", (ApiVersion)6, JsonConvert.SerializeObject((object)request), (List<KeyValuePair<string, string>>)null, accessToken, (string)null, (string)null);
		}
	}
	public class Charity : ApiBase
	{
		public Charity(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetCharityCampaignResponse> GetCharityCampaignAsync(string broadcasterId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetCharityCampaignResponse>("/charity/campaigns", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetCharityCampaignDonationsResponse> GetCharityCampaignDonationsAsync(string broadcasterId, int first = 20, string after = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (first < 1 || first > 100)
			{
				throw new BadParameterException("first cannot be less than 1 or greater than 100");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetCharityCampaignDonationsResponse>("/charity/donations", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}
	}
	public class Chat : ApiBase
	{
		public Chat(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetChannelChatBadgesResponse> GetChannelChatBadgesAsync(string broadcasterId, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetChannelChatBadgesResponse>("/chat/badges", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetGlobalChatBadgesResponse> GetGlobalChatBadgesAsync(string accessToken = null)
		{
			return ((ApiBase)this).TwitchGetGenericAsync<GetGlobalChatBadgesResponse>("/chat/badges/global", (ApiVersion)6, (List<KeyValuePair<string, string>>)null, accessToken, (string)null, (string)null);
		}

		public Task<GetChattersResponse> GetChattersAsync(string broadcasterId, string moderatorId, int first = 100, string after = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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 (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId cannot be null/empty/whitespace");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId cannot be null/empty/whitespace");
			}
			if (first < 1 || first > 1000)
			{
				throw new BadParameterException("first cannot be less than 1 or greater than 1000");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetChattersResponse>("/chat/chatters", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetChannelEmotesResponse> GetChannelEmotesAsync(string broadcasterId, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetChannelEmotesResponse>("/chat/emotes", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetEmoteSetsResponse> GetEmoteSetsAsync(List<string> emoteSetIds, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			list.AddRange(emoteSetIds.Select((string emoteSetId) => new KeyValuePair<string, string>("emote_set_id", emoteSetId)));
			return ((ApiBase)this).TwitchGetGenericAsync<GetEmoteSetsResponse>("/chat/emotes/set", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetGlobalEmotesResponse> GetGlobalEmotesAsync(string accessToken = null)
		{
			return ((ApiBase)this).TwitchGetGenericAsync<GetGlobalEmotesResponse>("/chat/emotes/global", (ApiVersion)6, (List<KeyValuePair<string, string>>)null, accessToken, (string)null, (string)null);
		}

		public Task<GetUserEmotesResponse> GetUserEmotesAsync(string userId, string after = null, string broadcasterId = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(userId))
			{
				throw new BadParameterException("userId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("user_id", userId)
			};
			if (!string.IsNullOrEmpty(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			if (!string.IsNullOrEmpty(broadcasterId))
			{
				list.Add(new KeyValuePair<string, string>("broadcaster_id", broadcasterId));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetUserEmotesResponse>("/chat/emotes/user", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetChatSettingsResponse> GetChatSettingsAsync(string broadcasterId, string moderatorId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrEmpty(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetChatSettingsResponse>("/chat/settings", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<UpdateChatSettingsResponse> UpdateChatSettingsAsync(string broadcasterId, string moderatorId, ChatSettings settings, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrEmpty(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (settings == null)
			{
				throw new BadParameterException("settings must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId)
			};
			return ((ApiBase)this).TwitchPatchGenericAsync<UpdateChatSettingsResponse>("/chat/settings", (ApiVersion)6, JsonConvert.SerializeObject((object)settings), list, accessToken, (string)null, (string)null);
		}

		public Task SendChatAnnouncementAsync(string broadcasterId, string moderatorId, string message, AnnouncementColors color = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrEmpty(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (message == null)
			{
				throw new BadParameterException("message must be set");
			}
			if (message.Length > 500)
			{
				throw new BadParameterException("message length must be less than or equal to 500 characters");
			}
			if (color == null)
			{
				color = AnnouncementColors.Primary;
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId)
			};
			JObject val = new JObject
			{
				["message"] = JToken.op_Implicit(message),
				["color"] = JToken.op_Implicit(color.Value)
			};
			return ((ApiBase)this).TwitchPostAsync("/chat/announcements", (ApiVersion)6, ((object)val).ToString(), list, accessToken, (string)null, (string)null);
		}

		public Task SendShoutoutAsync(string fromBroadcasterId, string toBroadcasterId, string moderatorId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(fromBroadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrEmpty(toBroadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrEmpty(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("from_broadcaster_id", fromBroadcasterId),
				new KeyValuePair<string, string>("to_broadcaster_id", toBroadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId)
			};
			return ((ApiBase)this).TwitchPostAsync("/chat/shoutouts", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}

		public Task<SendChatMessageResponse> SendChatMessage(string broadcasterId, string senderId, string message, string replyParentMessageId = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrEmpty(senderId))
			{
				throw new BadParameterException("senderId must be set");
			}
			if (string.IsNullOrEmpty(message))
			{
				throw new BadParameterException("message must be set");
			}
			JObject val = new JObject
			{
				["broadcaster_id"] = JToken.op_Implicit(broadcasterId),
				["sender_id"] = JToken.op_Implicit(senderId),
				["message"] = JToken.op_Implicit(message)
			};
			if (replyParentMessageId != null)
			{
				val.Add("reply_parent_message_id", JToken.op_Implicit(replyParentMessageId));
			}
			return ((ApiBase)this).TwitchPostGenericAsync<SendChatMessageResponse>("/chat/messages", (ApiVersion)6, ((object)val).ToString(), (List<KeyValuePair<string, string>>)null, accessToken, (string)null, (string)null);
		}

		public Task UpdateUserChatColorAsync(string userId, UserColors color, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(userId))
			{
				throw new BadParameterException("userId must be set");
			}
			if (string.IsNullOrEmpty(color.Value))
			{
				throw new BadParameterException("color must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("user_id", userId),
				new KeyValuePair<string, string>("color", color.Value)
			};
			return ((ApiBase)this).TwitchPutAsync("/chat/color", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}

		public Task UpdateUserChatColorAsync(string userId, string colorHex, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			if (string.IsNullOrEmpty(userId))
			{
				throw new BadParameterException("userId must be set");
			}
			if (string.IsNullOrEmpty(colorHex))
			{
				throw new BadParameterException("colorHex must be set");
			}
			if (colorHex.Length != 6)
			{
				throw new BadParameterException("colorHex length must be equal to 6 characters \"######\"");
			}
			string value = HttpUtility.UrlEncode("#" + colorHex);
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("user_id", userId),
				new KeyValuePair<string, string>("color", value)
			};
			return ((ApiBase)this).TwitchPutAsync("/chat/color", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}

		public Task<GetUserChatColorResponse> GetUserChatColorAsync(List<string> userIds, string accessToken = null)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (userIds.Count == 0)
			{
				throw new BadParameterException("userIds must contain at least 1 userId");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			foreach (string userId in userIds)
			{
				if (string.IsNullOrEmpty(userId))
				{
					throw new BadParameterException("userId must be set");
				}
				list.Add(new KeyValuePair<string, string>("user_id", userId));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetUserChatColorResponse>("/chat/color", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}
	}
	public class Clips : ApiBase
	{
		public Clips(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetClipsResponse> GetClipsAsync(List<string> clipIds = null, string gameId = null, string broadcasterId = null, string before = null, string after = null, DateTime? startedAt = null, DateTime? endedAt = null, bool? isFeatured = null, int first = 20, string accessToken = null)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			if (first < 0 || first > 100)
			{
				throw new BadParameterException("'first' must between 0 (inclusive) and 100 (inclusive).");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			if (clipIds != null)
			{
				list.AddRange(clipIds.Select((string clipId) => new KeyValuePair<string, string>("id", clipId)));
			}
			if (!string.IsNullOrWhiteSpace(gameId))
			{
				list.Add(new KeyValuePair<string, string>("game_id", gameId));
			}
			if (!string.IsNullOrWhiteSpace(broadcasterId))
			{
				list.Add(new KeyValuePair<string, string>("broadcaster_id", broadcasterId));
			}
			if (list.Count == 0 || (list.Count > 1 && gameId != null && broadcasterId != null))
			{
				throw new BadParameterException("One of the following parameters must be set: clipId, gameId, broadcasterId. Only one is allowed to be set.");
			}
			if (!startedAt.HasValue && endedAt.HasValue)
			{
				throw new BadParameterException("The ended_at parameter cannot be used without the started_at parameter. Please include both parameters!");
			}
			if (startedAt.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("started_at", DateTimeExtensions.ToRfc3339String(startedAt.Value)));
			}
			if (endedAt.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("ended_at", DateTimeExtensions.ToRfc3339String(endedAt.Value)));
			}
			if (!string.IsNullOrWhiteSpace(before))
			{
				list.Add(new KeyValuePair<string, string>("before", before));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			if (isFeatured.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("is_featured", isFeatured.Value.ToString()));
			}
			list.Add(new KeyValuePair<string, string>("first", first.ToString()));
			return ((ApiBase)this).TwitchGetGenericAsync<GetClipsResponse>("/clips", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<CreatedClipResponse> CreateClipAsync(string broadcasterId, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchPostGenericAsync<CreatedClipResponse>("/clips", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}
	}
	public class ContentClassificationLabels : ApiBase
	{
		public ContentClassificationLabels(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetContentClassificationLabelsResponse> GetContentClassificationLabelsAsync(string locale = null, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			if (!string.IsNullOrWhiteSpace(locale))
			{
				list.Add(new KeyValuePair<string, string>("locale", locale));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetContentClassificationLabelsResponse>("/content_classification_labels", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}
	}
	public class Entitlements : ApiBase
	{
		public Entitlements(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetDropsEntitlementsResponse> GetDropsEntitlementsAsync(string id = null, string userId = null, string gameId = null, string after = null, int first = 20, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (!string.IsNullOrWhiteSpace(id))
			{
				list.Add(new KeyValuePair<string, string>("id", id));
			}
			if (!string.IsNullOrWhiteSpace(userId))
			{
				list.Add(new KeyValuePair<string, string>("user_id", userId));
			}
			if (!string.IsNullOrWhiteSpace(gameId))
			{
				list.Add(new KeyValuePair<string, string>("game_id", gameId));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetDropsEntitlementsResponse>("/entitlements/drops", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<UpdateDropsEntitlementsResponse> UpdateDropsEntitlementsAsync(string[] entitlementIds, FulfillmentStatus fulfillmentStatus, string accessToken)
		{
			var anon = new
			{
				entitlement_ids = entitlementIds,
				fulfillment_status = ((object)(FulfillmentStatus)(ref fulfillmentStatus)).ToString()
			};
			return ((ApiBase)this).TwitchPatchGenericAsync<UpdateDropsEntitlementsResponse>("/entitlements/drops", (ApiVersion)6, JsonConvert.SerializeObject((object)anon), (List<KeyValuePair<string, string>>)null, accessToken, (string)null, (string)null);
		}
	}
	public class EventSub : ApiBase
	{
		public EventSub(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<CreateEventSubSubscriptionResponse> CreateEventSubSubscriptionAsync(string type, string version, Dictionary<string, string> condition, EventSubTransportMethod method, string websocketSessionId = null, string webhookCallback = null, string webhookSecret = null, string conduitId = null, string clientId = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected I4, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(type))
			{
				throw new BadParameterException("type must be set");
			}
			if (string.IsNullOrEmpty(version))
			{
				throw new BadParameterException("version must be set");
			}
			if (condition == null || condition.Count == 0)
			{
				throw new BadParameterException("condition must be set");
			}
			EventSubTransportMethod val = method;
			EventSubTransportMethod val2 = val;
			switch ((int)val2)
			{
			case 0:
			{
				if (string.IsNullOrWhiteSpace(webhookCallback))
				{
					throw new BadParameterException("webhookCallback must be set");
				}
				if (webhookSecret == null || webhookSecret.Length < 10 || webhookSecret.Length > 100)
				{
					throw new BadParameterException("webhookSecret must be set, and be between 10 (inclusive) and 100 (inclusive)");
				}
				var anon3 = new
				{
					type = type,
					version = version,
					condition = condition,
					transport = new
					{
						method = ((object)(EventSubTransportMethod)(ref method)).ToString().ToLowerInvariant(),
						callback = webhookCallback,
						secret = webhookSecret
					}
				};
				return ((ApiBase)this).TwitchPostGenericAsync<CreateEventSubSubscriptionResponse>("/eventsub/subscriptions", (ApiVersion)6, JsonConvert.SerializeObject((object)anon3), (List<KeyValuePair<string, string>>)null, accessToken, clientId, (string)null);
			}
			case 1:
			{
				if (string.IsNullOrWhiteSpace(websocketSessionId))
				{
					throw new BadParameterException("websocketSessionId must be set");
				}
				var anon2 = new
				{
					type = type,
					version = version,
					condition = condition,
					transport = new
					{
						method = ((object)(EventSubTransportMethod)(ref method)).ToString().ToLowerInvariant(),
						session_id = websocketSessionId
					}
				};
				return ((ApiBase)this).TwitchPostGenericAsync<CreateEventSubSubscriptionResponse>("/eventsub/subscriptions", (ApiVersion)6, JsonConvert.SerializeObject((object)anon2), (List<KeyValuePair<string, string>>)null, accessToken, clientId, (string)null);
			}
			case 2:
			{
				if (string.IsNullOrWhiteSpace(conduitId))
				{
					throw new BadParameterException("conduitId must be set");
				}
				var anon = new
				{
					type = type,
					version = version,
					condition = condition,
					transport = new
					{
						method = ((object)(EventSubTransportMethod)(ref method)).ToString().ToLowerInvariant(),
						conduit_id = conduitId
					}
				};
				return ((ApiBase)this).TwitchPostGenericAsync<CreateEventSubSubscriptionResponse>("/eventsub/subscriptions", (ApiVersion)6, JsonConvert.SerializeObject((object)anon), (List<KeyValuePair<string, string>>)null, accessToken, clientId, (string)null);
			}
			default:
				throw new ArgumentOutOfRangeException("method", method, null);
			}
		}

		public Task<GetEventSubSubscriptionsResponse> GetEventSubSubscriptionsAsync(string status = null, string type = null, string userId = null, string after = null, string clientId = null, string accessToken = null)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			if (!string.IsNullOrWhiteSpace(status))
			{
				list.Add(new KeyValuePair<string, string>("status", status));
			}
			if (!string.IsNullOrWhiteSpace(type))
			{
				list.Add(new KeyValuePair<string, string>("type", type));
			}
			if (!string.IsNullOrWhiteSpace(userId))
			{
				list.Add(new KeyValuePair<string, string>("user_id", userId));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetEventSubSubscriptionsResponse>("/eventsub/subscriptions", (ApiVersion)6, list, accessToken, clientId, (string)null);
		}

		public async Task<bool> DeleteEventSubSubscriptionAsync(string id, string clientId = null, string accessToken = null)
		{
			List<KeyValuePair<string, string>> getParams = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("id", id)
			};
			return (await ((ApiBase)this).TwitchDeleteAsync("/eventsub/subscriptions", (ApiVersion)6, getParams, accessToken, clientId, (string)null)).Key == 204;
		}

		public async Task<GetConduitsResponse> GetConduits(string clientId = null, string accessToken = null)
		{
			return await ((ApiBase)this).TwitchGetGenericAsync<GetConduitsResponse>("/eventsub/conduits", (ApiVersion)6, (List<KeyValuePair<string, string>>)null, accessToken, clientId, (string)null);
		}

		public async Task<CreateConduitsResponse> CreateConduits(CreateConduitsRequest request, string clientId = null, string accessToken = null)
		{
			int shardCount = request.ShardCount;
			if ((shardCount <= 0 || shardCount > 20000) ? true : false)
			{
				throw new BadParameterException("request.ShardCount must be greater than 0 and less or equal than 20000");
			}
			return await ((ApiBase)this).TwitchPostGenericAsync<CreateConduitsResponse>("/eventsub/conduits", (ApiVersion)6, JsonConvert.SerializeObject((object)request), (List<KeyValuePair<string, string>>)null, accessToken, clientId, (string)null);
		}

		public async Task<UpdateConduitsResponse> UpdateConduits(UpdateConduitsRequest request, string clientId = null, string accessToken = null)
		{
			int shardCount = request.ShardCount;
			if ((shardCount <= 0 || shardCount > 20000) ? true : false)
			{
				throw new BadParameterException("request.ShardCount must be greater than 0 and less or equal than 20000");
			}
			return await ((ApiBase)this).TwitchPatchGenericAsync<UpdateConduitsResponse>("/eventsub/conduits", (ApiVersion)6, JsonConvert.SerializeObject((object)request), (List<KeyValuePair<string, string>>)null, accessToken, clientId, (string)null);
		}

		public async Task<bool> DeleteConduit(string id, string clientId = null, string accessToken = null)
		{
			List<KeyValuePair<string, string>> getParams = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("id", id)
			};
			return (await ((ApiBase)this).TwitchDeleteAsync("/eventsub/conduits", (ApiVersion)6, getParams, accessToken, clientId, (string)null)).Key == 204;
		}

		public async Task<GetConduitShardsResponse> GetConduitShards(string conduitId, string status = null, string after = null, string clientId = null, string accessToken = null)
		{
			List<KeyValuePair<string, string>> getParams = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("conduit_id", conduitId)
			};
			if (!string.IsNullOrWhiteSpace(status))
			{
				getParams.Add(new KeyValuePair<string, string>("status", status));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				getParams.Add(new KeyValuePair<string, string>("after", after));
			}
			return await ((ApiBase)this).TwitchGetGenericAsync<GetConduitShardsResponse>("/eventsub/conduits/shards", (ApiVersion)6, getParams, accessToken, clientId, (string)null);
		}

		public async Task<UpdateConduitShardsResponse> UpdateConduitShards(UpdateConduitShardsRequest request, string clientId = null, string accessToken = null)
		{
			List<string> validMethods = new List<string> { "webhook", "websocket" };
			ShardUpdate[] shards = request.Shards;
			foreach (ShardUpdate shard in shards)
			{
				if (!validMethods.Contains(shard.Transport.Method))
				{
					throw new BadParameterException("request.Shards.Transport.Method valid values: " + string.Join(", ", validMethods));
				}
				if (shard.Transport.Secret != null && (shard.Transport.Secret.Length < 10 || shard.Transport.Secret.Length > 100))
				{
					throw new BadParameterException($"request.Shards.Transport.Secret must be greater than or equal to {10} and less than or equal to {100}");
				}
			}
			return await ((ApiBase)this).TwitchPatchGenericAsync<UpdateConduitShardsResponse>("/eventsub/conduits/shards", (ApiVersion)6, JsonConvert.SerializeObject((object)request), (List<KeyValuePair<string, string>>)null, accessToken, clientId, (string)null);
		}
	}
	public class Extensions : ApiBase
	{
		public Extensions(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetExtensionTransactionsResponse> GetExtensionTransactionsAsync(string extensionId, List<string> ids = null, string after = null, int first = 20, string applicationAccessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(extensionId))
			{
				throw new BadParameterException("extensionId cannot be null");
			}
			if (first < 1 || first > 100)
			{
				throw new BadParameterException("'first' must between 1 (inclusive) and 100 (inclusive).");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("extension_id", extensionId)
			};
			if (ids != null)
			{
				list.AddRange(ids.Select((string id) => new KeyValuePair<string, string>("id", id)));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			list.Add(new KeyValuePair<string, string>("first", first.ToString()));
			return ((ApiBase)this).TwitchGetGenericAsync<GetExtensionTransactionsResponse>("/extensions/transactions", (ApiVersion)6, list, applicationAccessToken, (string)null, (string)null);
		}

		public Task<GetExtensionLiveChannelsResponse> GetExtensionLiveChannelsAsync(string extensionId, int first = 20, string after = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(extensionId))
			{
				throw new BadParameterException("extensionId must be set");
			}
			if (first < 1 || first > 100)
			{
				throw new BadParameterException("'first' must between 1 (inclusive) and 100 (inclusive).");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("extension_id", extensionId),
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetExtensionLiveChannelsResponse>("/extensions/live", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetReleasedExtensionsResponse> GetReleasedExtensionsAsync(string extensionId, string extensionVersion = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(extensionId))
			{
				throw new BadParameterException("extensionId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("extension_id", extensionId)
			};
			if (!string.IsNullOrWhiteSpace(extensionVersion))
			{
				list.Add(new KeyValuePair<string, string>("extension_version", extensionVersion));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetReleasedExtensionsResponse>("/extensions/released", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}
	}
	public class Games : ApiBase
	{
		public Games(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetGamesResponse> GetGamesAsync(List<string> gameIds = null, List<string> gameNames = null, List<string> igdbIds = null, string accessToken = null)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			if ((gameIds == null && gameNames == null && igdbIds == null) || (gameIds != null && gameIds.Count == 0 && gameNames == null && igdbIds == null) || (gameNames != null && gameNames.Count == 0 && gameIds == null && igdbIds == null) || (igdbIds != null && igdbIds.Count == 0 && gameIds == null && gameNames == null))
			{
				throw new BadParameterException("Either gameIds, gameNames or igdbIds must have at least one value");
			}
			if (gameIds != null && gameIds.Count > 100)
			{
				throw new BadParameterException("gameIds list cannot exceed 100 items");
			}
			if (gameNames != null && gameNames.Count > 100)
			{
				throw new BadParameterException("gameNames list cannot exceed 100 items");
			}
			if (igdbIds != null && igdbIds.Count > 100)
			{
				throw new BadParameterException("igdbIds list cannot exceed 100 items");
			}
			if (gameIds?.Count + gameNames?.Count + igdbIds?.Count > 100)
			{
				throw new BadParameterException("The combined amount of items of gameIds, gameNames and igdbIds cannot exceed 100 items");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			if (gameIds != null && gameIds.Count > 0)
			{
				list.AddRange(gameIds.Select((string gameId) => new KeyValuePair<string, string>("id", gameId)));
			}
			if (gameNames != null && gameNames.Count > 0)
			{
				list.AddRange(gameNames.Select((string gameName) => new KeyValuePair<string, string>("name", gameName)));
			}
			if (igdbIds != null && igdbIds.Count > 0)
			{
				list.AddRange(igdbIds.Select((string igdbId) => new KeyValuePair<string, string>("igdb_id", igdbId)));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetGamesResponse>("/games", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetTopGamesResponse> GetTopGamesAsync(string before = null, string after = null, int first = 20, string accessToken = null)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (first < 0 || first > 100)
			{
				throw new BadParameterException("'first' parameter must be between 1 (inclusive) and 100 (inclusive).");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (!string.IsNullOrWhiteSpace(before))
			{
				list.Add(new KeyValuePair<string, string>("before", before));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetTopGamesResponse>("/games/top", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}
	}
	public class Goals : ApiBase
	{
		public Goals(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetCreatorGoalsResponse> GetCreatorGoalsAsync(string broadcasterId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId cannot be null or empty");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetCreatorGoalsResponse>("/goals", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}
	}
	public class GuestStar : ApiBase
	{
		public GuestStar(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetChannelGuestStarSettingsResponse> GetChannelGuestStarSettingsAsync(string broadcasterId, string moderatorId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetChannelGuestStarSettingsResponse>("/guest_star/channel_settings", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task UpdateChannelGuestStarSettingsAsync(string broadcasterId, UpdateChannelGuestStarSettingsRequest newSettings, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (newSettings == null)
			{
				throw new BadParameterException("newSettings cannot be null");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			string text = JsonConvert.SerializeObject((object)newSettings);
			return ((ApiBase)this).TwitchPatchAsync("/guest_star/channel_settings", (ApiVersion)6, text, list, accessToken, (string)null, (string)null);
		}

		public Task<GetGuestStarSessionResponse> GetGuestStarSessionAsync(string broadcasterId, string moderatorId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetGuestStarSessionResponse>("/guest_star/session", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<CreateGuestStarSessionResponse> CreateGuestStarSession(string broadcasterId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			return ((ApiBase)this).TwitchPostGenericAsync<CreateGuestStarSessionResponse>("/guest_star/session", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}

		public Task<EndGuestStarSessionResponse> EndGuestStarSession(string broadcasterId, string sessionId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(sessionId))
			{
				throw new BadParameterException("sessionId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("sessionId", sessionId)
			};
			return ((ApiBase)this).TwitchDeleteGenericAsync<EndGuestStarSessionResponse>("/guest_star/session", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetGuestStarInvitesResponse> GetGuestStarInvitesAsync(string broadcasterId, string moderatorId, string sessionId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (string.IsNullOrWhiteSpace(sessionId))
			{
				throw new BadParameterException("sessionId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("session_id", sessionId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetGuestStarInvitesResponse>("/guest_star/invites", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task SendGuestStarInvitesAsync(string broadcasterId, string moderatorId, string sessionId, string guestId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (string.IsNullOrWhiteSpace(sessionId))
			{
				throw new BadParameterException("sessionId must be set");
			}
			if (string.IsNullOrWhiteSpace(guestId))
			{
				throw new BadParameterException("guestId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("session_id", sessionId),
				new KeyValuePair<string, string>("guest_id", guestId)
			};
			return ((ApiBase)this).TwitchPostAsync("/guest_star/invites", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}

		public Task DeleteGuestStarInvitesAsync(string broadcasterId, string moderatorId, string sessionId, string guestId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (string.IsNullOrWhiteSpace(sessionId))
			{
				throw new BadParameterException("sessionId must be set");
			}
			if (string.IsNullOrWhiteSpace(guestId))
			{
				throw new BadParameterException("guestId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("session_id", sessionId),
				new KeyValuePair<string, string>("guest_id", guestId)
			};
			return ((ApiBase)this).TwitchDeleteAsync("/guest_star/invites", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task AssignGuestStarSlotAsync(string broadcasterId, string moderatorId, string sessionId, string guestId, string slotId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (string.IsNullOrWhiteSpace(sessionId))
			{
				throw new BadParameterException("sessionId must be set");
			}
			if (string.IsNullOrWhiteSpace(guestId))
			{
				throw new BadParameterException("guestId must be set");
			}
			if (string.IsNullOrWhiteSpace(slotId))
			{
				throw new BadParameterException("slotId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("session_id", sessionId),
				new KeyValuePair<string, string>("guest_id", guestId),
				new KeyValuePair<string, string>("slot_id", slotId)
			};
			return ((ApiBase)this).TwitchPostAsync("/guest_star/slot", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}

		public Task UpdateGuestStarSlotAsync(string broadcasterId, string moderatorId, string sessionId, string sourceSlotId, string destinationSlotId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (string.IsNullOrWhiteSpace(sessionId))
			{
				throw new BadParameterException("sessionId must be set");
			}
			if (string.IsNullOrWhiteSpace(sourceSlotId))
			{
				throw new BadParameterException("sourceSlotId must be set");
			}
			if (string.IsNullOrWhiteSpace(destinationSlotId))
			{
				throw new BadParameterException("destinationSlotId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("session_id", sessionId),
				new KeyValuePair<string, string>("source_slot_id", sourceSlotId),
				new KeyValuePair<string, string>("destination_slot_id", destinationSlotId)
			};
			return ((ApiBase)this).TwitchPatchAsync("/guest_star/slot", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}

		public Task DeleteGuestStarSlotAsync(string broadcasterId, string moderatorId, string sessionId, string slotId, bool? shouldReinviteGuest = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (string.IsNullOrWhiteSpace(sessionId))
			{
				throw new BadParameterException("sessionId must be set");
			}
			if (string.IsNullOrWhiteSpace(slotId))
			{
				throw new BadParameterException("slotId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("session_id", sessionId),
				new KeyValuePair<string, string>("slot_id", slotId)
			};
			if (shouldReinviteGuest.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("should_reinvite_guest", shouldReinviteGuest.Value.ToString()));
			}
			return ((ApiBase)this).TwitchDeleteAsync("/guest_star/slot", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task UpdateGuestStarSlotSettingsAsync(string broadcasterId, string moderatorId, string sessionId, string slotId, bool? isAudioEnabled = null, bool? isVideoEnabled = null, bool? isLive = null, int? volume = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (string.IsNullOrWhiteSpace(sessionId))
			{
				throw new BadParameterException("sessionId must be set");
			}
			if (string.IsNullOrWhiteSpace(slotId))
			{
				throw new BadParameterException("slotId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("session_id", sessionId),
				new KeyValuePair<string, string>("slot_id", slotId)
			};
			if (isAudioEnabled.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("is_audio_enabled", isAudioEnabled.Value.ToString()));
			}
			if (isVideoEnabled.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("is_video_enabled", isVideoEnabled.Value.ToString()));
			}
			if (isLive.HasValue)
			{
				list.Add(new KeyValuePair<string, string>("is_live", isLive.Value.ToString()));
			}
			if (volume.HasValue)
			{
				int valueOrDefault = volume.GetValueOrDefault();
				if (valueOrDefault >= 0 && valueOrDefault <= 100)
				{
					list.Add(new KeyValuePair<string, string>("volume", volume.Value.ToString()));
				}
			}
			return ((ApiBase)this).TwitchPatchAsync("/guest_star/slot_settings", (ApiVersion)6, (string)null, list, accessToken, (string)null, (string)null);
		}
	}
	public class Helix
	{
		private readonly ILogger<Helix> _logger;

		public IApiSettings Settings { get; }

		public Analytics Analytics { get; }

		public Bits Bits { get; }

		public Chat Chat { get; }

		public Channels Channels { get; }

		public ChannelPoints ChannelPoints { get; }

		public Charity Charity { get; }

		public Clips Clips { get; }

		public Entitlements Entitlements { get; }

		public ContentClassificationLabels ContentClassificationLabels { get; }

		public EventSub EventSub { get; }

		public Extensions Extensions { get; }

		public Games Games { get; }

		public Goals Goals { get; }

		public GuestStar GuestStar { get; }

		public HypeTrain HypeTrain { get; }

		public Moderation Moderation { get; }

		public Polls Polls { get; }

		public Predictions Predictions { get; }

		public Raids Raids { get; }

		public Schedule Schedule { get; }

		public Search Search { get; }

		public Streams Streams { get; }

		public Subscriptions Subscriptions { get; }

		public Tags Tags { get; }

		public Teams Teams { get; }

		public Videos Videos { get; }

		public Users Users { get; }

		public Whispers Whispers { get; }

		public Helix(ILoggerFactory loggerFactory = null, IRateLimiter rateLimiter = null, IApiSettings settings = null, IHttpCallHandler http = null)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			_logger = loggerFactory?.CreateLogger<Helix>();
			rateLimiter = (IRateLimiter)(((object)rateLimiter) ?? ((object)BypassLimiter.CreateLimiterBypassInstance()));
			http = (IHttpCallHandler)(((object)http) ?? ((object)new TwitchHttpClient(loggerFactory?.CreateLogger<TwitchHttpClient>())));
			Settings = (IApiSettings)(((object)settings) ?? ((object)new ApiSettings()));
			Analytics = new Analytics(Settings, rateLimiter, http);
			Bits = new Bits(Settings, rateLimiter, http);
			Chat = new Chat(Settings, rateLimiter, http);
			Channels = new Channels(Settings, rateLimiter, http);
			ChannelPoints = new ChannelPoints(Settings, rateLimiter, http);
			Charity = new Charity(Settings, rateLimiter, http);
			Clips = new Clips(Settings, rateLimiter, http);
			ContentClassificationLabels = new ContentClassificationLabels(Settings, rateLimiter, http);
			Entitlements = new Entitlements(Settings, rateLimiter, http);
			EventSub = new EventSub(Settings, rateLimiter, http);
			Extensions = new Extensions(Settings, rateLimiter, http);
			Games = new Games(Settings, rateLimiter, http);
			Goals = new Goals(settings, rateLimiter, http);
			GuestStar = new GuestStar(settings, rateLimiter, http);
			HypeTrain = new HypeTrain(Settings, rateLimiter, http);
			Moderation = new Moderation(Settings, rateLimiter, http);
			Polls = new Polls(Settings, rateLimiter, http);
			Predictions = new Predictions(Settings, rateLimiter, http);
			Raids = new Raids(settings, rateLimiter, http);
			Schedule = new Schedule(Settings, rateLimiter, http);
			Search = new Search(Settings, rateLimiter, http);
			Streams = new Streams(Settings, rateLimiter, http);
			Subscriptions = new Subscriptions(Settings, rateLimiter, http);
			Tags = new Tags(Settings, rateLimiter, http);
			Teams = new Teams(Settings, rateLimiter, http);
			Users = new Users(Settings, rateLimiter, http);
			Videos = new Videos(Settings, rateLimiter, http);
			Whispers = new Whispers(Settings, rateLimiter, http);
		}
	}
	public class HypeTrain : ApiBase
	{
		public HypeTrain(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task<GetHypeTrainResponse> GetHypeTrainEventsAsync(string broadcasterId, int first = 1, string cursor = null, string accessToken = null)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("BroadcasterId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (!string.IsNullOrWhiteSpace(cursor))
			{
				list.Add(new KeyValuePair<string, string>("cursor", cursor));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetHypeTrainResponse>("/hypetrain/events", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}
	}
	public class Moderation : ApiBase
	{
		public Moderation(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http)
			: base(settings, rateLimiter, http)
		{
		}

		public Task ManageHeldAutoModMessagesAsync(string userId, string msgId, ManageHeldAutoModMessageActionEnum action, string accessToken = null)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(msgId))
			{
				throw new BadParameterException("userId and msgId cannot be null and must be greater than 0 length");
			}
			JObject val = new JObject
			{
				["user_id"] = JToken.op_Implicit(userId),
				["msg_id"] = JToken.op_Implicit(msgId),
				["action"] = JToken.op_Implicit(((object)(ManageHeldAutoModMessageActionEnum)(ref action)).ToString().ToUpper())
			};
			return ((ApiBase)this).TwitchPostAsync("/moderation/automod/message", (ApiVersion)6, ((object)val).ToString(), (List<KeyValuePair<string, string>>)null, accessToken, (string)null, (string)null);
		}

		public Task<CheckAutoModStatusResponse> CheckAutoModStatusAsync(List<Message> messages, string broadcasterId, string accessToken = null)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (messages == null || messages.Count == 0)
			{
				throw new BadParameterException("messages cannot be null and must be greater than 0 length");
			}
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId cannot be null/empty/whitespace");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			MessageRequest val = new MessageRequest
			{
				Messages = messages.ToArray()
			};
			return ((ApiBase)this).TwitchPostGenericAsync<CheckAutoModStatusResponse>("/moderation/enforcements/status", (ApiVersion)6, JsonConvert.SerializeObject((object)val), list, accessToken, (string)null, (string)null);
		}

		public Task<GetBannedEventsResponse> GetBannedEventsAsync(string broadcasterId, List<string> userIds = null, string after = null, int first = 20, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId cannot be null/empty/whitespace");
			}
			if (first < 1 || first > 100)
			{
				throw new BadParameterException("first cannot be less than 1 or greater than 100");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			if (userIds != null && userIds.Count > 0)
			{
				list.AddRange(userIds.Select((string userId) => new KeyValuePair<string, string>("user_id", userId)));
			}
			if (string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			list.Add(new KeyValuePair<string, string>("first", first.ToString()));
			return ((ApiBase)this).TwitchGetGenericAsync<GetBannedEventsResponse>("/moderation/banned/events", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetBannedUsersResponse> GetBannedUsersAsync(string broadcasterId, List<string> userIds = null, int first = 20, string after = null, string before = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId cannot be null/empty/whitespace");
			}
			if (first < 1 || first > 100)
			{
				throw new BadParameterException("first cannot be less than 1 or greater than 100");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (userIds != null && userIds.Count > 0)
			{
				list.AddRange(userIds.Select((string userId) => new KeyValuePair<string, string>("user_id", userId)));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			if (!string.IsNullOrWhiteSpace(before))
			{
				list.Add(new KeyValuePair<string, string>("before", before));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetBannedUsersResponse>("/moderation/banned", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetModeratorsResponse> GetModeratorsAsync(string broadcasterId, List<string> userIds = null, int first = 20, string after = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId cannot be null/empty/whitespace");
			}
			if (first > 100 || first < 1)
			{
				throw new BadParameterException("first must be greater than 0 and less than 101");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (userIds != null && userIds.Count > 0)
			{
				list.AddRange(userIds.Select((string userId) => new KeyValuePair<string, string>("user_id", userId)));
			}
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetModeratorsResponse>("/moderation/moderators", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetModeratorEventsResponse> GetModeratorEventsAsync(string broadcasterId, List<string> userIds = null, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId cannot be null/empty/whitespace");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId)
			};
			if (userIds != null && userIds.Count > 0)
			{
				list.AddRange(userIds.Select((string userId) => new KeyValuePair<string, string>("user_id", userId)));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetModeratorEventsResponse>("/moderation/moderators/events", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<BanUserResponse> BanUserAsync(string broadcasterId, string moderatorId, BanUserRequest banUserRequest, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrEmpty(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (banUserRequest == null)
			{
				throw new BadParameterException("banUserRequest cannot be null");
			}
			if (string.IsNullOrWhiteSpace(banUserRequest.UserId))
			{
				throw new BadParameterException("banUserRequest.UserId must be set");
			}
			if (banUserRequest.Duration.HasValue && (banUserRequest.Duration.Value <= 0 || banUserRequest.Duration.Value > 1209600))
			{
				throw new BadParameterException("banUserRequest.Duration has to be between including 1 and including 1209600");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId)
			};
			var anon = new
			{
				data = banUserRequest
			};
			return ((ApiBase)this).TwitchPostGenericAsync<BanUserResponse>("/moderation/bans", (ApiVersion)6, JsonConvert.SerializeObject((object)anon), list, accessToken, (string)null, (string)null);
		}

		public Task UnbanUserAsync(string broadcasterId, string moderatorId, string userId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (string.IsNullOrWhiteSpace(userId))
			{
				throw new BadParameterException("userId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("user_id", userId)
			};
			return ((ApiBase)this).TwitchDeleteAsync("/moderation/bans", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<GetAutomodSettingsResponse> GetAutomodSettingsAsync(string broadcasterId, string moderatorId, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId)
			};
			return ((ApiBase)this).TwitchGetGenericAsync<GetAutomodSettingsResponse>("/moderation/automod/settings", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<UpdateAutomodSettingsResponse> UpdateAutomodSettingsAsync(string broadcasterId, string moderatorId, AutomodSettings settings, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId)
			};
			return ((ApiBase)this).TwitchPutGenericAsync<UpdateAutomodSettingsResponse>("/moderation/automod/settings", (ApiVersion)6, JsonConvert.SerializeObject((object)settings), list, accessToken, (string)null, (string)null);
		}

		public Task<GetBlockedTermsResponse> GetBlockedTermsAsync(string broadcasterId, string moderatorId, string after = null, int first = 20, string accessToken = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			if (string.IsNullOrWhiteSpace(broadcasterId))
			{
				throw new BadParameterException("broadcasterId must be set");
			}
			if (string.IsNullOrWhiteSpace(moderatorId))
			{
				throw new BadParameterException("moderatorId must be set");
			}
			if (first < 1 || first > 100)
			{
				throw new BadParameterException("first must be greater than 0 and less than 101");
			}
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("broadcaster_id", broadcasterId),
				new KeyValuePair<string, string>("moderator_id", moderatorId),
				new KeyValuePair<string, string>("first", first.ToString())
			};
			if (!string.IsNullOrWhiteSpace(after))
			{
				list.Add(new KeyValuePair<string, string>("after", after));
			}
			return ((ApiBase)this).TwitchGetGenericAsync<GetBlockedTermsResponse>("/moderation/blocked_terms", (ApiVersion)6, list, accessToken, (string)null, (string)null);
		}

		public Task<AddBlockedTermResponse> AddBlo

TwitchLib.Api.Helix.Models.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using TwitchLib.Api.Core.Enums;
using TwitchLib.Api.Helix.Models.Common;
using TwitchLib.Api.Helix.Models.Users.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2022")]
[assembly: AssemblyDescription("Project containing the Helix models used in TwitchLib.Api")]
[assembly: AssemblyFileVersion("3.10.0")]
[assembly: AssemblyInformationalVersion("3.10.0+92a4359ed145876af4e8e108e267004dcb0babab")]
[assembly: AssemblyProduct("TwitchLib.Api.Helix.Models")]
[assembly: AssemblyTitle("TwitchLib.Api.Helix.Models")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/swiftyspiffy/TwitchLib")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("3.10.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 TwitchLib.Api.Helix.Models.Videos.GetVideos
{
	public class GetVideosResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Video[] Videos { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class MutedSegment
	{
		[JsonProperty(PropertyName = "duration")]
		public int Duration { get; protected set; }

		[JsonProperty(PropertyName = "offset")]
		public int Offset { get; protected set; }
	}
	public class Video
	{
		[JsonProperty(PropertyName = "created_at")]
		public string CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "description")]
		public string Description { get; protected set; }

		[JsonProperty(PropertyName = "duration")]
		public string Duration { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "language")]
		public string Language { get; protected set; }

		[JsonProperty(PropertyName = "published_at")]
		public string PublishedAt { get; protected set; }

		[JsonProperty(PropertyName = "thumbnail_url")]
		public string ThumbnailUrl { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; protected set; }

		[JsonProperty(PropertyName = "url")]
		public string Url { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "viewable")]
		public string Viewable { get; protected set; }

		[JsonProperty(PropertyName = "view_count")]
		public int ViewCount { get; protected set; }

		[JsonProperty(PropertyName = "stream_id")]
		public string StreamId { get; protected set; }

		[JsonProperty(PropertyName = "muted_segments")]
		public MutedSegment[] MutedSegments { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Videos.DeleteVideos
{
	public class DeleteVideosResponse
	{
		[JsonProperty(PropertyName = "data")]
		public string[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Users.UpdateUserExtensions
{
	public class UpdateUserExtensionsRequest
	{
		[JsonProperty(PropertyName = "panel")]
		public Dictionary<string, UserExtensionState> Panel { get; set; }

		[JsonProperty(PropertyName = "component")]
		public Dictionary<string, UserExtensionState> Component { get; set; }

		[JsonProperty(PropertyName = "overlay")]
		public Dictionary<string, UserExtensionState> Overlay { get; set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Users.Internal
{
	public class ActiveExtensions
	{
		[JsonProperty(PropertyName = "panel")]
		public Dictionary<string, UserActiveExtension> Panel { get; protected set; }

		[JsonProperty(PropertyName = "overlay")]
		public Dictionary<string, UserActiveExtension> Overlay { get; protected set; }

		[JsonProperty(PropertyName = "component")]
		public Dictionary<string, UserActiveExtension> Component { get; protected set; }
	}
	public class ExtensionSlot
	{
		public ExtensionType Type;

		public string Slot;

		public UserExtensionState UserExtensionState;

		public ExtensionSlot(ExtensionType type, string slot, UserExtensionState userExtensionState)
		{
			//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)
			Type = type;
			Slot = slot;
			UserExtensionState = userExtensionState;
		}
	}
	public class UserActiveExtension
	{
		[JsonProperty(PropertyName = "active")]
		public bool Active { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "version")]
		public string Version { get; protected set; }

		[JsonProperty(PropertyName = "name")]
		public string Name { get; protected set; }

		[JsonProperty(PropertyName = "x")]
		public int X { get; protected set; }

		[JsonProperty(PropertyName = "y")]
		public int Y { get; protected set; }
	}
	public class UserExtension
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "version")]
		public string Version { get; protected set; }

		[JsonProperty(PropertyName = "name")]
		public string Name { get; protected set; }

		[JsonProperty(PropertyName = "can_activate")]
		public bool CanActivate { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string[] Type { get; protected set; }
	}
	public class UserExtensionState
	{
		[JsonProperty(PropertyName = "active")]
		public bool Active { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "version")]
		public string Version { get; protected set; }

		public UserExtensionState(bool active, string id, string version)
		{
			Active = active;
			Id = id;
			Version = version;
		}
	}
}
namespace TwitchLib.Api.Helix.Models.Users.GetUsers
{
	public class GetUsersResponse
	{
		[JsonProperty(PropertyName = "data")]
		public User[] Users { get; protected set; }
	}
	public class User
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "login")]
		public string Login { get; protected set; }

		[JsonProperty(PropertyName = "display_name")]
		public string DisplayName { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public DateTime CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_type")]
		public string BroadcasterType { get; protected set; }

		[JsonProperty(PropertyName = "description")]
		public string Description { get; protected set; }

		[JsonProperty(PropertyName = "profile_image_url")]
		public string ProfileImageUrl { get; protected set; }

		[JsonProperty(PropertyName = "offline_image_url")]
		public string OfflineImageUrl { get; protected set; }

		[Obsolete]
		[JsonProperty(PropertyName = "view_count")]
		public long ViewCount { get; protected set; }

		[JsonProperty(PropertyName = "email")]
		public string Email { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Users.GetUserFollows
{
	public class Follow
	{
		[JsonProperty(PropertyName = "from_id")]
		public string FromUserId { get; protected set; }

		[JsonProperty(PropertyName = "from_login")]
		public string FromLogin { get; protected set; }

		[JsonProperty(PropertyName = "from_name")]
		public string FromUserName { get; protected set; }

		[JsonProperty(PropertyName = "to_id")]
		public string ToUserId { get; protected set; }

		[JsonProperty(PropertyName = "to_login")]
		public string ToLogin { get; protected set; }

		[JsonProperty(PropertyName = "to_name")]
		public string ToUserName { get; protected set; }

		[JsonProperty(PropertyName = "followed_at")]
		public DateTime FollowedAt { get; protected set; }
	}
	public class GetUsersFollowsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Follow[] Follows { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }

		[JsonProperty(PropertyName = "total")]
		public long TotalFollows { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Users.GetUserExtensions
{
	public class GetUserExtensionsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public UserExtension[] Users { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Users.GetUserBlockList
{
	public class BlockedUser
	{
		[JsonProperty(PropertyName = "user_id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "display_name")]
		public string DisplayName { get; protected set; }
	}
	public class GetUserBlockListResponse
	{
		[JsonProperty(PropertyName = "data")]
		public BlockedUser[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Users.GetUserActiveExtensions
{
	public class GetUserActiveExtensionsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ActiveExtensions Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Teams
{
	public class ChannelTeam : TeamBase
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }
	}
	public class GetChannelTeamsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ChannelTeam[] ChannelTeams { get; protected set; }
	}
	public class GetTeamsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Team[] Teams { get; protected set; }
	}
	public class Team : TeamBase
	{
		[JsonProperty(PropertyName = "users")]
		public TeamMember[] Users { get; protected set; }
	}
	public abstract class TeamBase
	{
		[JsonProperty(PropertyName = "banner")]
		public string Banner { get; protected set; }

		[JsonProperty(PropertyName = "background_image_url")]
		public string BackgroundImageUrl { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public string CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "updated_at")]
		public string UpdatedAt { get; protected set; }

		[JsonProperty(PropertyName = "info")]
		public string Info { get; protected set; }

		[JsonProperty(PropertyName = "thumbnail_url")]
		public string ThumbnailUrl { get; protected set; }

		[JsonProperty(PropertyName = "team_name")]
		public string TeamName { get; protected set; }

		[JsonProperty(PropertyName = "team_display_name")]
		public string TeamDisplayName { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }
	}
	public class TeamMember
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Tags
{
	public class GetAllStreamTagsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Tag[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Subscriptions
{
	public class CheckUserSubscriptionResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Subscription[] Data { get; protected set; }
	}
	public class GetBroadcasterSubscriptionsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Subscription[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }

		[JsonProperty(PropertyName = "total")]
		public int Total { get; protected set; }

		[JsonProperty(PropertyName = "points")]
		public int Points { get; protected set; }
	}
	public class GetUserSubscriptionsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Subscription[] Data { get; protected set; }
	}
	public class Subscription
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "is_gift")]
		public bool IsGift { get; protected set; }

		[JsonProperty(PropertyName = "tier")]
		public string Tier { get; protected set; }

		[JsonProperty(PropertyName = "plan_name")]
		public string PlanName { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "gifter_id")]
		public string GiftertId { get; protected set; }

		[JsonProperty(PropertyName = "gifter_name")]
		public string GifterName { get; protected set; }

		[JsonProperty(PropertyName = "gifter_login")]
		public string GifterLogin { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Streams.GetStreamTags
{
	public class GetStreamTagsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Tag[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Streams.GetStreams
{
	public class GetStreamsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Stream[] Streams { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public static class GetStreamsType
	{
		public const string All = "all";

		public const string Live = "live";
	}
	public class LiveStreams
	{
		[JsonProperty(PropertyName = "_total")]
		public int Total { get; protected set; }

		[JsonProperty(PropertyName = "streams")]
		public Stream[] Streams { get; protected set; }
	}
	public class Stream
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "game_id")]
		public string GameId { get; protected set; }

		[JsonProperty(PropertyName = "game_name")]
		public string GameName { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "tags")]
		public string[] Tags { get; protected set; }

		[JsonProperty(PropertyName = "viewer_count")]
		public int ViewerCount { get; protected set; }

		[JsonProperty(PropertyName = "started_at")]
		public DateTime StartedAt { get; protected set; }

		[JsonProperty(PropertyName = "language")]
		public string Language { get; protected set; }

		[JsonProperty(PropertyName = "thumbnail_url")]
		public string ThumbnailUrl { get; protected set; }

		[Obsolete]
		[JsonProperty(PropertyName = "tag_ids")]
		public string[] TagIds { get; protected set; }

		[JsonProperty(PropertyName = "is_mature")]
		public bool IsMature { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Streams.GetStreamMarkers
{
	public class GetStreamMarkersResponse
	{
		[JsonProperty(PropertyName = "data")]
		public UserMarkerListing[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class Marker
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public DateTime CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "description")]
		public string Description { get; protected set; }

		[JsonProperty(PropertyName = "position_seconds")]
		public int PositionSeconds { get; protected set; }

		[JsonProperty(PropertyName = "URL")]
		public string Url { get; protected set; }
	}
	public class UserMarkerListing
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "videos")]
		public Video[] Videos { get; protected set; }
	}
	public class Video
	{
		[JsonProperty(PropertyName = "video_id")]
		public string VideoId { get; protected set; }

		[JsonProperty(PropertyName = "markers")]
		public Marker[] Markers { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Streams.GetStreamKey
{
	public class GetStreamKeyResponse
	{
		[JsonProperty(PropertyName = "data")]
		public StreamKey[] Streams { get; protected set; }
	}
	public class StreamKey
	{
		[JsonProperty(PropertyName = "stream_key")]
		public string Key { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Streams.GetFollowedStreams
{
	public class GetFollowedStreamsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Stream[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class Stream
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "game_id")]
		public string GameId { get; protected set; }

		[JsonProperty(PropertyName = "game_name")]
		public string GameName { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "viewer_count")]
		public int ViewerCount { get; protected set; }

		[JsonProperty(PropertyName = "started_at")]
		public DateTime StartedAt { get; protected set; }

		[JsonProperty(PropertyName = "language")]
		public string Language { get; protected set; }

		[JsonProperty(PropertyName = "thumbnail_url")]
		public string ThumbnailUrl { get; protected set; }

		[Obsolete]
		[JsonProperty(PropertyName = "tag_ids")]
		public string[] TagIds { get; protected set; }

		[JsonProperty(PropertyName = "tags")]
		public string[] Tags { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Streams.CreateStreamMarker
{
	public class CreatedMarker
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public DateTime CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "description")]
		public string Description { get; protected set; }

		[JsonProperty(PropertyName = "position_seconds")]
		public int PositionSeconds { get; protected set; }
	}
	[JsonObject(/*Could not decode attribute arguments.*/)]
	public class CreateStreamMarkerRequest
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; set; }

		[JsonProperty(PropertyName = "description")]
		public string Description { get; set; }
	}
	public class CreateStreamMarkerResponse
	{
		[JsonProperty(PropertyName = "data")]
		public CreatedMarker[] Marker { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Search
{
	public class Channel
	{
		[JsonProperty(PropertyName = "game_id")]
		public string GameId { get; protected set; }

		[JsonProperty(PropertyName = "game_name")]
		public string GameName { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "display_name")]
		public string DisplayName { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_language")]
		public string BroadcasterLanguage { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "thumbnail_url")]
		public string ThumbnailUrl { get; protected set; }

		[JsonProperty(PropertyName = "is_live")]
		public bool IsLive { get; protected set; }

		[JsonProperty(PropertyName = "started_at")]
		public DateTime? StartedAt { get; protected set; }

		[Obsolete]
		[JsonProperty(PropertyName = "tag_ids")]
		public List<string> TagIds { get; protected set; }

		[JsonProperty(PropertyName = "tags")]
		public List<string> Tags { get; protected set; }
	}
	public class Game
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "name")]
		public string Name { get; protected set; }

		[JsonProperty(PropertyName = "box_art_url")]
		public string BoxArtUrl { get; protected set; }
	}
	public class SearchCategoriesResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Game[] Games { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class SearchChannelsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Channel[] Channels { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Schedule
{
	public class Category
	{
		[JsonProperty("id")]
		public string Id { get; protected set; }

		[JsonProperty("name")]
		public string Name { get; protected set; }
	}
	public class ChannelStreamSchedule
	{
		[JsonProperty("segments")]
		public Segment[] Segments { get; protected set; }

		[JsonProperty("broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty("broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty("broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty("vacation")]
		public Vacation Vacation { get; protected set; }
	}
	public class Segment
	{
		[JsonProperty("id")]
		public string Id { get; protected set; }

		[JsonProperty("start_time")]
		public DateTime StartTime { get; protected set; }

		[JsonProperty("end_time")]
		public DateTime EndTime { get; protected set; }

		[JsonProperty("title")]
		public string Title { get; protected set; }

		[JsonProperty("canceled_until")]
		public DateTime? CanceledUntil { get; protected set; }

		[JsonProperty("category")]
		public Category Category { get; protected set; }

		[JsonProperty("is_recurring")]
		public bool IsRecurring { get; protected set; }
	}
	public class Vacation
	{
		[JsonProperty("start_time")]
		public DateTime StartTime { get; protected set; }

		[JsonProperty("end_time")]
		public DateTime EndTime { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Schedule.UpdateChannelStreamSegment
{
	public class UpdateChannelStreamSegmentRequest
	{
		[JsonProperty("start_time")]
		public DateTime StartTime { get; set; }

		[JsonProperty("duration")]
		public string Duration { get; set; }

		[JsonProperty("category_id")]
		public string CategoryId { get; set; }

		[JsonProperty("title")]
		public string Title { get; set; }

		[JsonProperty("is_canceled")]
		public bool IsCanceled { get; set; }

		[JsonProperty("timezone")]
		public string Timezone { get; set; }
	}
	public class UpdateChannelStreamSegmentResponse
	{
		[JsonProperty("data")]
		public ChannelStreamSchedule Schedule { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Schedule.GetChannelStreamSchedule
{
	public class GetChannelStreamScheduleResponse
	{
		[JsonProperty("data")]
		public ChannelStreamSchedule Schedule { get; protected set; }

		[JsonProperty("pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Schedule.CreateChannelStreamSegment
{
	public class CreateChannelStreamSegmentRequest
	{
		[JsonProperty("start_time")]
		public DateTime StartTime { get; set; }

		[JsonProperty("timezone")]
		public string Timezone { get; set; }

		[JsonProperty("is_recurring")]
		public bool IsRecurring { get; set; }

		[JsonProperty("duration")]
		public string Duration { get; set; }

		[JsonProperty("category_id")]
		public string CategoryId { get; set; }

		[JsonProperty("title")]
		public string Title { get; set; }
	}
	public class CreateChannelStreamSegmentResponse
	{
		[JsonProperty("data")]
		public ChannelStreamSchedule Schedule { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Raids
{
	public class Raid
	{
		[JsonProperty(PropertyName = "created_at")]
		public DateTime CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "is_mature")]
		public bool IsMature { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Raids.StartRaid
{
	public class StartRaidResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Raid[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Predictions
{
	public class Outcome
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "users")]
		public int ChannelPoints { get; protected set; }

		[JsonProperty(PropertyName = "channel_points")]
		public int ChannelPointsVotes { get; protected set; }

		[JsonProperty(PropertyName = "top_predictors")]
		public TopPredictor[] TopPredictors { get; protected set; }

		[JsonProperty(PropertyName = "color")]
		public string Color { get; protected set; }
	}
	public class Prediction
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "winning_outcome_id")]
		public string WinningOutcomeId { get; protected set; }

		[JsonProperty(PropertyName = "outcomes")]
		public Outcome[] Outcomes { get; protected set; }

		[JsonProperty(PropertyName = "prediction_window")]
		public string PredictionWindow { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public PredictionStatus Status { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public string CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "ended_at")]
		public string EndedAt { get; protected set; }

		[JsonProperty(PropertyName = "locked_at")]
		public string LockedAt { get; protected set; }
	}
	public class TopPredictor
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "channel_points_used")]
		public int ChannelPointsUsed { get; protected set; }

		[JsonProperty(PropertyName = "channel_points_won")]
		public int ChannelPointsWon { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Predictions.GetPredictions
{
	public class GetPredictionsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Prediction[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Predictions.EndPrediction
{
	public class EndPredictionResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Prediction[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Predictions.CreatePrediction
{
	public class CreatePredictionRequest
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; set; }

		[JsonProperty(PropertyName = "outcomes")]
		public Outcome[] Outcomes { get; set; }

		[JsonProperty(PropertyName = "prediction_window")]
		public int PredictionWindowSeconds { get; set; }
	}
	public class CreatePredictionResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Prediction[] Data { get; protected set; }
	}
	public class Outcome
	{
		[JsonProperty(PropertyName = "title")]
		public string Title { get; set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Polls
{
	public class Choice
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "votes")]
		public int Votes { get; protected set; }

		[JsonProperty(PropertyName = "channel_points_votes")]
		public int ChannelPointsVotes { get; protected set; }

		[JsonProperty(PropertyName = "bits_votes")]
		public int BitsVotes { get; protected set; }
	}
	public class Poll
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "choices")]
		public Choice[] Choices { get; protected set; }

		[JsonProperty(PropertyName = "bits_voting_enabled")]
		public bool BitsVotingEnabled { get; protected set; }

		[JsonProperty(PropertyName = "bits_per_vote")]
		public int BitsPerVote { get; protected set; }

		[JsonProperty(PropertyName = "channel_points_voting_enabled")]
		public bool ChannelPointsVotingEnabled { get; protected set; }

		[JsonProperty(PropertyName = "channel_points_per_vote")]
		public int ChannelPointsPerVote { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public string Status { get; protected set; }

		[JsonProperty(PropertyName = "duration")]
		public int DurationSeconds { get; protected set; }

		[JsonProperty(PropertyName = "started_at")]
		public DateTime StartedAt { get; protected set; }

		[JsonProperty(PropertyName = "ended_at")]
		public DateTime EndedAt { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Polls.GetPolls
{
	public class GetPollsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Poll[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Polls.EndPoll
{
	public class EndPollResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Poll[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Polls.CreatePoll
{
	public class Choice
	{
		[JsonProperty(PropertyName = "title")]
		public string Title { get; set; }
	}
	public class CreatePollRequest
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; set; }

		[JsonProperty(PropertyName = "choices")]
		public Choice[] Choices { get; set; }

		[JsonProperty(PropertyName = "channel_points_voting_enabled")]
		public bool ChannelPointsVotingEnabled { get; set; }

		[JsonProperty(PropertyName = "channel_points_per_vote")]
		public int ChannelPointsPerVote { get; set; }

		[JsonProperty(PropertyName = "duration")]
		public int DurationSeconds { get; set; }
	}
	public class CreatePollResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Poll[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.WarnChatUser
{
	public class WarnChatUserResponse
	{
		[JsonProperty(PropertyName = "data")]
		public WarnedChatUser[] Data { get; protected set; }
	}
	public class WarnedChatUser
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "moderator_id")]
		public string ModeratorId { get; protected set; }

		[JsonProperty(PropertyName = "reason")]
		public string Reason { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.WarnChatUser.Request
{
	public class WarnChatUserRequest
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; set; }

		[JsonProperty(PropertyName = "reason")]
		public string Reason { get; set; } = string.Empty;

	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.UnbanRequests
{
	public class UnbanRequest
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "moderator_id")]
		public string ModeratorId { get; protected set; }

		[JsonProperty(PropertyName = "moderator_login")]
		public string ModeratorLogin { get; protected set; }

		[JsonProperty(PropertyName = "moderator_name")]
		public string ModeratorName { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "text")]
		public string Text { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public string Status { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public DateTime CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "resolved_at")]
		public DateTime? ResolvedAt { get; protected set; }

		[JsonProperty(PropertyName = "resolution_text")]
		public string ResolutionText { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.UnbanRequests.ResolveUnbanRequests
{
	public class ResolveUnbanRequestsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public UnbanRequest[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.UnbanRequests.GetUnbanRequests
{
	public class GetUnbanRequestsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public UnbanRequest[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.ShieldModeStatus
{
	public class ShieldModeStatus
	{
		[JsonProperty(PropertyName = "is_active")]
		public bool IsActive { get; protected set; }

		[JsonProperty(PropertyName = "moderator_id")]
		public string ModeratorId { get; protected set; }

		[JsonProperty(PropertyName = "moderator_login")]
		public string ModeratorLogin { get; protected set; }

		[JsonProperty(PropertyName = "moderator_name")]
		public string ModeratorName { get; protected set; }

		[JsonProperty(PropertyName = "last_activated_at")]
		public string LastActivatedAt { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.ShieldModeStatus.UpdateShieldModeStatus
{
	public class ShieldModeStatusRequest
	{
		[JsonProperty("is_active")]
		public bool IsActive { get; set; }
	}
	public class UpdateShieldModeStatusResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ShieldModeStatus[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.ShieldModeStatus.GetShieldModeStatus
{
	public class GetShieldModeStatusResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ShieldModeStatus[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.GetModerators
{
	public class GetModeratorsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Moderator[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class Moderator
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.GetModeratorEvents
{
	public class EventData
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }
	}
	public class GetModeratorEventsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ModeratorEvent[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class ModeratorEvent
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "event_type")]
		public string EventType { get; protected set; }

		[JsonProperty(PropertyName = "event_timestamp")]
		public DateTime EventTimestamp { get; protected set; }

		[JsonProperty(PropertyName = "version")]
		public string Version { get; protected set; }

		[JsonProperty(PropertyName = "event_data")]
		public EventData EventData { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.GetModeratedChannels
{
	public class GetModeratedChannelsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ModeratedChannel[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class ModeratedChannel
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.GetBannedUsers
{
	public class BannedUserEvent
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "expires_at")]
		public DateTime? ExpiresAt { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public string CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "reason")]
		public string Reason { get; protected set; }

		[JsonProperty(PropertyName = "moderator_id")]
		public string ModeratorId { get; protected set; }

		[JsonProperty(PropertyName = "moderator_login")]
		public string ModeratorLogin { get; protected set; }

		[JsonProperty(PropertyName = "moderator_name")]
		public string ModeratorName { get; protected set; }
	}
	public class GetBannedUsersResponse
	{
		[JsonProperty(PropertyName = "data")]
		public BannedUserEvent[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.GetBannedEvents
{
	public class BannedEvent
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "event_type")]
		public string EventType { get; protected set; }

		[JsonProperty(PropertyName = "event_timestamp")]
		public DateTime EventTimestamp { get; protected set; }

		[JsonProperty(PropertyName = "version")]
		public string Version { get; protected set; }

		[JsonProperty(PropertyName = "event_data")]
		public EventData EventData { get; protected set; }
	}
	public class EventData
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "expires_at")]
		public DateTime? ExpiresAt { get; protected set; }

		[JsonProperty(PropertyName = "reason")]
		public string Reason { get; protected set; }

		[JsonProperty(PropertyName = "moderator_id")]
		public string ModeratorId { get; protected set; }

		[JsonProperty(PropertyName = "moderator_login")]
		public string ModeratorLogin { get; protected set; }

		[JsonProperty(PropertyName = "moderator_name")]
		public string ModeratorName { get; protected set; }
	}
	public class GetBannedEventsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public BannedEvent[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.CheckAutoModStatus
{
	public class AutoModResult
	{
		[JsonProperty(PropertyName = "msg_id")]
		public string MsgId { get; protected set; }

		[JsonProperty(PropertyName = "is_permitted")]
		public bool IsPermitted { get; protected set; }
	}
	public class CheckAutoModStatusResponse
	{
		[JsonProperty(PropertyName = "data")]
		public AutoModResult[] Data { get; protected set; }
	}
	public class Message
	{
		[JsonProperty(PropertyName = "msg_id")]
		public string MsgId { get; set; }

		[JsonProperty(PropertyName = "msg_text")]
		public string MsgText { get; set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.CheckAutoModStatus.Request
{
	public class MessageRequest
	{
		[JsonProperty(PropertyName = "data")]
		public Message[] Messages { get; set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.BlockedTerms
{
	public class AddBlockedTermResponse
	{
		[JsonProperty(PropertyName = "data")]
		public BlockedTerm[] Data { get; protected set; }
	}
	public class BlockedTerm
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "moderator_id")]
		public string ModeratorId { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "text")]
		public string Text { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public DateTime CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "updated_at")]
		public DateTime UpdatedAt { get; protected set; }

		[JsonProperty(PropertyName = "expires_at")]
		public DateTime? ExpiresAt { get; protected set; }
	}
	public class GetBlockedTermsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public BlockedTerm[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.BanUser
{
	public class BannedUser
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public string CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "moderator_id")]
		public string ModeratorId { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "end_time")]
		public DateTime? EndTime { get; protected set; }
	}
	public class BanUser
	{
		public string UserId;

		public string Reason;
	}
	public class BanUserRequest
	{
		[JsonProperty("user_id")]
		public string UserId { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Reason { get; set; } = string.Empty;


		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public int? Duration { get; set; }
	}
	public class BanUserResponse
	{
		[JsonProperty(PropertyName = "data")]
		public BannedUser[] Data { get; protected set; }
	}
	public class TimeoutUser
	{
		public string UserId;

		public string Reason;

		public TimeSpan Duration;
	}
}
namespace TwitchLib.Api.Helix.Models.Moderation.AutomodSettings
{
	public class AutomodSettings
	{
		[JsonProperty(PropertyName = "overall_level")]
		public int? OverallLevel;

		[JsonProperty(PropertyName = "disability")]
		public int? Disability;

		[JsonProperty(PropertyName = "aggression")]
		public int? Aggression;

		[JsonProperty(PropertyName = "sexuality_sex_or_gender")]
		public int? SexualitySexOrGender;

		[JsonProperty(PropertyName = "misogyny")]
		public int? Misogyny;

		[JsonProperty(PropertyName = "bullying")]
		public int? Bullying;

		[JsonProperty(PropertyName = "swearing")]
		public int? Swearing;

		[JsonProperty(PropertyName = "race_ethnicity_or_religion")]
		public int? RaceEthnicityOrReligion;

		[JsonProperty(PropertyName = "sex_based_terms")]
		public int? SexBasedTerms;
	}
	public class AutomodSettingsResponseModel
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId;

		[JsonProperty(PropertyName = "moderator_id")]
		public string ModeratorId;

		[JsonProperty(PropertyName = "overall_level")]
		public int? OverallLevel;

		[JsonProperty(PropertyName = "disability")]
		public int? Disability;

		[JsonProperty(PropertyName = "aggression")]
		public int? Aggression;

		[JsonProperty(PropertyName = "sexuality_sex_or_gender")]
		public int? SexualitySexOrGender;

		[JsonProperty(PropertyName = "misogyny")]
		public int? Misogyny;

		[JsonProperty(PropertyName = "bullying")]
		public int? Bullying;

		[JsonProperty(PropertyName = "swearing")]
		public int? Swearing;

		[JsonProperty(PropertyName = "race_ethnicity_or_religion")]
		public int? RaceEthnicityOrReligion;

		[JsonProperty(PropertyName = "sex_based_terms")]
		public int? SexBasedTerms;
	}
	public class GetAutomodSettingsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public AutomodSettingsResponseModel[] Data { get; protected set; }
	}
	public class UpdateAutomodSettingsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public AutomodSettings[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.HypeTrain
{
	public class GetHypeTrainResponse
	{
		[JsonProperty(PropertyName = "data")]
		public HypeTrain[] HypeTrain { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class HypeTrain
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "event_type")]
		public string EventType { get; protected set; }

		[JsonProperty(PropertyName = "event_timestamp")]
		public string EventTimeStamp { get; protected set; }

		[JsonProperty(PropertyName = "version")]
		public string Version { get; protected set; }

		[JsonProperty(PropertyName = "event_data")]
		public HypeTrainEventData EventData { get; protected set; }
	}
	public class HypeTrainContribution
	{
		[JsonProperty(PropertyName = "total")]
		public int Total { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; protected set; }

		[JsonProperty(PropertyName = "user")]
		public string UserId { get; protected set; }
	}
	public class HypeTrainEventData
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "started_at")]
		public string StartedAt { get; protected set; }

		[JsonProperty(PropertyName = "expires_at")]
		public string ExpiresAt { get; protected set; }

		[JsonProperty(PropertyName = "cooldown_end_time")]
		public string CooldownEndTime { get; protected set; }

		[JsonProperty(PropertyName = "level")]
		public int Level { get; protected set; }

		[JsonProperty(PropertyName = "goal")]
		public int Goal { get; protected set; }

		[JsonProperty(PropertyName = "total")]
		public int Total { get; protected set; }

		[JsonProperty(PropertyName = "top_contribution")]
		public HypeTrainContribution[] TopContribution { get; protected set; }

		[JsonProperty(PropertyName = "last_contribution")]
		public HypeTrainContribution LastContribution { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Helpers
{
	public class ExtensionAnalytics
	{
		public string Date { get; protected set; }

		public string ExtensionName { get; protected set; }

		public string ExtensionClientId { get; protected set; }

		public int Installs { get; protected set; }

		public int Uninstalls { get; protected set; }

		public int Activations { get; protected set; }

		public int UniqueActiveChannels { get; protected set; }

		public int Renders { get; protected set; }

		public int UniqueRenders { get; protected set; }

		public int Views { get; protected set; }

		public int UniqueViewers { get; protected set; }

		public int UniqueInteractors { get; protected set; }

		public int Clicks { get; protected set; }

		public double ClicksPerInteractor { get; protected set; }

		public double InteractionRate { get; protected set; }

		public ExtensionAnalytics(string row)
		{
			string[] array = row.Split(',');
			Date = array[0];
			ExtensionName = array[1];
			ExtensionClientId = array[2];
			Installs = int.Parse(array[3]);
			Uninstalls = int.Parse(array[4]);
			Activations = int.Parse(array[5]);
			UniqueActiveChannels = int.Parse(array[6]);
			Renders = int.Parse(array[7]);
			UniqueRenders = int.Parse(array[8]);
			Views = int.Parse(array[9]);
			UniqueViewers = int.Parse(array[10]);
			UniqueInteractors = int.Parse(array[11]);
			Clicks = int.Parse(array[12]);
			ClicksPerInteractor = double.Parse(array[13]);
			InteractionRate = double.Parse(array[14]);
		}
	}
}
namespace TwitchLib.Api.Helix.Models.GuestStar
{
	public class GuestStarGuest
	{
		[JsonProperty(PropertyName = "slot_id")]
		public string SlotId { get; protected set; }

		[JsonProperty(PropertyName = "is_live")]
		public bool IsLive { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_display_name")]
		public string UserDisplayName { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "volume")]
		public int Volume { get; protected set; }

		[JsonProperty(PropertyName = "assigned_at")]
		public string AssignedAt { get; protected set; }

		[JsonProperty(PropertyName = "audio_settings")]
		public GuestStarMediaSettings AudioSettings { get; protected set; }

		[JsonProperty(PropertyName = "video_settings")]
		public GuestStarMediaSettings VideoSettings { get; protected set; }
	}
	public class GuestStarMediaSettings
	{
		[JsonProperty(PropertyName = "is_available")]
		public bool IsAvailable { get; protected set; }

		[JsonProperty(PropertyName = "is_host_enabled")]
		public bool IsHostEnabled { get; protected set; }

		[JsonProperty(PropertyName = "is_guest_enabled")]
		public bool IsGuestEnabled { get; protected set; }
	}
	public class GuestStarSession
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "guests")]
		public GuestStarGuest[] Guests { get; protected set; }
	}
	public abstract class GuestStarSettingsBase
	{
		[JsonProperty(PropertyName = "is_moderator_send_live_enabled")]
		public bool IsModeratorSendLiveEnabled { get; protected set; }

		[JsonProperty(PropertyName = "slot_count")]
		public int SlotCount { get; protected set; }

		[JsonProperty(PropertyName = "is_browser_source_audio_enabled")]
		public bool IsBrowserSourceAudioEnabled { get; protected set; }

		[JsonProperty(PropertyName = "group_layout")]
		public string GroupLayout { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.GuestStar.UpdateChannelGuestStarSettings
{
	public class UpdateChannelGuestStarSettingsRequest : GuestStarSettingsBase
	{
		[JsonProperty(PropertyName = "regenerate_browser_sources")]
		public bool RegenerateBrowserSources { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.GuestStar.GetGuestStarSession
{
	public class GetGuestStarSessionResponse
	{
		[JsonProperty(PropertyName = "data")]
		public GuestStarSession[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.GuestStar.GetGuestStarInvites
{
	public class GetGuestStarInvitesResponse
	{
		[JsonProperty(PropertyName = "data")]
		public GuestStarInvite[] Data { get; protected set; }
	}
	public class GuestStarInvite
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "invited_at")]
		public string InvitedAt { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public string Status { get; protected set; }

		[JsonProperty(PropertyName = "is_video_enabled")]
		public bool IsVideoEnabled { get; protected set; }

		[JsonProperty(PropertyName = "is_audio_enabled")]
		public bool IsAudioEnabled { get; protected set; }

		[JsonProperty(PropertyName = "is_video_available")]
		public bool IsVideoAvailable { get; protected set; }

		[JsonProperty(PropertyName = "is_audio_available")]
		public bool IsAudioAvailable { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.GuestStar.GetChannelGuestStarSettings
{
	public class GetChannelGuestStarSettingsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public GuestStarSettings[] Data { get; protected set; }
	}
	public class GuestStarSettings : GuestStarSettingsBase
	{
		[JsonProperty(PropertyName = "browser_source_token")]
		public string BrowserSourceToken { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.GuestStar.CreateGuestStarSession
{
	public class CreateGuestStarSessionResponse
	{
		[JsonProperty(PropertyName = "data")]
		public GuestStarSession[] Data { get; protected set; }
	}
	public class EndGuestStarSessionResponse
	{
		[JsonProperty(PropertyName = "data")]
		public GuestStarSession[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Goals
{
	public class CreatorGoal
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; protected set; }

		[JsonProperty(PropertyName = "description")]
		public string Description { get; protected set; }

		[JsonProperty(PropertyName = "current_amount")]
		public int CurrentAmount { get; protected set; }

		[JsonProperty(PropertyName = "target_amount")]
		public int TargetAmount { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public DateTime CreatedAt { get; protected set; }
	}
	public class GetCreatorGoalsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public CreatorGoal[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Games
{
	public class Game
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "name")]
		public string Name { get; protected set; }

		[JsonProperty(PropertyName = "box_art_url")]
		public string BoxArtUrl { get; protected set; }

		[JsonProperty(PropertyName = "igdb_id")]
		public string IgdbId { get; protected set; }
	}
	public class GetGamesResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Game[] Data { get; protected set; }
	}
	public class GetTopGamesResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Game[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Extensions.Transactions
{
	public class Cost
	{
		[JsonProperty(PropertyName = "amount")]
		public int Amount { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; protected set; }
	}
	public class GetExtensionTransactionsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Transaction[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class ProductData
	{
		[JsonProperty(PropertyName = "domain")]
		public string Domain { get; protected set; }

		[JsonProperty(PropertyName = "sku")]
		public string SKU { get; protected set; }

		[JsonProperty(PropertyName = "cost")]
		public Cost Cost { get; protected set; }

		[JsonProperty(PropertyName = "inDevelopment")]
		public bool InDevelopment { get; protected set; }

		[JsonProperty(PropertyName = "displayName")]
		public string DisplayName { get; protected set; }

		[JsonProperty(PropertyName = "expiration")]
		public string Expiration { get; protected set; }

		[JsonProperty(PropertyName = "broadcast")]
		public bool Broadcast { get; protected set; }
	}
	public class Transaction
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "timestamp")]
		public DateTime Timestamp { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "product_type")]
		public string ProductType { get; protected set; }

		[JsonProperty(PropertyName = "product_data")]
		public ProductData ProductData { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Extensions.ReleasedExtensions
{
	public class Component
	{
		[JsonProperty(PropertyName = "viewer_url")]
		public string ViewerUrl { get; protected set; }

		[JsonProperty(PropertyName = "aspect_width")]
		public int AspectWidth { get; protected set; }

		[JsonProperty(PropertyName = "aspect_height")]
		public int AspectHeight { get; protected set; }

		[JsonProperty(PropertyName = "aspect_ratio_x")]
		public int AspectRatioX { get; protected set; }

		[JsonProperty(PropertyName = "aspect_ratio_y")]
		public int AspectRatioY { get; protected set; }

		[JsonProperty(PropertyName = "autoscale")]
		public bool Autoscale { get; protected set; }

		[JsonProperty(PropertyName = "scale_pixels")]
		public int ScalePixels { get; protected set; }

		[JsonProperty(PropertyName = "target_height")]
		public int TargetHeight { get; protected set; }

		[JsonProperty(PropertyName = "size")]
		public int Size { get; protected set; }

		[JsonProperty(PropertyName = "zoom")]
		public bool Zoom { get; protected set; }

		[JsonProperty(PropertyName = "zoom_pixels")]
		public int ZoomPixels { get; protected set; }

		[JsonProperty(PropertyName = "can_link_external_content")]
		public string CanLinkExternalContent { get; protected set; }
	}
	public class GetReleasedExtensionsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ReleasedExtension[] Data { get; protected set; }
	}
	public class IconUrls
	{
		[JsonProperty(PropertyName = "100x100")]
		public string Size100x100 { get; protected set; }

		[JsonProperty(PropertyName = "24x24")]
		public string Size24x24 { get; protected set; }

		[JsonProperty(PropertyName = "300x200")]
		public string Size300x200 { get; protected set; }
	}
	public class Mobile
	{
		[JsonProperty(PropertyName = "viewer_url")]
		public string ViewerUrl { get; protected set; }
	}
	public class Panel
	{
		[JsonProperty(PropertyName = "viewer_url")]
		public string ViewerUrl { get; protected set; }

		[JsonProperty(PropertyName = "height")]
		public int Height { get; protected set; }

		[JsonProperty(PropertyName = "can_link_external_content")]
		public bool CanLinkExternalContent { get; protected set; }
	}
	public class ReleasedExtension
	{
		[JsonProperty(PropertyName = "author_name")]
		public string AuthorName { get; protected set; }

		[JsonProperty(PropertyName = "bits_enabled")]
		public bool BitsEnabled { get; protected set; }

		[JsonProperty(PropertyName = "can_install")]
		public bool CanInstall { get; protected set; }

		[JsonProperty(PropertyName = "configuration_location")]
		public string ConfigurationLocation { get; protected set; }

		[JsonProperty(PropertyName = "description")]
		public string Description { get; protected set; }

		[JsonProperty(PropertyName = "eula_tos_url")]
		public string EulaTosUrl { get; protected set; }

		[JsonProperty(PropertyName = "has_chat_support")]
		public bool HasChatSupport { get; protected set; }

		[JsonProperty(PropertyName = "icon_url")]
		public string IconUrl { get; protected set; }

		[JsonProperty(PropertyName = "icon_urls")]
		public IconUrls IconUrls { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "name")]
		public string Name { get; protected set; }

		[JsonProperty(PropertyName = "privacy_policy_url")]
		public string PrivacyPolicyUrl { get; protected set; }

		[JsonProperty(PropertyName = "request_identity_link")]
		public bool RequestIdentityLink { get; protected set; }

		[JsonProperty(PropertyName = "screenshot_urls")]
		public string[] ScreenshotUrls { get; protected set; }

		[JsonProperty(PropertyName = "state")]
		public ExtensionState State { get; protected set; }

		[JsonProperty(PropertyName = "subscriptions_support_level")]
		public string SubscriptionsSupportLevel { get; protected set; }

		[JsonProperty(PropertyName = "summary")]
		public string Summary { get; protected set; }

		[JsonProperty(PropertyName = "support_email")]
		public string SupportEmail { get; protected set; }

		[JsonProperty(PropertyName = "version")]
		public string Version { get; protected set; }

		[JsonProperty(PropertyName = "viewer_summary")]
		public string ViewerSummary { get; protected set; }

		[JsonProperty(PropertyName = "views")]
		public Views Views { get; protected set; }

		[JsonProperty(PropertyName = "allowlisted_config_urls")]
		public string[] AllowlistedConfigUrls { get; protected set; }

		[JsonProperty(PropertyName = "allowlisted_panel_urls")]
		public string[] AllowlistedPanelUrls { get; protected set; }
	}
	public class VideoOverlay
	{
		[JsonProperty(PropertyName = "viewer_url")]
		public string ViewerUrl { get; protected set; }

		[JsonProperty(PropertyName = "can_link_external_content")]
		public bool CanLinkExternalContent { get; protected set; }
	}
	public class Views
	{
		[JsonProperty(PropertyName = "mobile")]
		public Mobile Mobile { get; protected set; }

		[JsonProperty(PropertyName = "panel")]
		public Panel Panel { get; protected set; }

		[JsonProperty(PropertyName = "video_overlay")]
		public VideoOverlay VideoOverlay { get; protected set; }

		[JsonProperty(PropertyName = "component")]
		public Component Component { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Extensions.LiveChannels
{
	public class GetExtensionLiveChannelsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public LiveChannel[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
	public class LiveChannel
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "game_name")]
		public string GameName { get; protected set; }

		[JsonProperty(PropertyName = "game_id")]
		public string GameId { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.EventSub
{
	public class CreateEventSubSubscriptionResponse
	{
		[JsonProperty(PropertyName = "data")]
		public EventSubSubscription[] Subscriptions { get; protected set; }

		[JsonProperty(PropertyName = "total")]
		public int Total { get; protected set; }

		[JsonProperty(PropertyName = "total_cost")]
		public int TotalCost { get; protected set; }

		[JsonProperty(PropertyName = "max_total_cost")]
		public int MaxTotalCost { get; protected set; }
	}
	public class EventSubSubscription
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public string Status { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; protected set; }

		[JsonProperty(PropertyName = "version")]
		public string Version { get; protected set; }

		[JsonProperty(PropertyName = "condition")]
		public Dictionary<string, string> Condition { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public string CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "transport")]
		public EventSubTransport Transport { get; protected set; }

		[JsonProperty(PropertyName = "cost")]
		public int Cost { get; protected set; }
	}
	public class EventSubTransport
	{
		[JsonProperty(PropertyName = "method")]
		public string Method { get; protected set; }

		[JsonProperty(PropertyName = "callback")]
		public string Callback { get; protected set; }

		[JsonProperty(PropertyName = "session_id")]
		public string SessionId { get; protected set; }

		[JsonProperty(PropertyName = "connected_at")]
		public string DisconnectedAt { get; protected set; }
	}
	public class GetEventSubSubscriptionsResponse
	{
		[JsonProperty(PropertyName = "total")]
		public int Total { get; protected set; }

		[JsonProperty(PropertyName = "data")]
		public EventSubSubscription[] Subscriptions { get; protected set; }

		[JsonProperty(PropertyName = "total_cost")]
		public int TotalCost { get; protected set; }

		[JsonProperty(PropertyName = "max_total_cost")]
		public int MaxTotalCost { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.EventSub.Conduits
{
	public class Conduit
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "shard_count")]
		public int ShardCount { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.EventSub.Conduits.UpdateConduits
{
	public class UpdateConduitsRequest
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; set; }

		[JsonProperty(PropertyName = "shard_count")]
		public int ShardCount { get; set; }
	}
	public class UpdateConduitsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Conduit[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.EventSub.Conduits.Shards
{
	public class Shard
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public string Status { get; protected set; }

		[JsonProperty(PropertyName = "transport")]
		public Transport Transport { get; set; }
	}
	public class Transport
	{
		[JsonProperty(PropertyName = "method")]
		public string Method { get; protected set; }

		[JsonProperty(PropertyName = "callback")]
		public string Callback { get; protected set; }

		[JsonProperty(PropertyName = "session_id")]
		public string SessionId { get; protected set; }

		[JsonProperty(PropertyName = "connected_at")]
		public string ConnectedAt { get; protected set; }

		[JsonProperty(PropertyName = "disconnected_at")]
		public string DisconnectedAt { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.EventSub.Conduits.Shards.UpdateConduitShards
{
	public class Error
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "message")]
		public string Message { get; protected set; }

		[JsonProperty(PropertyName = "code")]
		public string Code { get; protected set; }
	}
	public class ShardUpdate
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; set; }

		[JsonProperty(PropertyName = "transport")]
		public TransportUpdate Transport { get; set; }
	}
	public class TransportUpdate
	{
		[JsonProperty(PropertyName = "method")]
		public string Method { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Callback { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Secret { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string SessionId { get; set; }
	}
	public class UpdateConduitShardsRequest
	{
		[JsonProperty(PropertyName = "conduit_id")]
		public string ConduitId { get; set; }

		[JsonProperty(PropertyName = "shards")]
		public ShardUpdate[] Shards { get; set; }
	}
	public class UpdateConduitShardsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Shard[] Shards { get; protected set; }

		[JsonProperty(PropertyName = "errors")]
		public Error[] Errors { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.EventSub.Conduits.Shards.GetConduitShards
{
	public class GetConduitShardsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Shard[] Shards { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.EventSub.Conduits.GetConduits
{
	public class GetConduitsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Conduit[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.EventSub.Conduits.CreateConduits
{
	public class CreateConduitsRequest
	{
		[JsonProperty(PropertyName = "shard_count")]
		public int ShardCount { get; set; }
	}
	public class CreateConduitsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Conduit[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Entitlements
{
	public class Status
	{
		[JsonProperty(PropertyName = "code")]
		public string Code { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public CodeStatusEnum StatusEnum { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Entitlements.UpdateDropsEntitlements
{
	public class DropEntitlementUpdate
	{
		[JsonProperty(PropertyName = "status")]
		public DropEntitlementUpdateStatus Status { get; protected set; }

		[JsonProperty(PropertyName = "ids")]
		public string[] Ids { get; protected set; }
	}
	public class UpdateDropsEntitlementsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public DropEntitlementUpdate[] DropEntitlementUpdates { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Entitlements.GetDropsEntitlements
{
	public class DropsEntitlement
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "benefit_id")]
		public string BenefitId { get; protected set; }

		[JsonProperty(PropertyName = "timestamp")]
		public DateTime Timestamp { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "game_id")]
		public string GameId { get; protected set; }

		[JsonProperty(PropertyName = "fulfillment_status")]
		public FulfillmentStatus FulfillmentStatus { get; protected set; }

		[JsonProperty(PropertyName = "last_updated")]
		public DateTime LastUpdated { get; protected set; }
	}
	public class GetDropsEntitlementsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public DropsEntitlement[] DropEntitlements { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.ContentClassificationLabels
{
	public class ContentClassificationLabel
	{
		[JsonProperty(PropertyName = "id")]
		public string ID { get; set; }

		[JsonProperty(PropertyName = "description")]
		public string Description { get; set; }

		[JsonProperty(PropertyName = "name")]
		public string Name { get; set; }
	}
	public class GetContentClassificationLabelsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ContentClassificationLabel[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Common
{
	public class DateRange
	{
		[JsonProperty(PropertyName = "started_at")]
		public DateTime StartedAt { get; protected set; }

		[JsonProperty(PropertyName = "ended_at")]
		public DateTime EndedAt { get; protected set; }
	}
	public class Pagination
	{
		[JsonProperty(PropertyName = "cursor")]
		public string Cursor { get; protected set; }
	}
	public class Tag
	{
		[JsonProperty(PropertyName = "tag_id")]
		public string TagId { get; protected set; }

		[JsonProperty(PropertyName = "is_auto")]
		public bool IsAuto { get; protected set; }

		[JsonProperty(PropertyName = "localization_names")]
		public Dictionary<string, string> LocalizationNames { get; protected set; }

		[JsonProperty(PropertyName = "localization_descriptions")]
		public Dictionary<string, string> LocalizationDescriptions { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Clips.GetClips
{
	public class Clip
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "url")]
		public string Url { get; protected set; }

		[JsonProperty(PropertyName = "embed_url")]
		public string EmbedUrl { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "creator_id")]
		public string CreatorId { get; protected set; }

		[JsonProperty(PropertyName = "creator_name")]
		public string CreatorName { get; protected set; }

		[JsonProperty(PropertyName = "video_id")]
		public string VideoId { get; protected set; }

		[JsonProperty(PropertyName = "game_id")]
		public string GameId { get; protected set; }

		[JsonProperty(PropertyName = "language")]
		public string Language { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "view_count")]
		public int ViewCount { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public string CreatedAt { get; protected set; }

		[JsonProperty(PropertyName = "thumbnail_url")]
		public string ThumbnailUrl { get; protected set; }

		[JsonProperty(PropertyName = "duration")]
		public float Duration { get; protected set; }

		[JsonProperty(PropertyName = "vod_offset")]
		public int VodOffset { get; protected set; }

		[JsonProperty(PropertyName = "is_featured")]
		public bool IsFeatured { get; protected set; }
	}
	public class GetClipsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public Clip[] Clips { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Clips.CreateClip
{
	public class CreatedClip
	{
		[JsonProperty(PropertyName = "edit_url")]
		public string EditUrl { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }
	}
	public class CreatedClipResponse
	{
		[JsonProperty(PropertyName = "data")]
		public CreatedClip[] CreatedClips { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat
{
	public class AnnouncementColors
	{
		public string Value { get; private set; }

		public static AnnouncementColors Blue => new AnnouncementColors("blue");

		public static AnnouncementColors Green => new AnnouncementColors("green");

		public static AnnouncementColors Orange => new AnnouncementColors("orange");

		public static AnnouncementColors Purple => new AnnouncementColors("purple");

		public static AnnouncementColors Primary => new AnnouncementColors("primary");

		private AnnouncementColors(string value)
		{
			Value = value;
		}
	}
	public class UserColors
	{
		public string Value { get; private set; }

		public static UserColors Blue => new UserColors("blue");

		public static UserColors BlueVoilet => new UserColors("blue_violet");

		public static UserColors CadetBlue => new UserColors("cadet_blue");

		public static UserColors Chocolate => new UserColors("chocolate");

		public static UserColors Coral => new UserColors("coral");

		public static UserColors DodgerBlue => new UserColors("dodger_blue");

		public static UserColors Firebrick => new UserColors("firebrick");

		public static UserColors GoldenRod => new UserColors("golden_rod");

		public static UserColors HotPink => new UserColors("hot_pink");

		public static UserColors OrangeRed => new UserColors("orange_red");

		public static UserColors Red => new UserColors("red");

		public static UserColors SeaGreen => new UserColors("sea_green");

		public static UserColors SpringGreen => new UserColors("spring_green");

		public static UserColors YellowGreen => new UserColors("yellow_green");

		private UserColors(string value)
		{
			Value = value;
		}
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.GetUserChatColor
{
	public class GetUserChatColorResponse
	{
		[JsonProperty(PropertyName = "data")]
		public UserChatColorResponseModel[] Data { get; protected set; }
	}
	public class UserChatColorResponseModel
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "color")]
		public string Color { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.GetChatters
{
	public class Chatter
	{
		[JsonProperty("user_id")]
		public string UserId { get; protected set; }

		[JsonProperty("user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty("user_name")]
		public string UserName { get; protected set; }
	}
	public class GetChattersResponse
	{
		[JsonProperty("data")]
		public Chatter[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }

		[JsonProperty("total")]
		public int Total { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.Emotes
{
	public class ChannelEmote : Emote
	{
		[JsonProperty("images")]
		public EmoteImages Images { get; protected set; }

		[JsonProperty("tier")]
		public string Tier { get; protected set; }

		[JsonProperty("emote_type")]
		public string EmoteType { get; protected set; }

		[JsonProperty("emote_set_id")]
		public string EmoteSetId { get; protected set; }
	}
	public abstract class Emote
	{
		[JsonProperty("id")]
		public string Id { get; protected set; }

		[JsonProperty("name")]
		public string Name { get; protected set; }

		[JsonProperty("format")]
		public string[] Format { get; protected set; }

		[JsonProperty("scale")]
		public string[] Scale { get; protected set; }

		[JsonProperty("theme_mode")]
		public string[] ThemeMode { get; protected set; }
	}
	public class EmoteImages
	{
		[JsonProperty("url_1x")]
		public string Url1X { get; protected set; }

		[JsonProperty("url_2x")]
		public string Url2X { get; protected set; }

		[JsonProperty("url_4x")]
		public string Url4X { get; protected set; }
	}
	public class EmoteSet : Emote
	{
		[JsonProperty("emote_type")]
		public string EmoteType { get; protected set; }

		[JsonProperty("emote_set_id")]
		public string EmoteSetId { get; protected set; }

		[JsonProperty("images")]
		public EmoteImages Images { get; protected set; }

		[JsonProperty("owner_id")]
		public string OwnerId { get; protected set; }
	}
	public class GlobalEmote : Emote
	{
		[JsonProperty("images")]
		public EmoteImages Images { get; protected set; }
	}
	public class UserEmote : Emote
	{
		[JsonProperty("emote_type")]
		public string EmoteType { get; protected set; }

		[JsonProperty("emote_set_id")]
		public string EmoteSetId { get; protected set; }

		[JsonProperty("owner_id")]
		public string OwnerId { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.Emotes.GetUserEmotes
{
	public class GetUserEmotesResponse
	{
		[JsonProperty("data")]
		public UserEmote[] Data { get; protected set; }

		[JsonProperty("template")]
		public string Template { get; protected set; }

		[JsonProperty("pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.Emotes.GetGlobalEmotes
{
	public class GetGlobalEmotesResponse
	{
		[JsonProperty("data")]
		public GlobalEmote[] GlobalEmotes { get; protected set; }

		[JsonProperty("template")]
		public string Template { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.Emotes.GetEmoteSets
{
	public class GetEmoteSetsResponse
	{
		[JsonProperty("data")]
		public EmoteSet[] EmoteSets { get; protected set; }

		[JsonProperty("template")]
		public string Template { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.Emotes.GetChannelEmotes
{
	public class GetChannelEmotesResponse
	{
		[JsonProperty("data")]
		public ChannelEmote[] ChannelEmotes { get; protected set; }

		[JsonProperty("template")]
		public string Template { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.ChatSettings
{
	public class ChatSettings
	{
		[JsonProperty(PropertyName = "emote_mode")]
		public bool? EmoteMode;

		[JsonProperty(PropertyName = "follower_mode")]
		public bool? FollowerMode;

		[JsonProperty(PropertyName = "follower_mode_duration")]
		public int? FollowerModeDuration;

		[JsonProperty(PropertyName = "non_moderator_chat_delay")]
		public bool? NonModeratorChatDelay;

		[JsonProperty(PropertyName = "non_moderator_chat_delay_duration")]
		public int? NonModeratorChatDelayDuration;

		[JsonProperty(PropertyName = "slow_mode")]
		public bool? SlowMode;

		[JsonProperty(PropertyName = "slow_mode_wait_time")]
		public int? SlowModeWaitTime;

		[JsonProperty(PropertyName = "subscriber_mode")]
		public bool? SubscriberMode;

		[JsonProperty(PropertyName = "unique_chat_mode")]
		public bool? UniqueChatMode;
	}
	public class ChatSettingsResponseModel
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "emote_mode")]
		public bool EmoteMode { get; protected set; }

		[JsonProperty(PropertyName = "follower_mode")]
		public bool FollowerMode { get; protected set; }

		[JsonProperty(PropertyName = "follower_mode_duration")]
		public int? FollowerModeDuration { get; protected set; }

		[JsonProperty(PropertyName = "moderator_id")]
		public bool ModeratorId { get; protected set; }

		[JsonProperty(PropertyName = "non_moderator_chat_delay")]
		public bool NonModeratorChatDelay { get; protected set; }

		[JsonProperty(PropertyName = "non_moderator_chat_delay_duration")]
		public int? NonModeratorChatDelayDuration { get; protected set; }

		[JsonProperty(PropertyName = "slow_mode")]
		public bool SlowMode { get; protected set; }

		[JsonProperty(PropertyName = "slow_mode_wait_time")]
		public int? SlowModeWaitDuration { get; protected set; }

		[JsonProperty(PropertyName = "subscriber_mode")]
		public bool SubscriberMode { get; protected set; }

		[JsonProperty(PropertyName = "unique_chat_mode")]
		public bool UniqueChatMode { get; protected set; }
	}
	public class GetChatSettingsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ChatSettingsResponseModel[] Data { get; protected set; }
	}
	public class UpdateChatSettingsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public UpdateChatSettingsResponseModel[] Data { get; protected set; }
	}
	public class UpdateChatSettingsResponseModel
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "emote_mode")]
		public bool EmoteMode { get; protected set; }

		[JsonProperty(PropertyName = "follower_mode")]
		public bool FollowerMode { get; protected set; }

		[JsonProperty(PropertyName = "follower_mode_duration")]
		public int? FollowerModeDuration { get; protected set; }

		[JsonProperty(PropertyName = "moderator_id")]
		public string ModeratorId { get; protected set; }

		[JsonProperty(PropertyName = "non_moderator_chat_delay")]
		public bool NonModeratorChatDelay { get; protected set; }

		[JsonProperty(PropertyName = "non_moderator_chat_delay_duration")]
		public int? NonModeratorChatDelayDuration { get; protected set; }

		[JsonProperty(PropertyName = "slow_mode")]
		public bool SlowMode { get; protected set; }

		[JsonProperty(PropertyName = "slow_mode_wait_time")]
		public int? SlowModeWaitDuration { get; protected set; }

		[JsonProperty(PropertyName = "subscriber_mode")]
		public bool SubscriberMode { get; protected set; }

		[JsonProperty(PropertyName = "unique_chat_mode")]
		public bool UniqueChatMode { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.Badges
{
	public class BadgeEmoteSet
	{
		[JsonProperty(PropertyName = "set_id")]
		public string SetId { get; protected set; }

		[JsonProperty(PropertyName = "versions")]
		public BadgeVersion[] Versions { get; protected set; }
	}
	public class BadgeVersion
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "image_url_1x")]
		public string ImageUrl1x { get; protected set; }

		[JsonProperty(PropertyName = "image_url_2x")]
		public string ImageUrl2x { get; protected set; }

		[JsonProperty(PropertyName = "image_url_4x")]
		public string ImageUrl4x { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "description")]
		public string Description { get; protected set; }

		[JsonProperty(PropertyName = "click_action")]
		public string ClickAction { get; protected set; }

		[JsonProperty(PropertyName = "click_url")]
		public string ClickUrl { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.Badges.GetGlobalChatBadges
{
	public class GetGlobalChatBadgesResponse
	{
		[JsonProperty(PropertyName = "data")]
		public BadgeEmoteSet[] EmoteSet { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Chat.Badges.GetChannelChatBadges
{
	public class GetChannelChatBadgesResponse
	{
		[JsonProperty(PropertyName = "data")]
		public BadgeEmoteSet[] EmoteSet { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Charity
{
	public class Amount
	{
		[JsonProperty(PropertyName = "value")]
		public int? Value { get; protected set; }

		[JsonProperty(PropertyName = "decimal_places")]
		public int? DecimalPlaces { get; protected set; }

		[JsonProperty(PropertyName = "currency")]
		public string Currency { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Charity.GetCharityCampaign
{
	public class CharityCampaignResponseModel
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "charity_name")]
		public string CharityName { get; protected set; }

		[JsonProperty(PropertyName = "charity_description")]
		public string CharityDescription { get; protected set; }

		[JsonProperty(PropertyName = "charity_logo")]
		public string CharityLogo { get; protected set; }

		[JsonProperty(PropertyName = "charity_website")]
		public string CharityWebsite { get; protected set; }

		[JsonProperty(PropertyName = "current_amount")]
		public Amount CurrentAmount { get; protected set; }

		[JsonProperty(PropertyName = "target_amount")]
		public Amount TargetAmount { get; protected set; }
	}
	public class GetCharityCampaignResponse
	{
		[JsonProperty(PropertyName = "data")]
		public CharityCampaignResponseModel[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Charity.GetCharityCampaignDonations
{
	public class CharityCampaignDonationsResponseModel
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "campaign_id")]
		public string CampaignId { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "amount")]
		public Amount Amount { get; protected set; }
	}
	public class GetCharityCampaignDonationsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public CharityCampaignDonationsResponseModel[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.StartCommercial
{
	public class StartCommercialRequest
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; set; }

		[JsonProperty(PropertyName = "length")]
		public int Length { get; set; }
	}
	public class StartCommercialResponse
	{
		[JsonProperty(PropertyName = "length")]
		public int Length { get; protected set; }

		[JsonProperty(PropertyName = "message")]
		public string Message { get; protected set; }

		[JsonProperty(PropertyName = "retry_after")]
		public int RetryAfter { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.SnoozeNextAd
{
	public class SnoozeNextAd
	{
		[JsonProperty(PropertyName = "snooze_count")]
		public int SnoozeCount { get; protected set; }

		[JsonProperty(PropertyName = "snooze_refresh_at")]
		public string SnoozeRefreshAt { get; protected set; }

		[JsonProperty(PropertyName = "next_ad_at")]
		public string NextAdAt { get; protected set; }
	}
	public class SnoozeNextAdResponse
	{
		[JsonProperty(PropertyName = "data")]
		public SnoozeNextAd[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.SendChatMessage
{
	public class ChatMessageInfo
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string MessageId { get; set; } = string.Empty;


		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public bool IsSent { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public DropReason DropReason { get; set; }
	}
	public class DropReason
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Code { get; set; } = string.Empty;


		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Message { get; set; } = string.Empty;

	}
	public class SendChatMessageResponse
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public ChatMessageInfo[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.ModifyChannelInformation
{
	public class ContentClassificationLabel
	{
		[JsonConverter(typeof(StringEnumConverter))]
		[JsonProperty(PropertyName = "id")]
		public ContentClassificationLabelEnum Id { get; set; }

		[JsonProperty(PropertyName = "is_enabled")]
		public bool IsEnabled { get; set; }
	}
	[JsonObject(/*Could not decode attribute arguments.*/)]
	public class ModifyChannelInformationRequest
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string GameId { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string BroadcasterLanguage { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Title { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public int? Delay { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string[] Tags { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public ContentClassificationLabel[] ContentClassificationLabels { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public bool IsBrandedContent { get; set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.GetFollowedChannels
{
	public class FollowedChannel
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "followed_at")]
		public string FollowedAt { get; protected set; }
	}
	public class GetFollowedChannelsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public FollowedChannel[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }

		[JsonProperty(PropertyName = "total")]
		public int Total { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.GetChannelVIPs
{
	public class ChannelVIPsResponseModel
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }
	}
	public class GetChannelVIPsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ChannelVIPsResponseModel[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.GetChannelInformation
{
	public class ChannelInformation
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "game_id")]
		public string GameId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_language")]
		public string BroadcasterLanguage { get; protected set; }

		[JsonProperty(PropertyName = "game_name")]
		public string GameName { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "delay")]
		public int Delay { get; protected set; }

		[JsonProperty(PropertyName = "tags")]
		public string[] Tags { get; protected set; }

		[JsonProperty(PropertyName = "content_classification_labels")]
		public string[] ContentClassificationLabels { get; protected set; }

		[JsonProperty(PropertyName = "is_branded_content")]
		public bool IsBrandedContent { get; protected set; }
	}
	public class GetChannelInformationResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ChannelInformation[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.GetChannelFollowers
{
	public class ChannelFollower
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_login")]
		public string UserLogin { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "followed_at")]
		public string FollowedAt { get; protected set; }
	}
	public class GetChannelFollowersResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ChannelFollower[] Data { get; protected set; }

		[JsonProperty(PropertyName = "pagination")]
		public Pagination Pagination { get; protected set; }

		[JsonProperty(PropertyName = "total")]
		public int Total { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.GetChannelEditors
{
	public class ChannelEditor
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "created_at")]
		public DateTime CreatedAt { get; protected set; }
	}
	public class GetChannelEditorsResponse
	{
		[JsonProperty(PropertyName = "data")]
		public ChannelEditor[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.Channels.GetAdSchedule
{
	public class AdSchedule
	{
		[JsonProperty(PropertyName = "snooze_count")]
		public int SnoozeCount { get; protected set; }

		[JsonProperty(PropertyName = "snooze_refresh_at")]
		public string SnoozeRefreshAt { get; protected set; }

		[JsonProperty(PropertyName = "next_ad_at")]
		public string NextAdAt { get; protected set; }

		[JsonProperty(PropertyName = "duration")]
		public int Duration { get; protected set; }

		[JsonProperty(PropertyName = "last_ad_at")]
		public string LastAdAt { get; protected set; }

		[JsonProperty(PropertyName = "preroll_free_time")]
		public int PrerollFreeTime { get; protected set; }
	}
	public class GetAdScheduleResponse
	{
		[JsonProperty(PropertyName = "data")]
		public AdSchedule[] Data { get; protected set; }
	}
}
namespace TwitchLib.Api.Helix.Models.ChannelPoints
{
	public class CustomReward
	{
		[JsonProperty(PropertyName = "broadcaster_id")]
		public string BroadcasterId { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_login")]
		public string BroadcasterLogin { get; protected set; }

		[JsonProperty(PropertyName = "broadcaster_name")]
		public string BroadcasterName { get; protected set; }

		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "prompt")]
		public string Prompt { get; protected set; }

		[JsonProperty(PropertyName = "cost")]
		public int Cost { get; protected set; }

		[JsonProperty(PropertyName = "image")]
		public Image Image { get; protected set; }

		[JsonProperty(PropertyName = "default_image")]
		public DefaultImage DefaultImage { get; protected set; }

		[JsonProperty(PropertyName = "background_color")]
		public string BackgroundColor { get; protected set; }

		[JsonProperty(PropertyName = "is_enabled")]
		public bool IsEnabled { get; protected set; }

		[JsonProperty(PropertyName = "is_user_input_required")]
		public bool IsUserInpu

TwitchLib.Client.dll

Decompiled a month ago
#define DEBUG
using System;
using System.CodeDom.Compiler;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using TwitchLib.Client.Enums;
using TwitchLib.Client.Enums.Internal;
using TwitchLib.Client.Events;
using TwitchLib.Client.Exceptions;
using TwitchLib.Client.Extensions;
using TwitchLib.Client.Interfaces;
using TwitchLib.Client.Internal;
using TwitchLib.Client.Manager;
using TwitchLib.Client.Models;
using TwitchLib.Client.Models.Interfaces;
using TwitchLib.Client.Models.Internal;
using TwitchLib.Client.Parsing;
using TwitchLib.Client.Throttling;
using TwitchLib.Communication.Clients;
using TwitchLib.Communication.Events;
using TwitchLib.Communication.Interfaces;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: InternalsVisibleTo("TwitchLib.Client.Test")]
[assembly: InternalsVisibleTo("TwitchLib.Client.Benchmark")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2023")]
[assembly: AssemblyDescription("Client component of TwitchLib. This component allows you to access Twitch chat and whispers, as well as the events that are sent over this connection.")]
[assembly: AssemblyFileVersion("4.0.0")]
[assembly: AssemblyInformationalVersion("4.0.0+5ef35d539836f8bcd29bd836a23b9e853020acfa")]
[assembly: AssemblyProduct("TwitchLib.Client")]
[assembly: AssemblyTitle("TwitchLib.Client")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.Client")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("4.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TwitchLib.Client
{
	public class TwitchClient : ITwitchClient
	{
		private IClient? _client;

		private readonly ISendOptions _sendOptions;

		private ThrottlingService? _throttling;

		private readonly Queue<JoinedChannel> _joinChannelQueue = new Queue<JoinedChannel>();

		private readonly ILogger<TwitchClient>? _logger;

		private readonly ILoggerFactory? _loggerFactory;

		private readonly ClientProtocol _protocol;

		private bool _currentlyJoiningChannels;

		private System.Timers.Timer? _joinTimer;

		private readonly List<KeyValuePair<string, DateTime>> _awaitingJoins = new List<KeyValuePair<string, DateTime>>();

		private readonly JoinedChannelManager _joinedChannelManager = new JoinedChannelManager();

		private readonly HashSet<string> _hasSeenJoinedChannels = new HashSet<string>();

		private string _lastMessageSent = string.Empty;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnAnnouncementArgs>? m_OnAnnouncement;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnConnectedEventArgs>? m_OnConnected;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnJoinedChannelArgs>? m_OnJoinedChannel;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnIncorrectLoginArgs>? m_OnIncorrectLogin;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnChannelStateChangedArgs>? m_OnChannelStateChanged;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserStateChangedArgs>? m_OnUserStateChanged;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnMessageReceivedArgs>? m_OnMessageReceived;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnWhisperReceivedArgs>? m_OnWhisperReceived;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnMessageSentArgs>? m_OnMessageSent;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnChatCommandReceivedArgs>? m_OnChatCommandReceived;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnWhisperCommandReceivedArgs>? m_OnWhisperCommandReceived;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserJoinedArgs>? m_OnUserJoined;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnMessageClearedArgs>? m_OnMessageCleared;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnNewSubscriberArgs>? m_OnNewSubscriber;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnReSubscriberArgs>? m_OnReSubscriber;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnPrimePaidSubscriberArgs>? m_OnPrimePaidSubscriber;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnExistingUsersDetectedArgs>? m_OnExistingUsersDetected;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserLeftArgs>? m_OnUserLeft;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnDisconnectedArgs>? m_OnDisconnected;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnConnectionErrorArgs>? m_OnConnectionError;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnChatClearedArgs>? m_OnChatCleared;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserTimedoutArgs>? m_OnUserTimedout;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnLeftChannelArgs>? m_OnLeftChannel;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserBannedArgs>? m_OnUserBanned;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnSendReceiveDataArgs>? m_OnSendReceiveData;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnRaidNotificationArgs>? m_OnRaidNotification;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnGiftedSubscriptionArgs>? m_OnGiftedSubscription;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnCommunitySubscriptionArgs>? m_OnCommunitySubscription;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnContinuedGiftedSubscriptionArgs>? m_OnContinuedGiftedSubscription;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnMessageThrottledArgs>? m_OnMessageThrottled;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnErrorEventArgs>? m_OnError;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnConnectedEventArgs>? m_OnReconnected;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnRequiresVerifiedEmail;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnRequiresVerifiedPhoneNumber;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnRateLimit;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnDuplicate;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnBannedEmailAlias;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnSelfRaidError;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnNoPermissionError;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnRaidedChannelIsMatureAudience;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs>? m_OnFailureToReceiveJoinConfirmation;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnFollowersOnly;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnSubsOnly;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnEmoteOnly;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnSuspended;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnBanned;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnSlowMode;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs>? m_OnR9kMode;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserIntroArgs>? m_OnUserIntro;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUnaccountedForArgs>? m_OnUnaccountedFor;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnAnonGiftPaidUpgradeArgs>? m_OnAnonGiftPaidUpgrade;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUnraidNotificationArgs>? m_OnUnraidNotification;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnRitualArgs>? m_OnRitual;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnBitsBadgeTierArgs>? m_OnBitsBadgeTier;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnCommunityPayForwardArgs>? m_OnCommunityPayForward;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnStandardPayForwardArgs>? m_OnStandardPayForward;

		private static readonly string[] NewLineSeparator = new string[1] { "\r\n" };

		public ICollection<char> ChatCommandIdentifiers { get; } = new HashSet<char>();


		public ICollection<char> WhisperCommandIdentifiers { get; } = new HashSet<char>();


		public bool IsInitialized => _client != null;

		public IReadOnlyList<JoinedChannel> JoinedChannels => _joinedChannelManager.GetJoinedChannels();

		public string TwitchUsername
		{
			get
			{
				ConnectionCredentials? connectionCredentials = ConnectionCredentials;
				return ((connectionCredentials != null) ? connectionCredentials.TwitchUsername : null) ?? string.Empty;
			}
		}

		public WhisperMessage? PreviousWhisper { get; private set; }

		public bool IsConnected => IsInitialized && _client.IsConnected;

		public MessageEmoteCollection ChannelEmotes { get; } = new MessageEmoteCollection();


		public bool DisableAutoPong { get; set; } = false;


		public bool WillReplaceEmotes { get; set; } = false;


		public string ReplacedEmotesPrefix { get; set; } = "";


		public string ReplacedEmotesSuffix { get; set; } = "";


		public ConnectionCredentials? ConnectionCredentials { get; private set; }

		public event AsyncEventHandler<OnAnnouncementArgs>? OnAnnouncement
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnAnnouncementArgs> val = this.m_OnAnnouncement;
				AsyncEventHandler<OnAnnouncementArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnAnnouncementArgs> value2 = (AsyncEventHandler<OnAnnouncementArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnAnnouncement, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnAnnouncementArgs> val = this.m_OnAnnouncement;
				AsyncEventHandler<OnAnnouncementArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnAnnouncementArgs> value2 = (AsyncEventHandler<OnAnnouncementArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnAnnouncement, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnConnectedEventArgs>? OnConnected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnConnectedEventArgs> val = this.m_OnConnected;
				AsyncEventHandler<OnConnectedEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectedEventArgs> value2 = (AsyncEventHandler<OnConnectedEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnConnectedEventArgs> val = this.m_OnConnected;
				AsyncEventHandler<OnConnectedEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectedEventArgs> value2 = (AsyncEventHandler<OnConnectedEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnected, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnJoinedChannelArgs>? OnJoinedChannel
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnJoinedChannelArgs> val = this.m_OnJoinedChannel;
				AsyncEventHandler<OnJoinedChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnJoinedChannelArgs> value2 = (AsyncEventHandler<OnJoinedChannelArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnJoinedChannel, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnJoinedChannelArgs> val = this.m_OnJoinedChannel;
				AsyncEventHandler<OnJoinedChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnJoinedChannelArgs> value2 = (AsyncEventHandler<OnJoinedChannelArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnJoinedChannel, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnIncorrectLoginArgs>? OnIncorrectLogin
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnIncorrectLoginArgs> val = this.m_OnIncorrectLogin;
				AsyncEventHandler<OnIncorrectLoginArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnIncorrectLoginArgs> value2 = (AsyncEventHandler<OnIncorrectLoginArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnIncorrectLogin, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnIncorrectLoginArgs> val = this.m_OnIncorrectLogin;
				AsyncEventHandler<OnIncorrectLoginArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnIncorrectLoginArgs> value2 = (AsyncEventHandler<OnIncorrectLoginArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnIncorrectLogin, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnChannelStateChangedArgs>? OnChannelStateChanged
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnChannelStateChangedArgs> val = this.m_OnChannelStateChanged;
				AsyncEventHandler<OnChannelStateChangedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChannelStateChangedArgs> value2 = (AsyncEventHandler<OnChannelStateChangedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChannelStateChanged, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnChannelStateChangedArgs> val = this.m_OnChannelStateChanged;
				AsyncEventHandler<OnChannelStateChangedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChannelStateChangedArgs> value2 = (AsyncEventHandler<OnChannelStateChangedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChannelStateChanged, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserStateChangedArgs>? OnUserStateChanged
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserStateChangedArgs> val = this.m_OnUserStateChanged;
				AsyncEventHandler<OnUserStateChangedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserStateChangedArgs> value2 = (AsyncEventHandler<OnUserStateChangedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserStateChanged, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserStateChangedArgs> val = this.m_OnUserStateChanged;
				AsyncEventHandler<OnUserStateChangedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserStateChangedArgs> value2 = (AsyncEventHandler<OnUserStateChangedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserStateChanged, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnMessageReceivedArgs>? OnMessageReceived
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnMessageReceivedArgs> val = this.m_OnMessageReceived;
				AsyncEventHandler<OnMessageReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageReceivedArgs> value2 = (AsyncEventHandler<OnMessageReceivedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageReceived, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnMessageReceivedArgs> val = this.m_OnMessageReceived;
				AsyncEventHandler<OnMessageReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageReceivedArgs> value2 = (AsyncEventHandler<OnMessageReceivedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageReceived, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnWhisperReceivedArgs>? OnWhisperReceived
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnWhisperReceivedArgs> val = this.m_OnWhisperReceived;
				AsyncEventHandler<OnWhisperReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnWhisperReceivedArgs> value2 = (AsyncEventHandler<OnWhisperReceivedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnWhisperReceived, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnWhisperReceivedArgs> val = this.m_OnWhisperReceived;
				AsyncEventHandler<OnWhisperReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnWhisperReceivedArgs> value2 = (AsyncEventHandler<OnWhisperReceivedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnWhisperReceived, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnMessageSentArgs>? OnMessageSent
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnMessageSentArgs> val = this.m_OnMessageSent;
				AsyncEventHandler<OnMessageSentArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageSentArgs> value2 = (AsyncEventHandler<OnMessageSentArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageSent, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnMessageSentArgs> val = this.m_OnMessageSent;
				AsyncEventHandler<OnMessageSentArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageSentArgs> value2 = (AsyncEventHandler<OnMessageSentArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageSent, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnChatCommandReceivedArgs>? OnChatCommandReceived
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnChatCommandReceivedArgs> val = this.m_OnChatCommandReceived;
				AsyncEventHandler<OnChatCommandReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChatCommandReceivedArgs> value2 = (AsyncEventHandler<OnChatCommandReceivedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChatCommandReceived, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnChatCommandReceivedArgs> val = this.m_OnChatCommandReceived;
				AsyncEventHandler<OnChatCommandReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChatCommandReceivedArgs> value2 = (AsyncEventHandler<OnChatCommandReceivedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChatCommandReceived, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnWhisperCommandReceivedArgs>? OnWhisperCommandReceived
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnWhisperCommandReceivedArgs> val = this.m_OnWhisperCommandReceived;
				AsyncEventHandler<OnWhisperCommandReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnWhisperCommandReceivedArgs> value2 = (AsyncEventHandler<OnWhisperCommandReceivedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnWhisperCommandReceived, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnWhisperCommandReceivedArgs> val = this.m_OnWhisperCommandReceived;
				AsyncEventHandler<OnWhisperCommandReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnWhisperCommandReceivedArgs> value2 = (AsyncEventHandler<OnWhisperCommandReceivedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnWhisperCommandReceived, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserJoinedArgs>? OnUserJoined
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserJoinedArgs> val = this.m_OnUserJoined;
				AsyncEventHandler<OnUserJoinedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserJoinedArgs> value2 = (AsyncEventHandler<OnUserJoinedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserJoined, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserJoinedArgs> val = this.m_OnUserJoined;
				AsyncEventHandler<OnUserJoinedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserJoinedArgs> value2 = (AsyncEventHandler<OnUserJoinedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserJoined, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnMessageClearedArgs>? OnMessageCleared
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnMessageClearedArgs> val = this.m_OnMessageCleared;
				AsyncEventHandler<OnMessageClearedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageClearedArgs> value2 = (AsyncEventHandler<OnMessageClearedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageCleared, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnMessageClearedArgs> val = this.m_OnMessageCleared;
				AsyncEventHandler<OnMessageClearedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageClearedArgs> value2 = (AsyncEventHandler<OnMessageClearedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageCleared, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnNewSubscriberArgs>? OnNewSubscriber
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnNewSubscriberArgs> val = this.m_OnNewSubscriber;
				AsyncEventHandler<OnNewSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnNewSubscriberArgs> value2 = (AsyncEventHandler<OnNewSubscriberArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnNewSubscriber, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnNewSubscriberArgs> val = this.m_OnNewSubscriber;
				AsyncEventHandler<OnNewSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnNewSubscriberArgs> value2 = (AsyncEventHandler<OnNewSubscriberArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnNewSubscriber, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnReSubscriberArgs>? OnReSubscriber
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnReSubscriberArgs> val = this.m_OnReSubscriber;
				AsyncEventHandler<OnReSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnReSubscriberArgs> value2 = (AsyncEventHandler<OnReSubscriberArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnReSubscriber, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnReSubscriberArgs> val = this.m_OnReSubscriber;
				AsyncEventHandler<OnReSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnReSubscriberArgs> value2 = (AsyncEventHandler<OnReSubscriberArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnReSubscriber, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnPrimePaidSubscriberArgs>? OnPrimePaidSubscriber
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnPrimePaidSubscriberArgs> val = this.m_OnPrimePaidSubscriber;
				AsyncEventHandler<OnPrimePaidSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnPrimePaidSubscriberArgs> value2 = (AsyncEventHandler<OnPrimePaidSubscriberArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnPrimePaidSubscriber, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnPrimePaidSubscriberArgs> val = this.m_OnPrimePaidSubscriber;
				AsyncEventHandler<OnPrimePaidSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnPrimePaidSubscriberArgs> value2 = (AsyncEventHandler<OnPrimePaidSubscriberArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnPrimePaidSubscriber, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnExistingUsersDetectedArgs>? OnExistingUsersDetected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnExistingUsersDetectedArgs> val = this.m_OnExistingUsersDetected;
				AsyncEventHandler<OnExistingUsersDetectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnExistingUsersDetectedArgs> value2 = (AsyncEventHandler<OnExistingUsersDetectedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnExistingUsersDetected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnExistingUsersDetectedArgs> val = this.m_OnExistingUsersDetected;
				AsyncEventHandler<OnExistingUsersDetectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnExistingUsersDetectedArgs> value2 = (AsyncEventHandler<OnExistingUsersDetectedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnExistingUsersDetected, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserLeftArgs>? OnUserLeft
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserLeftArgs> val = this.m_OnUserLeft;
				AsyncEventHandler<OnUserLeftArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserLeftArgs> value2 = (AsyncEventHandler<OnUserLeftArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserLeft, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserLeftArgs> val = this.m_OnUserLeft;
				AsyncEventHandler<OnUserLeftArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserLeftArgs> value2 = (AsyncEventHandler<OnUserLeftArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserLeft, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnDisconnectedArgs>? OnDisconnected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnDisconnectedArgs> val = this.m_OnDisconnected;
				AsyncEventHandler<OnDisconnectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnDisconnectedArgs> value2 = (AsyncEventHandler<OnDisconnectedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnDisconnected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnDisconnectedArgs> val = this.m_OnDisconnected;
				AsyncEventHandler<OnDisconnectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnDisconnectedArgs> value2 = (AsyncEventHandler<OnDisconnectedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnDisconnected, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnConnectionErrorArgs>? OnConnectionError
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnConnectionErrorArgs> val = this.m_OnConnectionError;
				AsyncEventHandler<OnConnectionErrorArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectionErrorArgs> value2 = (AsyncEventHandler<OnConnectionErrorArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnectionError, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnConnectionErrorArgs> val = this.m_OnConnectionError;
				AsyncEventHandler<OnConnectionErrorArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectionErrorArgs> value2 = (AsyncEventHandler<OnConnectionErrorArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnectionError, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnChatClearedArgs>? OnChatCleared
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnChatClearedArgs> val = this.m_OnChatCleared;
				AsyncEventHandler<OnChatClearedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChatClearedArgs> value2 = (AsyncEventHandler<OnChatClearedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChatCleared, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnChatClearedArgs> val = this.m_OnChatCleared;
				AsyncEventHandler<OnChatClearedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChatClearedArgs> value2 = (AsyncEventHandler<OnChatClearedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChatCleared, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserTimedoutArgs>? OnUserTimedout
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserTimedoutArgs> val = this.m_OnUserTimedout;
				AsyncEventHandler<OnUserTimedoutArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserTimedoutArgs> value2 = (AsyncEventHandler<OnUserTimedoutArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserTimedout, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserTimedoutArgs> val = this.m_OnUserTimedout;
				AsyncEventHandler<OnUserTimedoutArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserTimedoutArgs> value2 = (AsyncEventHandler<OnUserTimedoutArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserTimedout, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnLeftChannelArgs>? OnLeftChannel
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnLeftChannelArgs> val = this.m_OnLeftChannel;
				AsyncEventHandler<OnLeftChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnLeftChannelArgs> value2 = (AsyncEventHandler<OnLeftChannelArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnLeftChannel, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnLeftChannelArgs> val = this.m_OnLeftChannel;
				AsyncEventHandler<OnLeftChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnLeftChannelArgs> value2 = (AsyncEventHandler<OnLeftChannelArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnLeftChannel, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserBannedArgs>? OnUserBanned
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserBannedArgs> val = this.m_OnUserBanned;
				AsyncEventHandler<OnUserBannedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserBannedArgs> value2 = (AsyncEventHandler<OnUserBannedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserBanned, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserBannedArgs> val = this.m_OnUserBanned;
				AsyncEventHandler<OnUserBannedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserBannedArgs> value2 = (AsyncEventHandler<OnUserBannedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserBanned, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnSendReceiveDataArgs>? OnSendReceiveData
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnSendReceiveDataArgs> val = this.m_OnSendReceiveData;
				AsyncEventHandler<OnSendReceiveDataArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnSendReceiveDataArgs> value2 = (AsyncEventHandler<OnSendReceiveDataArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSendReceiveData, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnSendReceiveDataArgs> val = this.m_OnSendReceiveData;
				AsyncEventHandler<OnSendReceiveDataArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnSendReceiveDataArgs> value2 = (AsyncEventHandler<OnSendReceiveDataArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSendReceiveData, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnRaidNotificationArgs>? OnRaidNotification
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnRaidNotificationArgs> val = this.m_OnRaidNotification;
				AsyncEventHandler<OnRaidNotificationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnRaidNotificationArgs> value2 = (AsyncEventHandler<OnRaidNotificationArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRaidNotification, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnRaidNotificationArgs> val = this.m_OnRaidNotification;
				AsyncEventHandler<OnRaidNotificationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnRaidNotificationArgs> value2 = (AsyncEventHandler<OnRaidNotificationArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRaidNotification, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnGiftedSubscriptionArgs>? OnGiftedSubscription
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnGiftedSubscriptionArgs> val = this.m_OnGiftedSubscription;
				AsyncEventHandler<OnGiftedSubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnGiftedSubscriptionArgs> value2 = (AsyncEventHandler<OnGiftedSubscriptionArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnGiftedSubscription, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnGiftedSubscriptionArgs> val = this.m_OnGiftedSubscription;
				AsyncEventHandler<OnGiftedSubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnGiftedSubscriptionArgs> value2 = (AsyncEventHandler<OnGiftedSubscriptionArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnGiftedSubscription, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnCommunitySubscriptionArgs>? OnCommunitySubscription
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnCommunitySubscriptionArgs> val = this.m_OnCommunitySubscription;
				AsyncEventHandler<OnCommunitySubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnCommunitySubscriptionArgs> value2 = (AsyncEventHandler<OnCommunitySubscriptionArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnCommunitySubscription, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnCommunitySubscriptionArgs> val = this.m_OnCommunitySubscription;
				AsyncEventHandler<OnCommunitySubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnCommunitySubscriptionArgs> value2 = (AsyncEventHandler<OnCommunitySubscriptionArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnCommunitySubscription, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnContinuedGiftedSubscriptionArgs>? OnContinuedGiftedSubscription
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> val = this.m_OnContinuedGiftedSubscription;
				AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> value2 = (AsyncEventHandler<OnContinuedGiftedSubscriptionArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnContinuedGiftedSubscription, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> val = this.m_OnContinuedGiftedSubscription;
				AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> value2 = (AsyncEventHandler<OnContinuedGiftedSubscriptionArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnContinuedGiftedSubscription, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnMessageThrottledArgs>? OnMessageThrottled
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnMessageThrottledArgs> val = this.m_OnMessageThrottled;
				AsyncEventHandler<OnMessageThrottledArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageThrottledArgs> value2 = (AsyncEventHandler<OnMessageThrottledArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageThrottled, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnMessageThrottledArgs> val = this.m_OnMessageThrottled;
				AsyncEventHandler<OnMessageThrottledArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageThrottledArgs> value2 = (AsyncEventHandler<OnMessageThrottledArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageThrottled, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnErrorEventArgs>? OnError
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnErrorEventArgs> val = this.m_OnError;
				AsyncEventHandler<OnErrorEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnErrorEventArgs> value2 = (AsyncEventHandler<OnErrorEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnError, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnErrorEventArgs> val = this.m_OnError;
				AsyncEventHandler<OnErrorEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnErrorEventArgs> value2 = (AsyncEventHandler<OnErrorEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnError, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnConnectedEventArgs>? OnReconnected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnConnectedEventArgs> val = this.m_OnReconnected;
				AsyncEventHandler<OnConnectedEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectedEventArgs> value2 = (AsyncEventHandler<OnConnectedEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnReconnected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnConnectedEventArgs> val = this.m_OnReconnected;
				AsyncEventHandler<OnConnectedEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectedEventArgs> value2 = (AsyncEventHandler<OnConnectedEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnReconnected, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnRequiresVerifiedEmail
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRequiresVerifiedEmail;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRequiresVerifiedEmail, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRequiresVerifiedEmail;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRequiresVerifiedEmail, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnRequiresVerifiedPhoneNumber
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRequiresVerifiedPhoneNumber;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRequiresVerifiedPhoneNumber, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRequiresVerifiedPhoneNumber;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRequiresVerifiedPhoneNumber, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnRateLimit
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRateLimit;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRateLimit, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRateLimit;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRateLimit, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnDuplicate
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnDuplicate;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnDuplicate, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnDuplicate;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnDuplicate, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnBannedEmailAlias
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnBannedEmailAlias;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBannedEmailAlias, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnBannedEmailAlias;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBannedEmailAlias, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnSelfRaidError
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSelfRaidError;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSelfRaidError, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSelfRaidError;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSelfRaidError, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnNoPermissionError
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnNoPermissionError;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnNoPermissionError, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnNoPermissionError;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnNoPermissionError, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnRaidedChannelIsMatureAudience
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRaidedChannelIsMatureAudience;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRaidedChannelIsMatureAudience, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRaidedChannelIsMatureAudience;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRaidedChannelIsMatureAudience, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs>? OnFailureToReceiveJoinConfirmation
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> val = this.m_OnFailureToReceiveJoinConfirmation;
				AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> value2 = (AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnFailureToReceiveJoinConfirmation, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> val = this.m_OnFailureToReceiveJoinConfirmation;
				AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> value2 = (AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnFailureToReceiveJoinConfirmation, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnFollowersOnly
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnFollowersOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnFollowersOnly, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnFollowersOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnFollowersOnly, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnSubsOnly
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSubsOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSubsOnly, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSubsOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSubsOnly, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnEmoteOnly
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnEmoteOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnEmoteOnly, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnEmoteOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnEmoteOnly, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnSuspended
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSuspended;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSuspended, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSuspended;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSuspended, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnBanned
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnBanned;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBanned, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnBanned;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBanned, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnSlowMode
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSlowMode;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSlowMode, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSlowMode;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSlowMode, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs>? OnR9kMode
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnR9kMode;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnR9kMode, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnR9kMode;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnR9kMode, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserIntroArgs>? OnUserIntro
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserIntroArgs> val = this.m_OnUserIntro;
				AsyncEventHandler<OnUserIntroArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserIntroArgs> value2 = (AsyncEventHandler<OnUserIntroArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserIntro, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserIntroArgs> val = this.m_OnUserIntro;
				AsyncEventHandler<OnUserIntroArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserIntroArgs> value2 = (AsyncEventHandler<OnUserIntroArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserIntro, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUnaccountedForArgs>? OnUnaccountedFor
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUnaccountedForArgs> val = this.m_OnUnaccountedFor;
				AsyncEventHandler<OnUnaccountedForArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUnaccountedForArgs> value2 = (AsyncEventHandler<OnUnaccountedForArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUnaccountedFor, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUnaccountedForArgs> val = this.m_OnUnaccountedFor;
				AsyncEventHandler<OnUnaccountedForArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUnaccountedForArgs> value2 = (AsyncEventHandler<OnUnaccountedForArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUnaccountedFor, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnAnonGiftPaidUpgradeArgs>? OnAnonGiftPaidUpgrade
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> val = this.m_OnAnonGiftPaidUpgrade;
				AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> value2 = (AsyncEventHandler<OnAnonGiftPaidUpgradeArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnAnonGiftPaidUpgrade, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> val = this.m_OnAnonGiftPaidUpgrade;
				AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> value2 = (AsyncEventHandler<OnAnonGiftPaidUpgradeArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnAnonGiftPaidUpgrade, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUnraidNotificationArgs>? OnUnraidNotification
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUnraidNotificationArgs> val = this.m_OnUnraidNotification;
				AsyncEventHandler<OnUnraidNotificationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUnraidNotificationArgs> value2 = (AsyncEventHandler<OnUnraidNotificationArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUnraidNotification, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUnraidNotificationArgs> val = this.m_OnUnraidNotification;
				AsyncEventHandler<OnUnraidNotificationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUnraidNotificationArgs> value2 = (AsyncEventHandler<OnUnraidNotificationArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUnraidNotification, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnRitualArgs>? OnRitual
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnRitualArgs> val = this.m_OnRitual;
				AsyncEventHandler<OnRitualArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnRitualArgs> value2 = (AsyncEventHandler<OnRitualArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRitual, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnRitualArgs> val = this.m_OnRitual;
				AsyncEventHandler<OnRitualArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnRitualArgs> value2 = (AsyncEventHandler<OnRitualArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRitual, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnBitsBadgeTierArgs>? OnBitsBadgeTier
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnBitsBadgeTierArgs> val = this.m_OnBitsBadgeTier;
				AsyncEventHandler<OnBitsBadgeTierArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnBitsBadgeTierArgs> value2 = (AsyncEventHandler<OnBitsBadgeTierArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBitsBadgeTier, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnBitsBadgeTierArgs> val = this.m_OnBitsBadgeTier;
				AsyncEventHandler<OnBitsBadgeTierArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnBitsBadgeTierArgs> value2 = (AsyncEventHandler<OnBitsBadgeTierArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBitsBadgeTier, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnCommunityPayForwardArgs>? OnCommunityPayForward
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnCommunityPayForwardArgs> val = this.m_OnCommunityPayForward;
				AsyncEventHandler<OnCommunityPayForwardArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnCommunityPayForwardArgs> value2 = (AsyncEventHandler<OnCommunityPayForwardArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnCommunityPayForward, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnCommunityPayForwardArgs> val = this.m_OnCommunityPayForward;
				AsyncEventHandler<OnCommunityPayForwardArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnCommunityPayForwardArgs> value2 = (AsyncEventHandler<OnCommunityPayForwardArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnCommunityPayForward, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnStandardPayForwardArgs>? OnStandardPayForward
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnStandardPayForwardArgs> val = this.m_OnStandardPayForward;
				AsyncEventHandler<OnStandardPayForwardArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnStandardPayForwardArgs> value2 = (AsyncEventHandler<OnStandardPayForwardArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnStandardPayForward, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnStandardPayForwardArgs> val = this.m_OnStandardPayForward;
				AsyncEventHandler<OnStandardPayForwardArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnStandardPayForwardArgs> value2 = (AsyncEventHandler<OnStandardPayForwardArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnStandardPayForward, value2, val2);
				}
				while (val != val2);
			}
		}

		public TwitchClient(IClient? client = null, ClientProtocol protocol = 1, ISendOptions? sendOptions = null, ILoggerFactory? loggerFactory = null)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			_loggerFactory = loggerFactory;
			_logger = loggerFactory?.CreateLogger<TwitchClient>();
			_client = client;
			_protocol = protocol;
			_sendOptions = (ISendOptions)(((object)sendOptions) ?? ((object)new SendOptions(20u, 10000u, 30u, (ushort)50)));
		}

		public void Initialize(ConnectionCredentials credentials, string? channel = null)
		{
			List<string> list = new List<string>();
			if (channel != null)
			{
				list.Add(channel);
			}
			Initialize(credentials, list);
		}

		public void Initialize(ConnectionCredentials credentials, List<string> channels)
		{
			channels = channels.ConvertAll((string x) => x.StartsWith("#") ? x.Substring(1) : x);
			InitializationHelper(credentials, channels);
		}

		private void InitializationHelper(ConnectionCredentials credentials, List<string> channels)
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			List<string> channels2 = channels;
			_logger?.LogInitialized(Assembly.GetExecutingAssembly().GetName().Version);
			ConnectionCredentials = credentials;
			if (ChatCommandIdentifiers.Count == 0)
			{
				ChatCommandIdentifiers.Add('!');
			}
			if (WhisperCommandIdentifiers.Count == 0)
			{
				WhisperCommandIdentifiers.Add('!');
			}
			int i;
			for (i = 0; i < channels2.Count; i++)
			{
				if (!string.IsNullOrEmpty(channels2[i]))
				{
					if (JoinedChannels.Any((JoinedChannel x) => x.Channel.Equals(channels2[i], StringComparison.OrdinalIgnoreCase)))
					{
						return;
					}
					_joinChannelQueue.Enqueue(new JoinedChannel(channels2[i]));
				}
			}
			InitializeClient();
		}

		private void InitializeClient()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			IClient client = _client;
			IClient val = client;
			if (val == null)
			{
				ClientProtocol protocol = _protocol;
				if (1 == 0)
				{
				}
				IClient client2;
				if ((int)protocol != 0)
				{
					if ((int)protocol != 1)
					{
						throw new ArgumentOutOfRangeException("_protocol", _protocol, null);
					}
					client2 = (IClient)new WebSocketClient((IClientOptions)null, _loggerFactory?.CreateLogger<WebSocketClient>());
				}
				else
				{
					client2 = (IClient)new TcpClient((IClientOptions)null, _loggerFactory?.CreateLogger<TcpClient>());
				}
				if (1 == 0)
				{
				}
				val = (_client = client2);
			}
			Debug.Assert(_client != null, "_client != null");
			_throttling = new ThrottlingService(_client, _sendOptions, _logger);
			_throttling.OnThrottled += OnThrottled;
			_throttling.OnError += ThrottlerOnError;
			_client.OnConnected += _client_OnConnectedAsync;
			_client.OnMessage += _client_OnMessage;
			_client.OnDisconnected += _client_OnDisconnected;
			_client.OnFatality += _client_OnFatality;
			_client.OnReconnected += _client_OnReconnected;
		}

		public async Task SendRawAsync(string message)
		{
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			_logger?.LogWriting(message);
			await _client.SendAsync(message);
			await this.OnSendReceiveData.TryInvoke(this, new OnSendReceiveDataArgs((SendReceiveDirection)0, message));
		}

		private void SendTwitchMessage(JoinedChannel? channel, string? message, string? replyToId = null, bool dryRun = false)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			if (channel == null || message == null || dryRun)
			{
				return;
			}
			if (message.Length > 500)
			{
				_logger?.LogMessageTooLong();
				return;
			}
			OutboundChatMessage val = new OutboundChatMessage(channel.Channel, message);
			if (replyToId != null)
			{
				val.ReplyToId = replyToId;
			}
			_lastMessageSent = message;
			_throttling.Enqueue(val);
		}

		public Task SendMessageAsync(JoinedChannel channel, string message, bool dryRun = false)
		{
			SendTwitchMessage(channel, message, null, dryRun);
			return Task.CompletedTask;
		}

		public Task SendMessageAsync(string channel, string message, bool dryRun = false)
		{
			return SendMessageAsync(GetJoinedChannel(channel), message, dryRun);
		}

		public Task SendReplyAsync(JoinedChannel channel, string replyToId, string message, bool dryRun = false)
		{
			SendTwitchMessage(channel, message, replyToId, dryRun);
			return Task.CompletedTask;
		}

		public Task SendReplyAsync(string channel, string replyToId, string message, bool dryRun = false)
		{
			return SendReplyAsync(GetJoinedChannel(channel), replyToId, message, dryRun);
		}

		public async Task<bool> ConnectAsync()
		{
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			_logger?.LogConnecting();
			_joinedChannelManager.Clear();
			if (await _client.OpenAsync())
			{
				_logger?.LogShouldBeConnected();
				return true;
			}
			return false;
		}

		public async Task DisconnectAsync()
		{
			_logger?.LogDisconnecting();
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			await _client.CloseAsync();
			_joinedChannelManager.Clear();
			PreviousWhisper = null;
		}

		public async Task ReconnectAsync()
		{
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			_logger?.LogReconnecting();
			await _client.ReconnectAsync();
		}

		public void SetConnectionCredentials(ConnectionCredentials credentials)
		{
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			if (IsConnected)
			{
				throw new IllegalAssignmentException("While the client is connected, you are unable to change the connection credentials. Please disconnect first and then change them.");
			}
			ConnectionCredentials = credentials;
		}

		public Task JoinChannelAsync(string channel, bool overrideCheck = false)
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			string channel2 = channel;
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			if (!IsConnected)
			{
				HandleNotConnected();
			}
			if (JoinedChannels.Any((JoinedChannel x) => !overrideCheck && x.Channel.Equals(channel2, StringComparison.OrdinalIgnoreCase)))
			{
				return Task.CompletedTask;
			}
			if (channel2[0] == '#')
			{
				channel2 = channel2.Substring(1);
			}
			_joinChannelQueue.Enqueue(new JoinedChannel(channel2));
			return (!_currentlyJoiningChannels) ? QueueingJoinCheckAsync() : Task.CompletedTask;
		}

		public JoinedChannel? GetJoinedChannel(string channel)
		{
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			if (JoinedChannels.Count == 0)
			{
				throw new BadStateException("Must be connected to at least one channel.");
			}
			if (channel[0] == '#')
			{
				channel = channel.Substring(1);
			}
			return _joinedChannelManager.GetJoinedChannel(channel);
		}

		public async Task LeaveChannelAsync(string channel)
		{
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			channel = channel.ToLower();
			if (channel[0] == '#')
			{
				channel = channel.Substring(1);
			}
			_logger?.LogLeavingChannel(channel);
			JoinedChannel joinedChannel = _joinedChannelManager.GetJoinedChannel(channel);
			if (joinedChannel != null)
			{
				await _client.SendAsync(Rfc2812.Part("#" + channel));
				_joinedChannelManager.RemoveJoinedChannel(channel);
			}
		}

		public Task LeaveChannelAsync(JoinedChannel channel)
		{
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			return LeaveChannelAsync(channel.Channel);
		}

		public Task OnReadLineTestAsync(string rawIrc)
		{
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			return HandleIrcMessageAsync(IrcParser.ParseMessage(rawIrc));
		}

		private Task OnThrottled(object? sender, OnMessageThrottledArgs e)
		{
			return this.OnMessageThrottled.TryInvoke(sender, e);
		}

		private Task ThrottlerOnError(object? sender, OnErrorEventArgs e)
		{
			return this.OnError.TryInvoke<OnErrorEventArgs>(sender, e);
		}

		private Task _client_OnFatality(object? sender, OnFatalErrorEventArgs e)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			return this.OnConnectionError.TryInvoke(this, new OnConnectionErrorArgs(TwitchUsername, new ErrorEvent(e.Reason)));
		}

		private Task _client_OnDisconnected(object? sender, OnDisconnectedEventArgs e)
		{
			return this.OnDisconnected.TryInvoke(sender, new OnDisconnectedArgs(TwitchUsername));
		}

		private async Task _client_OnReconnected(object? sender, OnConnectedEventArgs e)
		{
			await SendHandshake();
			foreach (JoinedChannel channel in _joinedChannelManager.GetJoinedChannels())
			{
				_joinChannelQueue.Enqueue(channel);
			}
			Queue<JoinedChannel> joinChannelQueue = _joinChannelQueue;
			if (joinChannelQueue != null && joinChannelQueue.Count > 0)
			{
				await QueueingJoinCheckAsync();
			}
			_joinedChannelManager.Clear();
			await this.OnReconnected.TryInvoke(sender, new OnConnectedEventArgs(TwitchUsername));
		}

		private async Task _client_OnMessage(object? sender, OnMessageEventArgs e)
		{
			string[] lines = e.Message.Split(NewLineSeparator, StringSplitOptions.None);
			string[] array = lines;
			foreach (string line in array)
			{
				if (line.Length > 1)
				{
					_logger?.LogReceived(line);
					await this.OnSendReceiveData.TryInvoke(this, new OnSendReceiveDataArgs((SendReceiveDirection)1, line));
					IrcMessage ircMessage;
					try
					{
						ircMessage = IrcParser.ParseMessage(line);
					}
					catch (Exception ex)
					{
						_logger?.LogParsingError(line, ex);
						this.OnError?.Invoke((object)this, new OnErrorEventArgs(ex));
						continue;
					}
					await HandleIrcMessageAsync(ircMessage);
				}
			}
		}

		private async Task _client_OnConnectedAsync(object? sender, EventArgs e)
		{
			await SendHandshake();
			Queue<JoinedChannel> joinChannelQueue = _joinChannelQueue;
			if (joinChannelQueue != null && joinChannelQueue.Count > 0)
			{
				await QueueingJoinCheckAsync();
			}
		}

		private async Task SendHandshake()
		{
			await _client.SendAsync(Rfc2812.Pass(ConnectionCredentials.TwitchOAuth));
			await _client.SendAsync(Rfc2812.Nick(ConnectionCredentials.TwitchUsername));
			await _client.SendAsync(Rfc2812.User(ConnectionCredentials.TwitchUsername, 0, ConnectionCredentials.TwitchUsername));
			if (ConnectionCredentials.Capabilities.Membership)
			{
				await _client.SendAsync("CAP REQ twitch.tv/membership");
			}
			if (ConnectionCredentials.Capabilities.Commands)
			{
				await _client.SendAsync("CAP REQ twitch.tv/commands");
			}
			if (ConnectionCredentials.Capabilities.Tags)
			{
				await _client.SendAsync("CAP REQ twitch.tv/tags");
			}
		}

		private async Task QueueingJoinCheckAsync()
		{
			if (_joinChannelQueue.Count > 0)
			{
				_currentlyJoiningChannels = true;
				JoinedChannel channelToJoin = _joinChannelQueue.Dequeue();
				_logger?.LogJoiningChannel(channelToJoin.Channel);
				await _client.SendAsync(Rfc2812.Join("#" + channelToJoin.Channel.ToLower()));
				_joinedChannelManager.AddJoinedChannel(new JoinedChannel(channelToJoin.Channel));
				StartJoinedChannelTimer(channelToJoin.Channel);
			}
			else
			{
				_logger?.LogChannelJoiningFinished();
			}
		}

		private void StartJoinedChannelTimer(string channel)
		{
			if (_joinTimer == null)
			{
				_joinTimer = new System.Timers.Timer(1000.0);
				_joinTimer.Elapsed += JoinChannelTimeout;
			}
			_awaitingJoins.Add(new KeyValuePair<string, DateTime>(channel.ToLower(), DateTime.Now));
			if (!_joinTimer.Enabled)
			{
				_joinTimer.Start();
			}
		}

		private void JoinChannelTimeout(object? sender, ElapsedEventArgs e)
		{
			if (_awaitingJoins.Any())
			{
				List<KeyValuePair<string, DateTime>> list = _awaitingJoins.Where<KeyValuePair<string, DateTime>>((KeyValuePair<string, DateTime> x) => (DateTime.Now - x.Value).TotalSeconds > 5.0).ToList();
				if (!list.Any())
				{
					return;
				}
				_awaitingJoins.RemoveAll((KeyValuePair<string, DateTime> x) => (DateTime.Now - x.Value).TotalSeconds > 5.0);
				{
					foreach (KeyValuePair<string, DateTime> item in list)
					{
						_joinedChannelManager.RemoveJoinedChannel(item.Key.ToLowerInvariant());
						this.OnFailureToReceiveJoinConfirmation?.TryInvoke(this, new OnFailureToReceiveJoinConfirmationArgs(new FailureToReceiveJoinConfirmationException(item.Key)));
					}
					return;
				}
			}
			_joinTimer.Stop();
			_currentlyJoiningChannels = false;
			QueueingJoinCheckAsync().GetAwaiter().GetResult();
		}

		private Task HandleIrcMessageAsync(IrcMessage ircMessage)
		{
			//IL_003c: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected I4, but got Unknown
			string text = ((object)ircMessage).ToString();
			if (text.StartsWith(":tmi.twitch.tv NOTICE * :Login authentication failed"))
			{
				return this.OnIncorrectLogin.TryInvoke(this, new OnIncorrectLoginArgs(new ErrorLoggingInException(text, TwitchUsername)));
			}
			IrcCommand command = ircMessage.Command;
			if (1 == 0)
			{
			}
			Task result;
			switch (command - 1)
			{
			case 0:
				result = HandlePrivMsg(ircMessage);
				break;
			case 4:
				result = HandleJoin(ircMessage);
				break;
			case 5:
				result = HandlePart(ircMessage);
				break;
			case 2:
				result = ((!DisableAutoPong) ? SendRawAsync("PONG") : Task.CompletedTask);
				break;
			case 1:
				result = HandleNotice(ircMessage);
				break;
			case 22:
				result = HandleWhisper(ircMessage);
				break;
			case 6:
				result = HandleClearChat(ircMessage);
				break;
			case 7:
				result = HandleClearMsg(ircMessage);
				break;
			case 8:
				result = HandleUserState(ircMessage);
				break;
			case 26:
				result = HandleUserNotice(ircMessage);
				break;
			case 23:
				result = HandleRoomState(ircMessage);
				break;
			case 24:
				result = ReconnectAsync();
				break;
			case 12:
				result = HandleCap(ircMessage);
				break;
			case 16:
				result = Handle004();
				break;
			case 17:
				result = Handle353(ircMessage);
				break;
			case 18:
				result = Handle366();
				break;
			case 3:
			case 9:
			case 13:
			case 14:
			case 15:
			case 19:
			case 20:
			case 21:
				result = Task.CompletedTask;
				break;
			default:
				result = this.OnUnaccountedFor?.Invoke((object)this, new OnUnaccountedForArgs(TwitchUsername, null, "HandleIrcMessage", text)) ?? UnaccountedFor(text);
				break;
			}
			if (1 == 0)
			{
			}
			return result;
		}

		private async Task HandlePrivMsg(IrcMessage ircMessage)
		{
			IrcMessage ircMessage2 = ircMessage;
			ChatMessage chatMessage = new ChatMessage(TwitchUsername, ircMessage2, ChannelEmotes, WillReplaceEmotes, ReplacedEmotesPrefix, ReplacedEmotesSuffix);
			foreach (JoinedChannel joinedChannel in JoinedChannels.Where((JoinedChannel x) => x.Channel.Equals(ircMessage2.Channel, StringComparison.InvariantCultureIgnoreCase)))
			{
				joinedChannel.HandleMessage(chatMessage);
			}
			await this.OnMessageReceived.TryInvoke(this, new OnMessageReceivedArgs(chatMessage));
			if (ircMessage2.Tags.TryGetValue("msg-id", out var msgId) && msgId == "user-intro" && this.OnUserIntro != null)
			{
				await this.OnUserIntro.Invoke((object)this, new OnUserIntroArgs(chatMessage));
			}
			CommandInfo commandInfo = default(CommandInfo);
			if (this.OnChatCommandReceived != null && !string.IsNullOrEmpty(chatMessage.Message) && ChatCommandIdentifiers.Contains(chatMessage.Message[0]) && CommandInfo.TryParse(chatMessage.Message.AsSpan(), ref commandInfo))
			{
				await this.OnChatCommandReceived.Invoke((object)this, new OnChatCommandReceivedArgs(chatMessage, commandInfo));
			}
		}

		private Task HandleNotice(IrcMessage ircMessage)
		{
			string channel = ircMessage.Channel;
			string message = ircMessage.Message;
			string text = ((object)ircMessage).ToString();
			if (message.Contains("Improperly formatted auth"))
			{
				return this.OnIncorrectLogin.TryInvoke(this, new OnIncorrectLoginArgs(new ErrorLoggingInException(text, TwitchUsername)));
			}
			string value;
			bool flag = ircMessage.Tags.TryGetValue("msg-id", out value);
			if (1 == 0)
			{
			}
			Task task = value switch
			{
				"no_permission" => this.OnNoPermissionError?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"raid_error_self" => this.OnSelfRaidError?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"raid_notice_mature" => this.OnRaidedChannelIsMatureAudience?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_banned_email_alias" => this.OnBannedEmailAlias?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_channel_suspended" => HandleChannelSuspended(ircMessage), 
				"msg_requires_verified_phone_number" => this.OnRequiresVerifiedPhoneNumber?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_verified_email" => this.OnRequiresVerifiedEmail?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_ratelimit" => this.OnRateLimit?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_duplicate" => this.OnDuplicate?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_followersonly" => this.OnFollowersOnly?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_subsonly" => this.OnSubsOnly?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_emoteonly" => this.OnEmoteOnly?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_suspended" => this.OnSuspended?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_banned" => this.OnBanned?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_slowmode" => this.OnSlowMode?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				"msg_r9k" => this.OnR9kMode?.Invoke((object)this, new NoticeEventArgs(channel, message)), 
				_ => this.OnUnaccountedFor?.Invoke((object)this, new OnUnaccountedForArgs(TwitchUsername, channel, "NoticeHandling", text)) ?? UnaccountedFor(text), 
			};
			if (1 == 0)
			{
			}
			Task task2 = task;
			return task2 ?? Task.CompletedTask;
		}

		private async Task HandleChannelSuspended(IrcMessage ircMessage)
		{
			IrcMessage ircMessage2 = ircMessage;
			_awaitingJoins.RemoveAll((KeyValuePair<string, DateTime> x) => x.Key.Equals(ircMessage2.Channel, StringComparison.OrdinalIgnoreCase));
			_joinedChannelManager.RemoveJoinedChannel(ircMessage2.Channel);
			await QueueingJoinCheckAsync();
			await this.OnFailureToReceiveJoinConfirmation.TryInvoke(this, new OnFailureToReceiveJoinConfirmationArgs(new FailureToReceiveJoinConfirmationException(ircMessage2.Channel, ircMessage2.Message)));
		}

		private Task HandleJoin(IrcMessage ircMessage)
		{
			IrcMessage ircMessage2 = ircMessage;
			if (string.Equals(TwitchUsername, ircMessage2.User, StringComparison.InvariantCultureIgnoreCase))
			{
				KeyValuePair<string, DateTime> item = _awaitingJoins.Find((KeyValuePair<string, DateTime> x) => x.Key == ircMessage2.Channel);
				_awaitingJoins.Remove(item);
				return this.OnJoinedChannel.TryInvoke(this, new OnJoinedChannelArgs(ircMessage2.Channel, TwitchUsername));
			}
			return this.OnUserJoined.TryInvoke(this, new OnUserJoinedArgs(ircMessage2.Channel, ircMessage2.User));
		}

		private Task HandlePart(IrcMessage ircMessage)
		{
			if (string.Equals(TwitchUsername, ircMessage.User, StringComparison.InvariantCultureIgnoreCase))
			{
				_joinedChannelManager.RemoveJoinedChannel(ircMessage.Channel);
				_hasSeenJoinedChannels.Remove(ircMessage.Channel);
				return this.OnLeftChannel.TryInvoke(this, new OnLeftChannelArgs(ircMessage.Channel, TwitchUsername));
			}
			return this.OnUserLeft.TryInvoke(this, new OnUserLeftArgs(ircMessage.Channel, ircMessage.User));
		}

		private Task HandleClearChat(IrcMessage ircMessage)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			if (string.IsNullOrWhiteSpace(ircMessage.Message))
			{
				return this.OnChatCleared.TryInvoke(this, new OnChatClearedArgs(ircMessage.Channel));
			}
			return ircMessage.Tags.ContainsKey("ban-duration") ? this.OnUserTimedout.TryInvoke(this, new OnUserTimedoutArgs(new UserTimeout(ircMessage))) : this.OnUserBanned.TryInvoke(this, new OnUserBannedArgs(new UserBan(ircMessage)));
		}

		private Task HandleClearMsg(IrcMessage ircMessage)
		{
			string value;
			DateTimeOffset tmiSent = (ircMessage.Tags.TryGetValue("tmi-sent-ts", out value) ? DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(value)) : default(DateTimeOffset));
			return this.OnMessageCleared.TryInvoke(this, new OnMessageClearedArgs(ircMessage.Channel, ircMessage.Message, ircMessage.Tags.GetValueOrDefault("target-msg-id", string.Empty), tmiSent));
		}

		private Task HandleUserState(IrcMessage ircMessage)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			UserState val = new UserState(ircMessage);
			string item = val.Channel.ToLowerInvariant();
			if (!_hasSeenJoinedChannels.Contains(item))
			{
				_hasSeenJoinedChannels.Add(val.Channel.ToLowerInvariant());
				return this.OnUserStateChanged.TryInvoke(this, new OnUserStateChangedArgs(val));
			}
			return this.OnMessageSent.TryInvoke(this, new OnMessageSentArgs(new SentMessage(val, _lastMessageSent)));
		}

		private Task Handle004()
		{
			return this.OnConnected.TryInvoke(this, new OnConnectedEventArgs(TwitchUsername));
		}

		private Task Handle353(IrcMessage ircMessage)
		{
			return this.OnExistingUsersDetected.TryInvoke(this, new OnExistingUsersDetectedArgs(ircMessage.Channel, ircMessage.Message.Split(' ').ToList()));
		}

		private Task Handle366()
		{
			_currentlyJoiningChannels = false;
			return QueueingJoinCheckAsync();
		}

		private async Task HandleWhisper(IrcMessage ircMessage)
		{
			WhisperMessage whisperMessage = (PreviousWhisper = new WhisperMessage(ircMessage, TwitchUsername));
			await this.OnWhisperReceived.TryInvoke(this, new OnWhisperReceivedArgs(whisperMessage));
			CommandInfo commandInfo = default(CommandInfo);
			if (this.OnWhisperCommandReceived != null && !string.IsNullOrEmpty(whisperMessage.Message) && WhisperCommandIdentifiers.Contains(whisperMessage.Message[0]) && CommandInfo.TryParse(whisperMessage.Message.AsSpan(), ref commandInfo))
			{
				await this.OnWhisperCommandReceived.Invoke((object)this, new OnWhisperCommandReceivedArgs(whisperMessage, commandInfo));
			}
		}

		private Task HandleRoomState(IrcMessage ircMessage)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			return this.OnChannelStateChanged.TryInvoke(this, new OnChannelStateChangedArgs(ircMessage.Channel, new ChannelState(ircMessage)));
		}

		private Task HandleUserNotice(IrcMessage ircMessage)
		{
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Expected O, but got Unknown
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Expected O, but got Unknown
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Expected O, but got Unknown
			//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Expected O, but got Unknown
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Expected O, but got Unknown
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Expected O, but got Unknown
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Expected O, but got Unknown
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Expected O, but got Unknown
			string text = ((object)ircMessage).ToString();
			ircMessage.Tags.TryGetValue("msg-id", out var value);
			if (1 == 0)
			{
			}
			Task result = value switch
			{
				"announcement" => this.OnAnnouncement.TryInvoke(this, new OnAnnouncementArgs(ircMessage.Channel, new Announcement(ircMessage))), 
				"raid" => this.OnRaidNotification.TryInvoke(this, new OnRaidNotificationArgs(ircMessage.Channel, new RaidNotification(ircMessage))), 
				"resub" => this.OnReSubscriber.TryInvoke(this, new OnReSubscriberArgs(ircMessage.Channel, new ReSubscriber(ircMessage))), 
				"subgift" => this.OnGiftedSubscription.TryInvoke(this, new OnGiftedSubscriptionArgs(ircMessage.Channel, new GiftedSubscription(ircMessage))), 
				"submysterygift" => this.OnCommunitySubscription.TryInvoke(this, new OnCommunitySubscriptionArgs(ircMessage.Channel, new CommunitySubscription(ircMessage))), 
				"giftpaidupgrade" => this.OnContinuedGiftedSubscription.TryInvoke(this, new OnContinuedGiftedSubscriptionArgs(ircMessage.Channel, new ContinuedGiftedSubscription(ircMessage))), 
				"sub" => this.OnNewSubscriber.TryInvoke(this, new OnNewSubscriberArgs(ircMessage.Channel, new Subscriber(ircMessage))), 
				"primepaidupgrade" => this.OnPrimePaidSubscriber.TryInvoke(this, new OnPrimePaidSubscriberArgs(ircMessage.Channel, new PrimePaidSubscriber(ircMessage))), 
				"anongiftpaidupgrade" => this.OnAnonGiftPaidUpgrade.TryInvoke(this, new OnAnonGiftPaidUpgradeArgs(ircMessage)), 
				"unraid" => this.OnUnraidNotification.TryInvoke(this, new OnUnraidNotificationArgs(ircMessage)), 
				"ritual" => this.OnRitual.TryInvoke(this, new OnRitualArgs(ircMessage)), 
				"bitsbadgetier" => this.OnBitsBadgeTier.TryInvoke(this, new OnBitsBadgeTierArgs(ircMessage)), 
				"communitypayforward" => this.OnCommunityPayForward.TryInvoke(this, new OnCommunityPayForwardArgs(ircMessage)), 
				"standardpayforward" => this.OnStandardPayForward.TryInvoke(this, new OnStandardPayForwardArgs(ircMessage)), 
				_ => this.OnUnaccountedFor?.Invoke((object)this, new OnUnaccountedForArgs(TwitchUsername, ircMessage.Channel, "UserNoticeHandling", text)) ?? UnaccountedFor(text), 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private static Task HandleCap(IrcMessage _)
		{
			return Task.CompletedTask;
		}

		private Task UnaccountedFor(string ircString)
		{
			_logger?.LogUnaccountedFor(ircString);
			return Task.CompletedTask;
		}

		public Task SendQueuedItemAsync(string message)
		{
			if (!IsInitialized)
			{
				HandleNotInitialized();
			}
			return _client.SendAsync(message);
		}

		[DoesNotReturn]
		protected static void HandleNotInitialized()
		{
			throw new ClientNotInitializedException("The twitch client has not been initialized and cannot be used. Please call Initialize();");
		}

		[DoesNotReturn]
		protected static void HandleNotConnected()
		{
			throw new ClientNotConnectedException("In order to perform this action, the client must be connected to Twitch. To confirm connection, try performing this action in or after the OnConnected event has been fired.");
		}
	}
}
namespace TwitchLib.Client.Throttling
{
	internal class Throttler
	{
		private readonly ISendOptions _sendOptions;

		private DateTime? _firstMessage;

		private uint _sentItemCount;

		internal Throttler(ISendOptions sendOptions)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			_sendOptions = (ISendOptions)(((object)sendOptions) ?? ((object)new SendOptions(20u, 10000u, 30u, (ushort)50)));
		}

		public bool ShouldThrottle()
		{
			if (IsThrottlingPeriodExceeded())
			{
				Reset();
			}
			if (_sentItemCount >= _sendOptions.SendsAllowedInPeriod)
			{
				return true;
			}
			_sentItemCount++;
			return false;
		}

		private void Reset()
		{
			_firstMessage = DateTime.UtcNow;
			_sentItemCount = 0u;
		}

		private bool IsThrottlingPeriodExceeded()
		{
			return !_firstMessage.HasValue || DateTime.UtcNow.Subtract(_firstMessage.Value) > _sendOptions.ThrottlingPeriod;
		}
	}
	internal class ThrottlingService
	{
		private readonly IClient _client;

		private readonly ISendOptions _sendOptions;

		private readonly ILogger? _logger;

		private readonly ConcurrentQueue<(DateTime, 

TwitchLib.Client.Enums.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2023")]
[assembly: AssemblyDescription("Project containing all of the enums used in TwitchLib.Client.")]
[assembly: AssemblyFileVersion("4.0.0")]
[assembly: AssemblyInformationalVersion("4.0.0+5ef35d539836f8bcd29bd836a23b9e853020acfa")]
[assembly: AssemblyProduct("TwitchLib.Client.Enums")]
[assembly: AssemblyTitle("TwitchLib.Client.Enums")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.Client")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("4.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 TwitchLib.Client.Enums
{
	public enum BadgeColor
	{
		Red = 10000,
		Blue = 5000,
		Green = 1000,
		Purple = 100,
		Gray = 1
	}
	public enum ClientProtocol
	{
		TCP,
		WebSocket
	}
	public enum Noisy
	{
		NotSet,
		True,
		False
	}
	public enum PaidLevel
	{
		One = 1,
		Two,
		Three,
		Four,
		Five,
		Six,
		Seven,
		Eight,
		Nine,
		Ten
	}
	public enum SendReceiveDirection
	{
		Sent,
		Received
	}
	public enum SubscriptionPlan
	{
		NotSet,
		Prime,
		Tier1,
		Tier2,
		Tier3
	}
	[Flags]
	public enum UserDetails
	{
		None = 0,
		Moderator = 1,
		Turbo = 2,
		Subscriber = 4,
		Vip = 8,
		Partner = 0x10,
		Staff = 0x20
	}
	public enum UserType : byte
	{
		Viewer,
		Moderator,
		GlobalModerator,
		Broadcaster,
		Admin,
		Staff
	}
}
namespace TwitchLib.Client.Enums.Internal
{
	public enum IrcCommand
	{
		Unknown,
		PrivMsg,
		Notice,
		Ping,
		Pong,
		Join,
		Part,
		ClearChat,
		ClearMsg,
		UserState,
		GlobalUserState,
		Nick,
		Pass,
		Cap,
		RPL_001,
		RPL_002,
		RPL_003,
		RPL_004,
		RPL_353,
		RPL_366,
		RPL_372,
		RPL_375,
		RPL_376,
		Whisper,
		RoomState,
		Reconnect,
		ServerChange,
		UserNotice,
		Mode
	}
}

TwitchLib.Client.Models.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.CodeAnalysis;
using TwitchLib.Client.Enums;
using TwitchLib.Client.Enums.Internal;
using TwitchLib.Client.Models.Extensions;
using TwitchLib.Client.Models.Extractors;
using TwitchLib.Client.Models.Interfaces;
using TwitchLib.Client.Models.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: InternalsVisibleTo("TwitchLib.Client")]
[assembly: InternalsVisibleTo("TwitchLib.Client.Test")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2023")]
[assembly: AssemblyDescription("Project contains all of the models used in TwitchLib.Client.")]
[assembly: AssemblyFileVersion("4.0.0")]
[assembly: AssemblyInformationalVersion("4.0.0+5ef35d539836f8bcd29bd836a23b9e853020acfa")]
[assembly: AssemblyProduct("TwitchLib.Client.Models")]
[assembly: AssemblyTitle("TwitchLib.Client.Models")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.Client")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("4.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public class HypeChat
{
	public int Amount { get; internal set; }

	public double CalculatedAmount => (Exponent == 0) ? Amount : (Amount / (10 * Exponent));

	public string Currency { get; internal set; } = null;


	public int Exponent { get; internal set; }

	public PaidLevel Level { get; internal set; }

	public bool IsSystemMessage { get; internal set; }

	internal static bool TrySetTag(ref HypeChat? hypeChat, KeyValuePair<string, string> tag)
	{
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		switch (tag.Key)
		{
		case "pinned-chat-paid-amount":
			(hypeChat ?? (hypeChat = new HypeChat())).Amount = int.Parse(tag.Value);
			break;
		case "pinned-chat-paid-currency":
			(hypeChat ?? (hypeChat = new HypeChat())).Currency = tag.Value;
			break;
		case "pinned-chat-paid-exponent":
			(hypeChat ?? (hypeChat = new HypeChat())).Exponent = int.Parse(tag.Value);
			break;
		case "pinned-chat-paid-level":
		{
			HypeChat? obj = hypeChat ?? (hypeChat = new HypeChat());
			if (!Enum.TryParse<PaidLevel>(tag.Value, ignoreCase: true, out PaidLevel result))
			{
				throw new ArgumentException("Requested value '" + tag.Value + "' was not found.");
			}
			obj.Level = result;
			break;
		}
		case "pinned-chat-paid-is-system-message":
			(hypeChat ?? (hypeChat = new HypeChat())).IsSystemMessage = TagHelper.ToBool(tag.Value);
			break;
		default:
			return false;
		}
		return true;
	}
}
namespace TwitchLib.Client.Models
{
	public class Announcement : UserNoticeBase
	{
		public string MsgParamColor { get; protected set; } = null;


		public string Message { get; protected set; }

		public Announcement(IrcMessage ircMessage)
			: base(ircMessage)
		{
			Message = ircMessage.Message;
		}

		public Announcement(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, string msgParamColor, string message)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			MsgParamColor = msgParamColor;
			Message = message;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			string key = tag.Key;
			string text = key;
			if (text == "msg-param-color")
			{
				MsgParamColor = tag.Value;
				return true;
			}
			return false;
		}
	}
	public class AnonGiftPaidUpgrade : UserNoticeBase
	{
		public int MsgParamPromoGiftTotal { get; protected set; }

		public string MsgParamPromoName { get; protected set; } = null;


		public AnonGiftPaidUpgrade(IrcMessage ircMessage)
			: base(ircMessage)
		{
		}

		public AnonGiftPaidUpgrade(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, int msgParamPromoGiftTotal, string msgParamPromoName)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			MsgParamPromoGiftTotal = msgParamPromoGiftTotal;
			MsgParamPromoName = msgParamPromoName;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			string key = tag.Key;
			string text = key;
			if (!(text == "msg-param-promo-gift-total"))
			{
				if (!(text == "msg-param-promo-name"))
				{
					return false;
				}
				MsgParamPromoName = tag.Value;
			}
			else
			{
				MsgParamPromoGiftTotal = int.Parse(tag.Value);
			}
			return true;
		}
	}
	public class BitsBadgeTier : UserNoticeBase
	{
		public int MsgParamThreshold { get; protected set; }

		public BitsBadgeTier(IrcMessage ircMessage)
			: base(ircMessage)
		{
		}

		public BitsBadgeTier(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, int msgParamThreshold)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			MsgParamThreshold = msgParamThreshold;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			string key = tag.Key;
			string text = key;
			if (text == "msg-param-threshold")
			{
				MsgParamThreshold = int.Parse(tag.Value);
			}
			return true;
		}
	}
	public class ChannelState
	{
		public string BroadcasterLanguage { get; } = null;


		public string Channel { get; }

		public bool? EmoteOnly { get; }

		public TimeSpan? FollowersOnly { get; } = null;


		public bool Mercury { get; }

		public bool? R9K { get; }

		public bool? Rituals { get; }

		public string RoomId { get; } = null;


		public int? SlowMode { get; }

		public bool? SubOnly { get; }

		public Dictionary<string, string>? UndocumentedTags { get; }

		public ChannelState(IrcMessage ircMessage)
		{
			foreach (KeyValuePair<string, string> tag in ircMessage.Tags)
			{
				string value = tag.Value;
				switch (tag.Key)
				{
				case "broadcaster-lang":
					BroadcasterLanguage = value;
					break;
				case "emote-only":
					EmoteOnly = TagHelper.ToBool(value);
					break;
				case "r9k":
					R9K = TagHelper.ToBool(value);
					break;
				case "rituals":
					Rituals = TagHelper.ToBool(value);
					break;
				case "slow":
				{
					int result;
					bool flag = int.TryParse(tag.Value, out result);
					SlowMode = (flag ? new int?(result) : null);
					break;
				}
				case "subs-only":
					SubOnly = TagHelper.ToBool(value);
					break;
				case "followers-only":
				{
					if (int.TryParse(value, out var result2))
					{
						FollowersOnly = ((result2 > -1) ? TimeSpan.FromMinutes(result2) : Timeout.InfiniteTimeSpan);
					}
					break;
				}
				case "room-id":
					RoomId = value;
					break;
				case "mercury":
					Mercury = TagHelper.ToBool(value);
					break;
				default:
					(UndocumentedTags ?? (UndocumentedTags = new Dictionary<string, string>())).Add(tag.Key, tag.Value);
					break;
				}
			}
			Channel = ircMessage.Channel;
		}

		public ChannelState(bool r9k, bool rituals, bool subonly, int slowMode, bool emoteOnly, string broadcasterLanguage, string channel, TimeSpan followersOnly, bool mercury, string roomId)
		{
			R9K = r9k;
			Rituals = rituals;
			SubOnly = subonly;
			SlowMode = slowMode;
			EmoteOnly = emoteOnly;
			BroadcasterLanguage = broadcasterLanguage;
			Channel = channel;
			FollowersOnly = followersOnly;
			Mercury = mercury;
			RoomId = roomId;
		}
	}
	public class ChatMessage : TwitchLibMessage
	{
		private readonly ChatReply? _chatReply;

		private readonly HypeChat? _hypeChat;

		protected readonly MessageEmoteCollection? _emoteCollection;

		public List<KeyValuePair<string, string>> BadgeInfo { get; } = null;


		public int Bits { get; }

		public double BitsInDollars { get; }

		public string Channel { get; }

		public CheerBadge? CheerBadge { get; }

		public string? CustomRewardId { get; }

		public string? EmoteReplacedMessage { get; }

		public string Id { get; } = null;


		public bool IsBroadcaster { get; }

		public bool IsFirstMessage { get; }

		public bool IsHighlighted { get; internal set; }

		public bool IsMe { get; }

		public bool IsSkippingSubMode { get; internal set; }

		public string Message { get; }

		public Noisy Noisy { get; }

		public string RoomId { get; } = null;


		public int SubscribedMonthCount { get; }

		public DateTimeOffset TmiSent { get; }

		public ChatReply? ChatReply => _chatReply;

		public HypeChat? HypeChat => _hypeChat;

		public ChatMessage(string botUsername, IrcMessage ircMessage, MessageEmoteCollection? emoteCollection = null, bool replaceEmotes = false, string prefix = "", string suffix = "")
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_074e: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_065f: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0648: Unknown result type (might be due to invalid IL or missing references)
			//IL_064a: Unknown result type (might be due to invalid IL or missing references)
			//IL_064b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0688: Unknown result type (might be due to invalid IL or missing references)
			//IL_068a: Unknown result type (might be due to invalid IL or missing references)
			//IL_068b: Unknown result type (might be due to invalid IL or missing references)
			base.BotUsername = botUsername;
			base.RawIrcMessage = ircMessage.ToString();
			Message = ircMessage.Message;
			if (Message.Length > 0 && (byte)Message[0] == 1 && (byte)Message[Message.Length - 1] == 1 && Message.StartsWith("\u0001ACTION ") && Message.EndsWith("\u0001"))
			{
				Message = Message.Trim('\u0001').Substring(7);
				IsMe = true;
			}
			_emoteCollection = emoteCollection;
			base.Username = ircMessage.User;
			Channel = ircMessage.Channel;
			UserDetails val = (UserDetails)0;
			foreach (KeyValuePair<string, string> tag in ircMessage.Tags)
			{
				string key = tag.Key;
				string value = tag.Value;
				switch (key)
				{
				case "badges":
					base.Badges = TagHelper.ToBadges(value);
					foreach (KeyValuePair<string, string> badge in base.Badges)
					{
						string key2 = badge.Key;
						string text = key2;
						if (!(text == "bits"))
						{
							if (text == "subscriber" && SubscribedMonthCount == 0)
							{
								SubscribedMonthCount = int.Parse(badge.Value);
							}
						}
						else
						{
							CheerBadge = new CheerBadge(int.Parse(badge.Value));
						}
					}
					break;
				case "badge-info":
				{
					BadgeInfo = TagHelper.ToBadges(value);
					KeyValuePair<string, string> keyValuePair = BadgeInfo.Find((KeyValuePair<string, string> b) => b.Key == "founder");
					if (!keyValuePair.Equals(default(KeyValuePair<string, string>)))
					{
						SubscribedMonthCount = int.Parse(keyValuePair.Value);
						break;
					}
					KeyValuePair<string, string> keyValuePair2 = BadgeInfo.Find((KeyValuePair<string, string> b) => b.Key == "subscriber");
					if (!keyValuePair2.Equals(default(KeyValuePair<string, string>)))
					{
						SubscribedMonthCount = int.Parse(keyValuePair2.Value);
					}
					break;
				}
				case "bits":
					Bits = int.Parse(value);
					BitsInDollars = ConvertBitsToUsd(Bits);
					break;
				case "color":
					base.HexColor = value;
					break;
				case "custom-reward-id":
					CustomRewardId = value;
					break;
				case "display-name":
					base.DisplayName = value;
					break;
				case "emotes":
					base.EmoteSet = new EmoteSet(value, Message);
					break;
				case "first-msg":
					IsFirstMessage = value == "1";
					break;
				case "id":
					Id = value;
					break;
				case "msg-id":
					HandleMsgId(value);
					break;
				case "mod":
					if (TagHelper.ToBool(tag.Value))
					{
						val = (UserDetails)(val | 1);
					}
					break;
				case "noisy":
					Noisy = (Noisy)(TagHelper.ToBool(value) ? 1 : 2);
					break;
				case "room-id":
					RoomId = value;
					break;
				case "subscriber":
					if (TagHelper.ToBool(tag.Value))
					{
						val = (UserDetails)(val | 4);
					}
					break;
				case "tmi-sent-ts":
					TmiSent = TagHelper.ToDateTimeOffsetFromUnixMs(value);
					break;
				case "turbo":
					if (TagHelper.ToBool(tag.Value))
					{
						val = (UserDetails)(val | 2);
					}
					break;
				case "user-id":
					base.UserId = value;
					break;
				case "user-type":
					base.UserType = TagHelper.ToUserType(value);
					break;
				default:
					if (!TwitchLib.Client.Models.ChatReply.TrySetTag(ref _chatReply, tag) && !global::HypeChat.TrySetTag(ref _hypeChat, tag))
					{
						(base.UndocumentedTags ?? (base.UndocumentedTags = new Dictionary<string, string>())).Add(tag.Key, tag.Value);
					}
					break;
				}
			}
			base.UserDetail = new UserDetail(val, base.Badges);
			if (_emoteCollection != null)
			{
				EmoteSet emoteSet = base.EmoteSet;
				if (emoteSet != null && emoteSet.Emotes.Count > 0)
				{
					SpanSliceEnumerator enumerator3 = new SpanSliceEnumerator(base.EmoteSet.RawEmoteSetString, '/').GetEnumerator();
					while (enumerator3.MoveNext())
					{
						ReadOnlySpan<char> current3 = enumerator3.Current;
						int num = current3.IndexOf(':');
						int num2 = current3.IndexOf(',');
						if (num2 == -1)
						{
							num2 = current3.Length;
						}
						int num3 = current3.IndexOf('-');
						if (num > 0 && num3 > num && num2 > num3)
						{
							ReadOnlySpan<char> s = current3.Slice(num + 1, num3 - num - 1);
							ReadOnlySpan<char> s2 = current3.Slice(num3 + 1, num2 - num3 - 1);
							if (int.TryParse(s, out var result) && int.TryParse(s2, out var result2) && result >= 0 && result < result2 && result2 < Message.Length)
							{
								string id = current3.Slice(0, num).ToString();
								string text2 = Message.Substring(result, result2 - result + 1);
								_emoteCollection.Add(new MessageEmote(id, text2));
							}
						}
					}
					if (replaceEmotes)
					{
						EmoteReplacedMessage = _emoteCollection?.ReplaceEmotes(Message, null, prefix, suffix);
					}
				}
			}
			if (base.EmoteSet == null)
			{
				EmoteSet emoteSet3 = (base.EmoteSet = new EmoteSet((string?)null, Message));
			}
			if (string.IsNullOrEmpty(base.DisplayName))
			{
				base.DisplayName = base.Username;
			}
			if (string.Equals(Channel, base.Username, StringComparison.InvariantCultureIgnoreCase))
			{
				base.UserType = (UserType)3;
				IsBroadcaster = true;
			}
			string[] array = Channel.Split(':');
			if (array.Length == 3 && string.Equals(array[1], base.UserId, StringComparison.InvariantCultureIgnoreCase))
			{
				base.UserType = (UserType)3;
				IsBroadcaster = true;
			}
		}

		public ChatMessage(string botUsername, string userId, string userName, string displayName, string hexColor, EmoteSet emoteSet, string message, UserType userType, string channel, string id, int subscribedMonthCount, string roomId, bool isMe, bool isBroadcaster, Noisy noisy, string rawIrcMessage, string emoteReplacedMessage, List<KeyValuePair<string, string>> badges, CheerBadge cheerBadge, int bits, double bitsInDollars, UserDetail userDetail)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			base.BotUsername = botUsername;
			base.UserId = userId;
			base.DisplayName = displayName;
			base.HexColor = hexColor;
			base.EmoteSet = emoteSet;
			Message = message;
			base.UserType = userType;
			Channel = channel;
			Id = id;
			SubscribedMonthCount = subscribedMonthCount;
			RoomId = roomId;
			IsMe = isMe;
			IsBroadcaster = isBroadcaster;
			Noisy = noisy;
			base.RawIrcMessage = rawIrcMessage;
			EmoteReplacedMessage = emoteReplacedMessage;
			base.Badges = badges;
			CheerBadge = cheerBadge;
			Bits = bits;
			BitsInDollars = bitsInDollars;
			base.Username = userName;
			base.UserDetail = userDetail;
		}

		private void HandleMsgId(string val)
		{
			if (val == "highlighted-message")
			{
				IsHighlighted = true;
			}
			else if (val == "skip-subs-mode-message")
			{
				IsSkippingSubMode = true;
			}
		}

		private static double ConvertBitsToUsd(int bits)
		{
			if (1 == 0)
			{
			}
			double result = ((bits < 10000) ? ((bits < 1500) ? ((double)bits / 100.0 * 1.4) : ((bits >= 5000) ? ((double)bits / 5000.0 * 64.4) : ((double)bits / 1500.0 * 19.95))) : ((bits >= 25000) ? ((double)bits / 25000.0 * 308.0) : ((double)bits / 10000.0 * 126.0)));
			if (1 == 0)
			{
			}
			return result;
		}
	}
	public class ChatReply
	{
		public string ParentDisplayName { get; internal set; } = null;


		public string ParentMsgBody { get; internal set; } = null;


		public string ParentMsgId { get; internal set; } = null;


		public string ParentUserId { get; internal set; } = null;


		public string ParentUserLogin { get; internal set; } = null;


		public string ThreadParentMsgId { get; internal set; } = null;


		public string ThreadParentUserLogin { get; internal set; } = null;


		internal static bool TrySetTag(ref ChatReply? reply, KeyValuePair<string, string> tag)
		{
			switch (tag.Key)
			{
			case "reply-parent-display-name":
				(reply ?? (reply = new ChatReply())).ParentDisplayName = tag.Value;
				break;
			case "reply-parent-msg-body":
				(reply ?? (reply = new ChatReply())).ParentMsgBody = tag.Value;
				break;
			case "reply-parent-msg-id":
				(reply ?? (reply = new ChatReply())).ParentMsgId = tag.Value;
				break;
			case "reply-parent-user-id":
				(reply ?? (reply = new ChatReply())).ParentUserId = tag.Value;
				break;
			case "reply-parent-user-login":
				(reply ?? (reply = new ChatReply())).ParentUserLogin = tag.Value;
				break;
			case "reply-thread-parent-msg-id":
				(reply ?? (reply = new ChatReply())).ThreadParentMsgId = tag.Value;
				break;
			case "reply-thread-parent-user-login":
				(reply ?? (reply = new ChatReply())).ThreadParentUserLogin = tag.Value;
				break;
			default:
				return false;
			}
			return true;
		}
	}
	public class CheerBadge
	{
		public int CheerAmount { get; }

		public BadgeColor Color { get; }

		public CheerBadge(int cheerAmount)
		{
			//IL_0012: 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)
			CheerAmount = cheerAmount;
			Color = GetColor(cheerAmount);
		}

		private BadgeColor GetColor(int cheerAmount)
		{
			//IL_0015: 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_0053: 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)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (cheerAmount >= 10000)
			{
				return (BadgeColor)10000;
			}
			if (cheerAmount >= 5000)
			{
				return (BadgeColor)5000;
			}
			if (cheerAmount >= 1000)
			{
				return (BadgeColor)1000;
			}
			return (BadgeColor)((cheerAmount < 100) ? 1 : 100);
		}
	}
	public class CommandInfo
	{
		public char Identifier { get; }

		public string Name { get; }

		public string ArgumentsAsString { get; }

		public List<string> ArgumentsAsList { get; }

		public CommandInfo(char identifier, string name)
			: this(identifier, name, string.Empty, new List<string>())
		{
		}

		public CommandInfo(char identifier, string name, string argumentsAsString, List<string> argumentsAsList)
		{
			Identifier = identifier;
			Name = name;
			ArgumentsAsString = argumentsAsString;
			ArgumentsAsList = argumentsAsList;
		}

		public static bool TryParse(ReadOnlySpan<char> s, [MaybeNullWhen(false)] out CommandInfo result)
		{
			result = null;
			s = s.Trim();
			if (s.IsEmpty)
			{
				return false;
			}
			char identifier = s[0];
			s = s.Slice(1);
			if (s.IsEmpty || s[0] == ' ')
			{
				return false;
			}
			int num = s.IndexOf(' ');
			if (num == -1)
			{
				string name = s.ToString();
				result = new CommandInfo(identifier, name);
			}
			else
			{
				string name2 = s.Slice(0, num).ToString();
				s = s.Slice(num + 1).TrimStart();
				string argumentsAsString = s.ToString();
				result = new CommandInfo(identifier, name2, argumentsAsString, ParseArgumentsToList(s));
			}
			return true;
			static List<string> ParseArgumentsToList(ReadOnlySpan<char> s)
			{
				List<string> list = new List<string>();
				while (!s.IsEmpty)
				{
					bool flag = s[0] == '"';
					int num2;
					if (s[0] == '"')
					{
						s = s.Slice(1);
						num2 = s.IndexOf('"');
					}
					else
					{
						num2 = s.IndexOfAny('"', ' ');
					}
					if (num2 == -1)
					{
						list.Add(s.ToString());
						s = default(ReadOnlySpan<char>);
					}
					else
					{
						list.Add(s.Slice(0, num2).ToString());
						if (!flag && s[num2] == '"')
						{
							num2--;
						}
						s = s.Slice(num2 + 1);
					}
					s = s.TrimStart();
				}
				return list;
			}
		}

		public override string ToString()
		{
			return (ArgumentsAsString.Length == 0) ? $"{Identifier}{Name}" : $"{Identifier}{Name} {ArgumentsAsString}";
		}
	}
	public class CommunityPayForward : UserNoticeBase
	{
		public bool MsgParamPriorGifterAnonymous { get; protected set; }

		public string MsgParamPriorGifterDisplayName { get; protected set; } = null;


		public string MsgParamPriorGifterId { get; protected set; } = null;


		public string MsgParamPriorGifterUserName { get; protected set; } = null;


		public CommunityPayForward(IrcMessage ircMessage)
			: base(ircMessage)
		{
		}

		public CommunityPayForward(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, bool msgParamPriorGifterAnonymous, string msgParamPriorGifterDisplayName, string msgParamPriorGifterId, string msgParamPriorGifterUserName)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			MsgParamPriorGifterAnonymous = msgParamPriorGifterAnonymous;
			MsgParamPriorGifterDisplayName = msgParamPriorGifterDisplayName;
			MsgParamPriorGifterId = msgParamPriorGifterId;
			MsgParamPriorGifterUserName = msgParamPriorGifterUserName;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			switch (tag.Key)
			{
			case "msg-param-prior-gifter-anonymous":
				MsgParamPriorGifterAnonymous = bool.Parse(tag.Value);
				break;
			case "msg-param-prior-gifter-display-name":
				MsgParamPriorGifterDisplayName = tag.Value;
				break;
			case "msg-param-prior-gifter-id":
				MsgParamPriorGifterId = tag.Value;
				break;
			case "msg-param-prior-gifter-user-name":
				MsgParamPriorGifterUserName = tag.Value;
				break;
			default:
				return false;
			}
			return true;
		}
	}
	public class CommunitySubscription : UserNoticeBase
	{
		private Goal? _goal;

		public bool IsAnonymous { get; }

		public Goal? MsgParamGoal
		{
			get
			{
				return _goal;
			}
			protected set
			{
				_goal = value;
			}
		}

		public string MsgParamGiftTheme { get; protected set; } = null;


		public int MsgParamMassGiftCount { get; protected set; }

		public string MsgParamOriginId { get; protected set; } = null;


		public int MsgParamSenderCount { get; protected set; }

		public SubscriptionPlan MsgParamSubPlan { get; protected set; }

		public CommunitySubscription(IrcMessage ircMessage)
			: base(ircMessage)
		{
			IsAnonymous = base.UserId == "274598607";
		}

		public CommunitySubscription(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, Goal? msgParamGoal, string msgParamGiftTheme, int msgParamMassGiftCount, string msgParamOriginId, int msgParamSenderCount, SubscriptionPlan msgParamSubPlan)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			IsAnonymous = userId == "274598607";
			MsgParamGoal = msgParamGoal;
			MsgParamGiftTheme = msgParamGiftTheme;
			MsgParamMassGiftCount = msgParamMassGiftCount;
			MsgParamOriginId = msgParamOriginId;
			MsgParamSenderCount = msgParamSenderCount;
			MsgParamSubPlan = msgParamSubPlan;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			switch (tag.Key)
			{
			case "msg-param-gift-theme":
				MsgParamGiftTheme = tag.Value;
				break;
			case "msg-param-mass-gift-count":
				MsgParamMassGiftCount = int.Parse(tag.Value);
				break;
			case "msg-param-sender-count":
				MsgParamSenderCount = int.Parse(tag.Value);
				break;
			case "msg-param-sub-plan":
				MsgParamSubPlan = TagHelper.ToSubscriptionPlan(tag.Value);
				break;
			default:
				return Goal.TrySetTag(ref _goal, tag);
			}
			return true;
		}
	}
	public class ConnectionCredentials
	{
		private static readonly Regex UsernameCheckRegex = new Regex("^([a-zA-Z0-9][a-zA-Z0-9_]{4,25})$");

		public string TwitchOAuth { get; }

		public string TwitchUsername { get; }

		public Capabilities Capabilities { get; }

		private static Regex GetUsernameCheckRegex()
		{
			return UsernameCheckRegex;
		}

		public ConnectionCredentials(string? twitchUsername = null, string? twitchOAuth = null, bool disableUsernameCheck = false, Capabilities? capabilities = null)
		{
			if (twitchUsername != null && !disableUsernameCheck && !GetUsernameCheckRegex().Match(twitchUsername).Success)
			{
				throw new Exception("Twitch username does not appear to be valid. " + twitchUsername);
			}
			TwitchUsername = twitchUsername?.ToLower() ?? $"justinfan{new Random().Next(1000, 89999)}";
			TwitchOAuth = twitchOAuth ?? string.Empty;
			if (!TwitchOAuth.Contains(":"))
			{
				TwitchOAuth = "oauth:" + TwitchOAuth.Replace("oauth", "");
			}
			Capabilities = capabilities ?? new Capabilities();
		}
	}
	public class Capabilities
	{
		public bool Membership { get; }

		public bool Tags { get; }

		public bool Commands { get; }

		public Capabilities(bool membership = true, bool tags = true, bool commands = true)
		{
			Membership = membership;
			Tags = tags;
			Commands = commands;
		}
	}
	public class ContinuedGiftedSubscription : UserNoticeBase
	{
		public int MsgParamPromoGiftTotal { get; protected set; }

		public string MsgParamPromoName { get; protected set; } = null;


		public string MsgParamSenderLogin { get; protected set; } = null;


		public string MsgParamSenderName { get; protected set; } = null;


		public ContinuedGiftedSubscription(IrcMessage ircMessage)
			: base(ircMessage)
		{
		}

		public ContinuedGiftedSubscription(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, int msgParamPromoGiftTotal, string msgParamPromoName, string msgParamSenderLogin, string msgParamSenderName)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			MsgParamPromoGiftTotal = msgParamPromoGiftTotal;
			MsgParamPromoName = msgParamPromoName;
			MsgParamSenderLogin = msgParamSenderLogin;
			MsgParamSenderName = msgParamSenderName;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			switch (tag.Key)
			{
			case "msg-param-promo-gift-total":
				MsgParamPromoGiftTotal = int.Parse(tag.Value);
				break;
			case "msg-param-promo-name":
				MsgParamPromoName = tag.Value;
				break;
			case "msg-param-sender-login":
				MsgParamSenderLogin = tag.Value;
				break;
			case "msg-param-sender-name":
				MsgParamSenderName = tag.Value;
				break;
			default:
				return false;
			}
			return true;
		}
	}
	public class Emote
	{
		public string Id { get; }

		public string Name { get; }

		public int StartIndex { get; }

		public int EndIndex { get; }

		public string ImageUrl { get; }

		public Emote(string emoteId, string name, int emoteStartIndex, int emoteEndIndex)
		{
			Id = emoteId;
			Name = name;
			StartIndex = emoteStartIndex;
			EndIndex = emoteEndIndex;
			ImageUrl = "https://static-cdn.jtvnw.net/emoticons/v1/" + emoteId + "/1.0";
		}
	}
	public class EmoteSet
	{
		public List<Emote> Emotes { get; }

		public string? RawEmoteSetString { get; }

		public EmoteSet(string? rawEmoteSetString, string message)
		{
			RawEmoteSetString = rawEmoteSetString;
			Emotes = EmoteExtractor.Extract(rawEmoteSetString, message);
		}

		public EmoteSet(IEnumerable<Emote> emotes, string rawEmoteSetString)
		{
			RawEmoteSetString = rawEmoteSetString;
			Emotes = emotes.ToList();
		}
	}
	public class ErrorEvent
	{
		public string Message { get; }

		public ErrorEvent(string message)
		{
			Message = message;
		}
	}
	public class GiftedSubscription : UserNoticeBase
	{
		private Goal? _goal;

		public Goal? MsgParamGoal
		{
			get
			{
				return _goal;
			}
			protected set
			{
				_goal = value;
			}
		}

		public bool IsAnonymous { get; }

		public string MsgParamMonths { get; protected set; } = null;


		public string MsgParamOriginId { get; protected set; }

		public string MsgParamRecipientDisplayName { get; protected set; } = null;


		public string MsgParamRecipientId { get; protected set; } = null;


		public string MsgParamRecipientUserName { get; protected set; } = null;


		public int MsgParamSenderCount { get; protected set; }

		public SubscriptionPlan MsgParamSubPlan { get; protected set; }

		public string MsgParamSubPlanName { get; protected set; } = null;


		public int MsgParamMultiMonthGiftDuration { get; protected set; }

		public GiftedSubscription(IrcMessage ircMessage)
			: base(ircMessage)
		{
			IsAnonymous = base.UserId == "274598607";
		}

		public GiftedSubscription(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, Goal? msgParamGoal, string msgParamMonths, string msgParamOriginId, string msgParamRecipientDisplayName, string msgParamRecipientId, string msgParamRecipientUserName, int msgParamSenderCount, SubscriptionPlan msgParamSubPlan, string msgParamSubPlanName, int msgParamMultiMonthGiftDuration)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			MsgParamGoal = msgParamGoal;
			IsAnonymous = userId == "274598607";
			MsgParamMonths = msgParamMonths;
			MsgParamOriginId = msgParamOriginId;
			MsgParamRecipientDisplayName = msgParamRecipientDisplayName;
			MsgParamRecipientId = msgParamRecipientId;
			MsgParamRecipientUserName = msgParamRecipientUserName;
			MsgParamSenderCount = msgParamSenderCount;
			MsgParamSubPlan = msgParamSubPlan;
			MsgParamSubPlanName = msgParamSubPlanName;
			MsgParamMultiMonthGiftDuration = msgParamMultiMonthGiftDuration;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			switch (tag.Key)
			{
			case "msg-param-months":
				MsgParamMonths = tag.Value;
				break;
			case "msg-param-origin-id":
				MsgParamOriginId = tag.Value;
				break;
			case "msg-param-recipient-display-name":
				MsgParamRecipientDisplayName = tag.Value;
				break;
			case "msg-param-recipient-id":
				MsgParamRecipientId = tag.Value;
				break;
			case "msg-param-recipient-user-name":
				MsgParamRecipientUserName = tag.Value;
				break;
			case "msg-param-sub-plan-name":
				MsgParamSubPlanName = tag.Value;
				break;
			case "msg-param-sub-plan":
				MsgParamSubPlan = TagHelper.ToSubscriptionPlan(tag.Value);
				break;
			case "msg-param-gift-months":
				MsgParamMultiMonthGiftDuration = int.Parse(tag.Value);
				break;
			default:
				return Goal.TrySetTag(ref _goal, tag);
			}
			return true;
		}
	}
	public class Goal
	{
		public string ContributionType { get; protected set; } = null;


		public int CurrentContributions { get; protected set; }

		public string? Description { get; protected set; }

		public int TargetContributions { get; protected set; }

		public int UserContributions { get; protected set; }

		internal static bool TrySetTag(ref Goal? goal, KeyValuePair<string, string> tag)
		{
			switch (tag.Key)
			{
			case "msg-param-goal-contribution-type":
				(goal ?? (goal = new Goal())).ContributionType = tag.Value;
				break;
			case "msg-param-goal-current-contributions":
				(goal ?? (goal = new Goal())).CurrentContributions = int.Parse(tag.Value);
				break;
			case "msg-param-goal-description":
				(goal ?? (goal = new Goal())).Description = tag.Value;
				break;
			case "msg-param-goal-target-contributions":
				(goal ?? (goal = new Goal())).TargetContributions = int.Parse(tag.Value);
				break;
			case "msg-param-goal-user-contributions":
				(goal ?? (goal = new Goal())).UserContributions = int.Parse(tag.Value);
				break;
			default:
				return false;
			}
			return true;
		}
	}
	public class JoinedChannel
	{
		public string Channel { get; }

		public ChatMessage? PreviousMessage { get; protected set; }

		public JoinedChannel(string channel)
		{
			Channel = channel;
		}

		public void HandleMessage(ChatMessage message)
		{
			PreviousMessage = message;
		}
	}
	public class MessageEmote
	{
		public delegate string ReplaceEmoteDelegate(MessageEmote caller);

		public enum EmoteSource
		{
			Twitch,
			FrankerFaceZ,
			BetterTwitchTv,
			SevenTv
		}

		public enum EmoteSize
		{
			Small,
			Medium,
			Large
		}

		public static readonly ReadOnlyCollection<string> TwitchEmoteUrls = new ReadOnlyCollection<string>(new string[3] { "https://static-cdn.jtvnw.net/emoticons/v1/{0}/1.0", "https://static-cdn.jtvnw.net/emoticons/v1/{0}/2.0", "https://static-cdn.jtvnw.net/emoticons/v1/{0}/3.0" });

		public static readonly ReadOnlyCollection<string> FrankerFaceZEmoteUrls = new ReadOnlyCollection<string>(new string[3] { "//cdn.frankerfacez.com/emoticon/{0}/1", "//cdn.frankerfacez.com/emoticon/{0}/2", "//cdn.frankerfacez.com/emoticon/{0}/4" });

		public static readonly ReadOnlyCollection<string> BetterTwitchTvEmoteUrls = new ReadOnlyCollection<string>(new string[3] { "//cdn.betterttv.net/emote/{0}/1x", "//cdn.betterttv.net/emote/{0}/2x", "//cdn.betterttv.net/emote/{0}/3x" });

		public static readonly ReadOnlyCollection<string> SevenTvEmoteUrls = new ReadOnlyCollection<string>(new string[3] { "//cdn.7tv.app/emote/{0}/1x.avif", "//cdn.7tv.app/emote/{0}/2x.avif", "//cdn.7tv.app/emote/{0}/5x.avif" });

		public string Id { get; }

		public string Text { get; }

		public EmoteSource Source { get; }

		public EmoteSize Size { get; }

		public string ReplacementString => ReplacementDelegate(this);

		public static ReplaceEmoteDelegate ReplacementDelegate { get; set; } = SourceMatchingReplacementText;


		public string EscapedText { get; }

		public static string SourceMatchingReplacementText(MessageEmote caller)
		{
			int size = (int)caller.Size;
			EmoteSource source = caller.Source;
			if (1 == 0)
			{
			}
			string result = source switch
			{
				EmoteSource.SevenTv => string.Format(SevenTvEmoteUrls[size], caller.Id), 
				EmoteSource.BetterTwitchTv => string.Format(BetterTwitchTvEmoteUrls[size], caller.Id), 
				EmoteSource.FrankerFaceZ => string.Format(FrankerFaceZEmoteUrls[size], caller.Id), 
				EmoteSource.Twitch => string.Format(TwitchEmoteUrls[size], caller.Id), 
				_ => caller.Text, 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		public MessageEmote(string id, string text, EmoteSource source = EmoteSource.Twitch, EmoteSize size = EmoteSize.Small, ReplaceEmoteDelegate? replacementDelegate = null)
		{
			Id = id;
			Text = text;
			EscapedText = Regex.Escape(text);
			Source = source;
			Size = size;
			if (replacementDelegate != null)
			{
				ReplacementDelegate = replacementDelegate;
			}
		}
	}
	public class MessageEmoteCollection
	{
		public delegate bool EmoteFilterDelegate(MessageEmote emote);

		private readonly Dictionary<string, MessageEmote> _emotes;

		private const string BasePattern = "(\\b {0}\\b)|(\\b{0} \\b)|(?<=\\W){0}(?=$)|(?<=\\s){0}(?=\\s)|(^{0}$)";

		private string? _currentPattern;

		private Regex? _regex;

		private readonly EmoteFilterDelegate _preferredFilter;

		private string? CurrentPattern
		{
			get
			{
				return _currentPattern;
			}
			set
			{
				if ((!(_currentPattern?.Equals(value))) ?? true)
				{
					_currentPattern = value;
					PatternChanged = true;
				}
			}
		}

		private Regex? CurrentRegex
		{
			get
			{
				if (PatternChanged)
				{
					if (CurrentPattern != null)
					{
						_regex = new Regex(string.Format(CurrentPattern, ""));
						PatternChanged = false;
					}
					else
					{
						_regex = null;
					}
				}
				return _regex;
			}
		}

		private bool PatternChanged { get; set; }

		private EmoteFilterDelegate CurrentEmoteFilter { get; set; } = AllInclusiveEmoteFilter;


		public MessageEmoteCollection()
		{
			_emotes = new Dictionary<string, MessageEmote>();
			_preferredFilter = AllInclusiveEmoteFilter;
		}

		public MessageEmoteCollection(EmoteFilterDelegate preferredFilter)
			: this()
		{
			_preferredFilter = preferredFilter;
		}

		public void Add(MessageEmote emote)
		{
			if (_emotes.TryAdd(emote.Text, emote))
			{
				if (CurrentPattern == null)
				{
					CurrentPattern = string.Format(null, "(\\b {0}\\b)|(\\b{0} \\b)|(?<=\\W){0}(?=$)|(?<=\\s){0}(?=\\s)|(^{0}$)", emote.EscapedText);
				}
				else
				{
					CurrentPattern = CurrentPattern + "|" + string.Format(null, "(\\b {0}\\b)|(\\b{0} \\b)|(?<=\\W){0}(?=$)|(?<=\\s){0}(?=\\s)|(^{0}$)", emote.EscapedText);
				}
			}
		}

		public void Merge(IEnumerable<MessageEmote> emotes)
		{
			IEnumerator<MessageEmote> enumerator = emotes.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Add(enumerator.Current);
			}
			enumerator.Dispose();
		}

		public void Remove(MessageEmote emote)
		{
			if (_emotes.Remove(emote.Text))
			{
				string text = "(^\\(\\\\b" + emote.EscapedText + "\\\\b\\)\\|?)";
				string text2 = "(\\|\\(\\\\b" + emote.EscapedText + "\\\\b\\))";
				string text3 = Regex.Replace(CurrentPattern, text + "|" + text2, "");
				CurrentPattern = (text3.Equals("") ? null : text3);
			}
		}

		public void RemoveAll()
		{
			_emotes.Clear();
			CurrentPattern = null;
		}

		public string ReplaceEmotes(string originalMessage, EmoteFilterDelegate? del = null, string prefix = "", string suffix = "")
		{
			string prefix2 = prefix;
			string suffix2 = suffix;
			if (CurrentRegex == null)
			{
				return originalMessage;
			}
			if (del != null && (Delegate?)del != (Delegate?)CurrentEmoteFilter)
			{
				CurrentEmoteFilter = del;
			}
			string text = CurrentRegex.Replace(originalMessage, delegate(Match match)
			{
				string key = match.Value.Trim();
				if (match.Value[0] == ' ')
				{
					prefix2 += " ";
				}
				if (match.Value[match.Value.Length - 1] == ' ')
				{
					suffix2 = " " + suffix2;
				}
				MessageEmote value;
				return (!_emotes.TryGetValue(key, out value)) ? match.Value : (CurrentEmoteFilter(value) ? (prefix2 + value.ReplacementString + suffix2) : match.Value);
			});
			CurrentEmoteFilter = _preferredFilter;
			return text.Replace("  ", " ");
		}

		public static bool AllInclusiveEmoteFilter(MessageEmote emote)
		{
			return true;
		}

		public static bool TwitchOnlyEmoteFilter(MessageEmote emote)
		{
			return emote.Source == MessageEmote.EmoteSource.Twitch;
		}
	}
	public class OutboundChatMessage
	{
		public string Channel { get; set; }

		public string Message { get; set; }

		public string? ReplyToId { get; set; }

		public OutboundChatMessage(string channel, string message)
		{
			Channel = channel;
			Message = message;
		}

		public override string ToString()
		{
			string text = Channel.ToLower();
			return (ReplyToId == null) ? ("PRIVMSG #" + text + " :" + Message) : ("@reply-parent-msg-id=" + ReplyToId + " PRIVMSG #" + text + " :" + Message);
		}
	}
	public class PrimePaidSubscriber : UserNoticeBase
	{
		public SubscriptionPlan MsgParamSubPlan { get; protected set; }

		public string ResubMessage { get; }

		public PrimePaidSubscriber(IrcMessage ircMessage)
			: base(ircMessage)
		{
			ResubMessage = ircMessage.Message;
		}

		public PrimePaidSubscriber(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, SubscriptionPlan msgParamSubPlan, string resubMessage)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			MsgParamSubPlan = msgParamSubPlan;
			ResubMessage = resubMessage;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			string key = tag.Key;
			string text = key;
			if (text == "msg-param-sub-plan")
			{
				MsgParamSubPlan = TagHelper.ToSubscriptionPlan(tag.Value);
				return true;
			}
			return false;
		}
	}
	public class RaidNotification : UserNoticeBase
	{
		public string MsgParamDisplayName { get; protected set; } = null;


		public string MsgParamLogin { get; protected set; } = null;


		public string MsgParamViewerCount { get; protected set; } = null;


		public RaidNotification(IrcMessage ircMessage)
			: base(ircMessage)
		{
		}

		public RaidNotification(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, string msgParamDisplayName, string msgParamLogin, string msgParamViewerCount)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			MsgParamDisplayName = msgParamDisplayName;
			MsgParamLogin = msgParamLogin;
			MsgParamViewerCount = msgParamViewerCount;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			switch (tag.Key)
			{
			case "msg-param-displayName":
				MsgParamDisplayName = tag.Value;
				break;
			case "msg-param-login":
				MsgParamLogin = tag.Value;
				break;
			case "msg-param-viewerCount":
				MsgParamViewerCount = tag.Value;
				break;
			default:
				return false;
			}
			return true;
		}
	}
	public class ReSubscriber : UserNoticeBase
	{
		public int MsgParamCumulativeMonths { get; protected set; }

		public bool MsgParamShouldShareStreak { get; protected set; }

		public int MsgParamStreakMonths { get; protected set; }

		public SubscriptionPlan MsgParamSubPlan { get; protected set; }

		public string MsgParamSubPlanName { get; protected set; } = null;


		public string ResubMessage { get; }

		public ReSubscriber(IrcMessage ircMessage)
			: base(ircMessage)
		{
			ResubMessage = ircMessage.Message;
		}

		public ReSubscriber(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, int msgParamCumulativeMonths, bool msgParamShouldShareStreak, int msgParamStreakMonths, SubscriptionPlan msgParamSubPlan, string msgParamSubPlanName, string resubMessage)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			MsgParamCumulativeMonths = msgParamCumulativeMonths;
			MsgParamShouldShareStreak = msgParamShouldShareStreak;
			MsgParamStreakMonths = msgParamStreakMonths;
			MsgParamSubPlan = msgParamSubPlan;
			MsgParamSubPlanName = msgParamSubPlanName;
			ResubMessage = resubMessage;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			switch (tag.Key)
			{
			case "msg-param-cumulative-months":
				MsgParamCumulativeMonths = int.Parse(tag.Value);
				break;
			case "msg-param-should-share-streak":
				MsgParamShouldShareStreak = TagHelper.ToBool(tag.Value);
				break;
			case "msg-param-streak-months":
				MsgParamStreakMonths = int.Parse(tag.Value);
				break;
			case "msg-param-sub-plan":
				MsgParamSubPlan = TagHelper.ToSubscriptionPlan(tag.Value);
				break;
			case "msg-param-sub-plan-name":
				MsgParamSubPlanName = tag.Value;
				break;
			default:
				return false;
			}
			return true;
		}
	}
	public class Ritual : UserNoticeBase
	{
		public string MsgParamRitualName { get; protected set; } = null;


		public string Message { get; protected set; }

		public Ritual(IrcMessage ircMessage)
			: base(ircMessage)
		{
			Message = ircMessage.Message;
		}

		public Ritual(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, string msgParamRitualName, string message)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			MsgParamRitualName = msgParamRitualName;
			Message = message;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			string key = tag.Key;
			string text = key;
			if (text == "msg-param-ritual-name")
			{
				MsgParamRitualName = tag.Value;
				return true;
			}
			return false;
		}
	}
	public class SendOptions : ISendOptions
	{
		public uint SendsAllowedInPeriod { get; }

		public ushort SendDelay { get; }

		public TimeSpan ThrottlingPeriod { get; } = TimeSpan.FromSeconds(30.0);


		public uint QueueCapacity { get; }

		public TimeSpan CacheItemTimeout { get; }

		public SendOptions(uint sendsAllowedInPeriod = 20u, uint queueCapacity = 10000u, uint cacheItemTimeoutInMinutes = 30u, ushort sendDelay = 50)
		{
			SendsAllowedInPeriod = sendsAllowedInPeriod;
			QueueCapacity = queueCapacity;
			CacheItemTimeout = TimeSpan.FromMinutes(cacheItemTimeoutInMinutes);
			SendDelay = sendDelay;
		}
	}
	public class SentMessage : IHexColorProperty
	{
		public List<KeyValuePair<string, string>> Badges { get; }

		public string Channel { get; }

		public string HexColor { get; }

		public string DisplayName { get; }

		public string EmoteSet { get; }

		public bool IsModerator { get; }

		public bool IsSubscriber { get; }

		public string Message { get; }

		public UserType UserType { get; }

		public SentMessage(UserState state, string message)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			Badges = state.Badges;
			Channel = state.Channel;
			HexColor = state.HexColor;
			DisplayName = state.DisplayName;
			EmoteSet = state.EmoteSet;
			IsModerator = state.IsModerator;
			IsSubscriber = state.IsSubscriber;
			UserType = state.UserType;
			Message = message;
		}

		public SentMessage(List<KeyValuePair<string, string>> badges, string channel, string hexColor, string displayName, string emoteSet, bool isModerator, bool isSubscriber, UserType userType, string message)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			Badges = badges;
			Channel = channel;
			HexColor = hexColor;
			DisplayName = displayName;
			EmoteSet = emoteSet;
			IsModerator = isModerator;
			IsSubscriber = isSubscriber;
			UserType = userType;
			Message = message;
		}
	}
	public class StandardPayForward : UserNoticeBase
	{
		public bool MsgParamPriorGifterAnonymous { get; protected set; }

		public string MsgParamPriorGifterDisplayName { get; protected set; } = null;


		public long MsgParamPriorGifterId { get; protected set; }

		public string MsgParamPriorGifterUserName { get; protected set; } = null;


		public string? MsgParamRecipientDisplayName { get; protected set; }

		public long? MsgParamRecipientId { get; protected set; }

		public string? MsgParamRecipientUserName { get; protected set; }

		public StandardPayForward(IrcMessage ircMessage)
			: base(ircMessage)
		{
		}

		public StandardPayForward(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, bool msgParamPriorGifterAnonymous, string msgParamPriorGifterDisplayName, long msgParamPriorGifterId, string msgParamPriorGifterUserName, string? msgParamRecipientDisplayName, long? msgParamRecipientId, string? msgParamRecipientUserName)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			MsgParamPriorGifterAnonymous = msgParamPriorGifterAnonymous;
			MsgParamPriorGifterDisplayName = msgParamPriorGifterDisplayName;
			MsgParamPriorGifterId = msgParamPriorGifterId;
			MsgParamPriorGifterUserName = msgParamPriorGifterUserName;
			MsgParamRecipientDisplayName = msgParamRecipientDisplayName;
			MsgParamRecipientId = msgParamRecipientId;
			MsgParamRecipientUserName = msgParamRecipientUserName;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			switch (tag.Key)
			{
			case "msg-param-prior-gifter-anonymous":
				MsgParamPriorGifterAnonymous = bool.Parse(tag.Value);
				break;
			case "msg-param-prior-gifter-display-name":
				MsgParamPriorGifterDisplayName = tag.Value;
				break;
			case "msg-param-prior-gifter-id":
				MsgParamPriorGifterId = long.Parse(tag.Value);
				break;
			case "msg-param-prior-gifter-user-name":
				MsgParamPriorGifterUserName = tag.Value;
				break;
			case "msg-param-recipient-display-name":
				MsgParamRecipientDisplayName = tag.Value;
				break;
			case "msg-param-recipient-id":
				MsgParamRecipientId = long.Parse(tag.Value);
				break;
			case "msg-param-recipient-user-name":
				MsgParamRecipientUserName = tag.Value;
				break;
			default:
				return false;
			}
			return true;
		}
	}
	public class Subscriber : UserNoticeBase
	{
		public int MsgParamCumulativeMonths { get; protected set; }

		public bool MsgParamShouldShareStreak { get; protected set; }

		public int MsgParamStreakMonths { get; protected set; }

		public SubscriptionPlan MsgParamSubPlan { get; protected set; }

		public string MsgParamSubPlanName { get; protected set; } = null;


		public string ResubMessage { get; }

		public Subscriber(IrcMessage ircMessage)
			: base(ircMessage)
		{
			ResubMessage = ircMessage.Message;
		}

		public Subscriber(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags, int msgParamCumulativeMonths, bool msgParamShouldShareStreak, int msgParamStreakMonths, SubscriptionPlan msgParamSubPlan, string msgParamSubPlanName, string resubMessage)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			MsgParamCumulativeMonths = msgParamCumulativeMonths;
			MsgParamShouldShareStreak = msgParamShouldShareStreak;
			MsgParamStreakMonths = msgParamStreakMonths;
			MsgParamSubPlan = msgParamSubPlan;
			MsgParamSubPlanName = msgParamSubPlanName;
			ResubMessage = resubMessage;
		}

		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			switch (tag.Key)
			{
			case "msg-param-cumulative-months":
				MsgParamCumulativeMonths = int.Parse(tag.Value);
				break;
			case "msg-param-should-share-streak":
				MsgParamShouldShareStreak = TagHelper.ToBool(tag.Value);
				break;
			case "msg-param-streak-months":
				MsgParamStreakMonths = int.Parse(tag.Value);
				break;
			case "msg-param-sub-plan":
				MsgParamSubPlan = TagHelper.ToSubscriptionPlan(tag.Value);
				break;
			case "msg-param-sub-plan-name":
				MsgParamSubPlanName = tag.Value;
				break;
			default:
				return false;
			}
			return true;
		}
	}
	public abstract class TwitchLibMessage : IHexColorProperty
	{
		public List<KeyValuePair<string, string>> Badges { get; protected set; } = null;


		public string BotUsername { get; protected set; } = null;


		public string HexColor { get; protected set; } = null;


		public string DisplayName { get; protected set; } = null;


		public EmoteSet EmoteSet { get; protected set; } = null;


		public string UserId { get; protected set; } = null;


		public string Username { get; protected set; } = null;


		public UserDetail UserDetail { get; protected set; }

		public UserType UserType { get; protected set; }

		public string RawIrcMessage { get; protected set; } = null;


		public Dictionary<string, string>? UndocumentedTags { get; protected set; }
	}
	public class UnraidNotification : UserNoticeBase
	{
		public UnraidNotification(IrcMessage ircMessage)
			: base(ircMessage)
		{
		}

		public UnraidNotification(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags)
			: base(badgeInfo, badges, hexColor, displayName, emotes, id, login, msgId, roomId, systemMsg, tmiSent, userDetail, userId, userType, undocumentedTags)
		{
		}//IL_0018: Unknown result type (might be due to invalid IL or missing references)


		protected override bool TrySet(KeyValuePair<string, string> tag)
		{
			return false;
		}
	}
	public class UserBan
	{
		public string Channel { get; }

		public string Username { get; }

		public string RoomId { get; } = null;


		public string TargetUserId { get; } = null;


		public UserBan(IrcMessage ircMessage)
		{
			Channel = ircMessage.Channel;
			Username = ircMessage.Message;
			if (ircMessage.Tags.TryGetValue("room-id", out string value))
			{
				RoomId = value;
			}
			if (ircMessage.Tags.TryGetValue("target-user-id", out string value2))
			{
				TargetUserId = value2;
			}
		}

		public UserBan(string channel, string username, string roomId, string targetUserId)
		{
			Channel = channel;
			Username = username;
			RoomId = roomId;
			TargetUserId = targetUserId;
		}
	}
	public readonly struct UserDetail
	{
		private readonly UserDetails _flags;

		public bool IsModerator => ((Enum)_flags).HasFlag((Enum)(object)(UserDetails)1);

		public bool IsSubscriber => ((Enum)_flags).HasFlag((Enum)(object)(UserDetails)4);

		public bool HasTurbo => ((Enum)_flags).HasFlag((Enum)(object)(UserDetails)2);

		public bool IsVip => ((Enum)_flags).HasFlag((Enum)(object)(UserDetails)8);

		public bool IsPartner => ((Enum)_flags).HasFlag((Enum)(object)(UserDetails)16);

		public bool IsStaff => ((Enum)_flags).HasFlag((Enum)(object)(UserDetails)32);

		public UserDetail(UserDetails userDetails)
		{
			//IL_0002: 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)
			_flags = userDetails;
		}

		internal UserDetail(UserDetails userDetails, List<KeyValuePair<string, string>> badges)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: 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_000b: 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)
			UserDetails val = UserDetailsExtractor.Extract(badges);
			_flags = (UserDetails)(userDetails | val);
		}

		public override string ToString()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			UserDetails flags = _flags;
			return ((object)(UserDetails)(ref flags)).ToString();
		}
	}
	public abstract class UserNoticeBase : IHexColorProperty
	{
		internal const string AnonymousGifterUserId = "274598607";

		public List<KeyValuePair<string, string>> BadgeInfo { get; protected set; } = null;


		public List<KeyValuePair<string, string>> Badges { get; protected set; } = null;


		public string HexColor { get; protected set; } = null;


		public string DisplayName { get; protected set; } = null;


		public string Emotes { get; protected set; } = null;


		public string Id { get; protected set; } = null;


		public string Login { get; protected set; } = null;


		public string MsgId { get; protected set; } = null;


		public string RoomId { get; protected set; } = null;


		public string SystemMsg { get; protected set; } = null;


		public DateTimeOffset TmiSent { get; protected set; }

		public UserDetail UserDetail { get; protected set; }

		public string UserId { get; protected set; } = null;


		public UserType UserType { get; protected set; }

		public Dictionary<string, string>? UndocumentedTags { get; protected set; }

		protected UserNoticeBase(IrcMessage ircMessage)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0441: Unknown result type (might be due to invalid IL or missing references)
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_0444: Unknown result type (might be due to invalid IL or missing references)
			UserDetails val = (UserDetails)0;
			foreach (KeyValuePair<string, string> tag in ircMessage.Tags)
			{
				switch (tag.Key)
				{
				case "badge-info":
					BadgeInfo = TagHelper.ToBadges(tag.Value);
					break;
				case "badges":
					Badges = TagHelper.ToBadges(tag.Value);
					break;
				case "color":
					HexColor = tag.Value;
					break;
				case "display-name":
					DisplayName = tag.Value;
					break;
				case "emotes":
					Emotes = tag.Value;
					break;
				case "id":
					Id = tag.Value;
					break;
				case "login":
					Login = tag.Value;
					break;
				case "mod":
					if (TagHelper.ToBool(tag.Value))
					{
						val = (UserDetails)(val | 1);
					}
					break;
				case "msg-id":
					MsgId = tag.Value;
					break;
				case "room-id":
					RoomId = tag.Value;
					break;
				case "subscriber":
					if (TagHelper.ToBool(tag.Value))
					{
						val = (UserDetails)(val | 4);
					}
					break;
				case "system-msg":
					SystemMsg = tag.Value.Replace("\\s", " ");
					break;
				case "tmi-sent-ts":
					TmiSent = TagHelper.ToDateTimeOffsetFromUnixMs(tag.Value);
					break;
				case "turbo":
					if (TagHelper.ToBool(tag.Value))
					{
						val = (UserDetails)(val | 2);
					}
					break;
				case "user-id":
					UserId = tag.Value;
					break;
				case "user-type":
					UserType = TagHelper.ToUserType(tag.Value);
					break;
				default:
					if (!TrySet(tag))
					{
						(UndocumentedTags ?? (UndocumentedTags = new Dictionary<string, string>())).Add(tag.Key, tag.Value);
					}
					break;
				}
			}
			UserDetail = new UserDetail(val, Badges);
		}

		protected UserNoticeBase(List<KeyValuePair<string, string>> badgeInfo, List<KeyValuePair<string, string>> badges, string hexColor, string displayName, string emotes, string id, string login, string msgId, string roomId, string systemMsg, DateTimeOffset tmiSent, UserDetail userDetail, string userId, UserType userType, Dictionary<string, string>? undocumentedTags)
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			BadgeInfo = badgeInfo;
			Badges = badges;
			HexColor = hexColor;
			DisplayName = displayName;
			Emotes = emotes;
			Id = id;
			Login = login;
			MsgId = msgId;
			RoomId = roomId;
			SystemMsg = systemMsg;
			TmiSent = tmiSent;
			UserDetail = userDetail;
			UserId = userId;
			UserType = userType;
			UndocumentedTags = undocumentedTags;
		}

		protected abstract bool TrySet(KeyValuePair<string, string> tag);
	}
	public class UserState : IHexColorProperty
	{
		public List<KeyValuePair<string, string>> Badges { get; } = new List<KeyValuePair<string, string>>();


		public List<KeyValuePair<string, string>> BadgeInfo { get; } = new List<KeyValuePair<string, string>>();


		public string Channel { get; }

		public string HexColor { get; } = null;


		public string DisplayName { get; } = null;


		public string EmoteSet { get; } = null;


		public string Id { get; } = null;


		public bool IsModerator { get; }

		public bool IsSubscriber { get; }

		public bool Turbo { get; }

		public UserType UserType { get; }

		public Dictionary<string, string>? UndocumentedTags { get; }

		public UserState(IrcMessage ircMessage)
		{
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: 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)
			Channel = ircMessage.Channel;
			foreach (KeyValuePair<string, string> tag in ircMessage.Tags)
			{
				string value = tag.Value;
				switch (tag.Key)
				{
				case "badges":
					Badges = TagHelper.ToBadges(value);
					break;
				case "badge-info":
					BadgeInfo = TagHelper.ToBadges(value);
					break;
				case "color":
					HexColor = value;
					break;
				case "display-name":
					DisplayName = value;
					break;
				case "emote-sets":
					EmoteSet = value;
					break;
				case "id":
					Id = value;
					break;
				case "mod":
					IsModerator = TagHelper.ToBool(value);
					break;
				case "subscriber":
					IsSubscriber = TagHelper.ToBool(value);
					break;
				case "turbo":
					Turbo = TagHelper.ToBool(value);
					break;
				case "user-type":
					UserType = TagHelper.ToUserType(tag.Value);
					break;
				default:
					(UndocumentedTags ?? (UndocumentedTags = new Dictionary<string, string>())).Add(tag.Key, tag.Value);
					break;
				}
			}
			if (string.Equals(ircMessage.User, Channel, StringComparison.InvariantCultureIgnoreCase))
			{
				UserType = (UserType)3;
			}
		}

		public UserState(List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string hexColor, string displayName, string emoteSet, string channel, string id, bool isSubscriber, bool isModerator, UserType userType)
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			Badges = badges;
			BadgeInfo = badgeInfo;
			HexColor = hexColor;
			DisplayName = displayName;
			EmoteSet = emoteSet;
			Channel = channel;
			Id = id;
			IsSubscriber = isSubscriber;
			IsModerator = isModerator;
			UserType = userType;
		}
	}
	public class UserTimeout
	{
		public string Channel { get; }

		public TimeSpan TimeoutDuration { get; }

		public string Username { get; }

		public string TargetUserId { get; } = null;


		public Dictionary<string, string>? UndocumentedTags { get; }

		public UserTimeout(IrcMessage ircMessage)
		{
			Channel = ircMessage.Channel;
			Username = ircMessage.Message;
			foreach (KeyValuePair<string, string> tag in ircMessage.Tags)
			{
				string value = tag.Value;
				string key = tag.Key;
				string text = key;
				if (!(text == "ban-duration"))
				{
					if (text == "target-user-id")
					{
						TargetUserId = value;
					}
					else
					{
						(UndocumentedTags ?? (UndocumentedTags = new Dictionary<string, string>())).Add(tag.Key, tag.Value);
					}
				}
				else
				{
					TimeoutDuration = TimeSpan.FromSeconds(int.Parse(value));
				}
			}
		}

		public UserTimeout(string channel, string username, string targetUserId, TimeSpan timeoutDuration)
		{
			Channel = channel;
			Username = username;
			TargetUserId = targetUserId;
			TimeoutDuration = timeoutDuration;
		}
	}
	public class WhisperMessage : TwitchLibMessage
	{
		public string MessageId { get; } = null;


		public string ThreadId { get; } = null;


		public string Message { get; }

		public WhisperMessage(List<KeyValuePair<string, string>> badges, string hexColor, string username, string displayName, EmoteSet emoteSet, string threadId, string messageId, string userId, string botUsername, string message, UserDetail userDetail, UserType userType)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			base.Badges = badges;
			base.HexColor = hexColor;
			base.Username = username;
			base.DisplayName = displayName;
			base.EmoteSet = emoteSet;
			ThreadId = threadId;
			MessageId = messageId;
			base.UserId = userId;
			base.UserDetail = userDetail;
			base.BotUsername = botUsername;
			Message = message;
			base.UserType = userType;
		}

		public WhisperMessage(IrcMessage ircMessage, string botUsername)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			base.Username = ircMessage.User;
			base.BotUsername = botUsername;
			base.RawIrcMessage = ircMessage.ToString();
			Message = ircMessage.Message;
			UserDetails val = (UserDetails)0;
			foreach (KeyValuePair<string, string> tag in ircMessage.Tags)
			{
				string value = tag.Value;
				switch (tag.Key)
				{
				case "badges":
					base.Badges = TagHelper.ToBadges(value);
					break;
				case "color":
					base.HexColor = value;
					break;
				case "display-name":
					base.DisplayName = value;
					break;
				case "emotes":
					base.EmoteSet = new EmoteSet(value, Message);
					break;
				case "message-id":
					MessageId = value;
					break;
				case "thread-id":
					ThreadId = value;
					break;
				case "turbo":
					if (TagHelper.ToBool(tag.Value))
					{
						val = (UserDetails)(val | 2);
					}
					break;
				case "user-id":
					base.UserId = value;
					break;
				case "user-type":
					base.UserType = TagHelper.ToUserType(tag.Value);
					break;
				default:
					(base.UndocumentedTags ?? (base.UndocumentedTags = new Dictionary<string, string>())).Add(tag.Key, tag.Value);
					break;
				}
			}
			base.UserDetail = new UserDetail(val, base.Badges);
			if (base.EmoteSet == null)
			{
				EmoteSet emoteSet2 = (base.EmoteSet = new EmoteSet((string?)null, Message));
			}
		}
	}
}
namespace TwitchLib.Client.Models.Internal
{
	public class IrcMessage
	{
		private string? _channel;

		private readonly string[]? _parameters;

		private string? _rawString;

		public string Channel => _channel ?? (_channel = (Params.StartsWith("#") ? Params.Remove(0, 1) : Params));

		public string Params
		{
			get
			{
				string[]? parameters = _parameters;
				return (parameters != null && parameters.Length != 0) ? _parameters[0] : "";
			}
		}

		public string Message => Trailing;

		public string Trailing
		{
			get
			{
				string[]? parameters = _parameters;
				return (parameters != null && parameters.Length > 1) ? _parameters[_parameters.Length - 1] : "";
			}
		}

		public string User { get; }

		public string? Hostmask { get; }

		public IrcCommand Command { get; }

		public Dictionary<string, string> Tags { get; }

		public IrcMessage(string user)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			_parameters = null;
			User = user;
			Hostmask = null;
			Command = (IrcCommand)0;
			Tags = new Dictionary<string, string>();
		}

		public IrcMessage(IrcCommand command, string[] parameters, string hostmask, Dictionary<string, string>? tags = null)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Invalid comparison between Unknown and I4
			int num = hostmask.IndexOf('!');
			User = ((num >= 0) ? hostmask.Substring(0, num) : hostmask);
			Hostmask = hostmask;
			Command = command;
			Tags = tags ?? new Dictionary<string, string>();
			_parameters = parameters;
			if ((int)command == 18 && Params.Length > 0 && Params.Contains("#"))
			{
				_parameters[0] = "#" + _parameters[0].Split('#')[1];
			}
		}

		internal IrcMessage(string raw, IrcCommand command, string[] parameters, string user, string hostmask, Dictionary<string, string>? tags = null)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Invalid comparison between Unknown and I4
			User = user;
			Hostmask = hostmask;
			Command = command;
			Tags = tags ?? new Dictionary<string, string>();
			_rawString = raw;
			_parameters = parameters;
			if ((int)command == 18 && Params.Length > 0 && Params.Contains("#"))
			{
				_parameters[0] = "#" + _parameters[0].Split('#')[1];
			}
		}

		public override string ToString()
		{
			return _rawString ?? (_rawString = GenerateToString());
		}

		private string GenerateToString()
		{
			//IL_00cf: 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)
			StringBuilder stringBuilder = new StringBuilder(128);
			Dictionary<string, string> tags = Tags;
			if (tags != null && tags.Count > 0)
			{
				stringBuilder.Append('@');
				foreach (KeyValuePair<string, string> tag in Tags)
				{
					stringBuilder.Append(tag.Key).Append('=').Append(tag.Value)
						.Append(';');
				}
				stringBuilder[stringBuilder.Length - 1] = ' ';
			}
			if (!string.IsNullOrEmpty(Hostmask))
			{
				stringBuilder.Append(':').Append(Hostmask).Append(' ');
			}
			IrcCommand command = Command;
			stringBuilder.Append(((object)(IrcCommand)(ref command)).ToString().ToUpperInvariant().Replace("RPL_", ""));
			if (_parameters == null || _parameters.Length == 0)
			{
				return stringBuilder.ToString();
			}
			if (!string.IsNullOrEmpty(_parameters[0]))
			{
				stringBuilder.Append(" ").Append(_parameters[0]);
			}
			if (_parameters.Length > 1)
			{
				string obj = _parameters[1];
				if (obj != null && obj.Length > 0)
				{
					stringBuilder.Append(" :").Append(_parameters[1]);
				}
			}
			return stringBuilder.ToString();
		}
	}
	public static class MsgIds
	{
		public const string AlreadyBanned = "already_banned";

		public const string AlreadyEmotesOff = "already_emotes_off";

		public const string AlreadyEmotesOn = "already_emotes_on";

		public const string AlreadyR9KOff = "already_r9k_off";

		public const string AlreadyR9KOn = "already_r9k_on";

		public const string AlreadySubsOff = "already_subs_off";

		public const string AlreadySubsOn = "already_subs_on";

		public const string AnonGiftPaidUpgrade = "anongiftpaidupgrade";

		public const string Announcement = "announcement";

		public const string BadUnbanNoBan = "bad_unban_no_ban";

		public const string BanSuccess = "ban_success";

		public const string BitsBadgeTier = "bitsbadgetier";

		public const string ColorChanged = "color_changed";

		public const string CommunityPayForward = "communitypayforward";

		public const string EmoteOnlyOff = "emote_only_off";

		public const string EmoteOnlyOn = "emote_only_on";

		public const string HighlightedMessage = "highlighted-message";

		public const string ModeratorsReceived = "room_mods";

		public const string NoMods = "no_mods";

		public const string NoVIPs = "no_vips";

		public const string MsgBannedEmailAlias = "msg_banned_email_alias";

		public const string MsgChannelSuspended = "msg_channel_suspended";

		public const string MsgRequiresVerifiedPhoneNumber = "msg_requires_verified_phone_number";

		public const string MsgVerifiedEmail = "msg_verified_email";

		public const string MsgRateLimit = "msg_ratelimit";

		public const string MsgDuplicate = "msg_duplicate";

		public const string MsgR9k = "msg_r9k";

		public const string MsgFollowersOnly = "msg_followersonly";

		public const string MsgSubsOnly = "msg_subsonly";

		public const string MsgEmoteOnly = "msg_emoteonly";

		public const string MsgSuspended = "msg_suspended";

		public const string MsgBanned = "msg_banned";

		public const string MsgSlowMode = "msg_slowmode";

		public const string NoPermission = "no_permission";

		public const string PrimePaidUprade = "primepaidupgrade";

		public const string Raid = "raid";

		public const string RaidErrorSelf = "raid_error_self";

		public const string RaidNoticeMature = "raid_notice_mature";

		public const string ReSubscription = "resub";

		public const string Ritual = "ritual";

		public const string R9KOff = "r9k_off";

		public const string R9KOn = "r9k_on";

		public const string StandardPayForward = "standardpayforward";

		public const string SubGift = "subgift";

		public const string CommunitySubscription = "submysterygift";

		public const string ContinuedGiftedSubscription = "giftpaidupgrade";

		public const string Subscription = "sub";

		public const string SubsOff = "subs_off";

		public const string SubsOn = "subs_on";

		public const string TimeoutSuccess = "timeout_success";

		public const string UnbanSuccess = "unban_success";

		public const string Unraid = "unraid";

		public const string UnrecognizedCmd = "unrecognized_cmd";

		public const string UserIntro = "user-intro";

		public const string VIPsSuccess = "vips_success";

		public const string SkipSubsModeMessage = "skip-subs-mode-message";
	}
	internal static class TagHelper
	{
		public static List<KeyValuePair<string, string>> ToBadges(string badgesStr)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			if (badgesStr.Contains('/'))
			{
				SpanSliceEnumerator enumerator = new SpanSliceEnumerator(badgesStr, ',').GetEnumerator();
				while (enumerator.MoveNext())
				{
					ReadOnlySpan<char> current = enumerator.Current;
					int num = current.IndexOf('/');
					string key = current.Slice(0, num).ToString();
					string value = current.Slice(num + 1).ToString();
					list.Add(new KeyValuePair<string, string>(key, value));
				}
			}
			return list;
		}

		public static UserType ToUserType(string s)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (1 == 0)
			{
			}
			UserType result = (UserType)(s switch
			{
				"mod" => 1, 
				"global_mod" => 2, 
				"admin" => 4, 
				"staff" => 5, 
				_ => 0, 
			});
			if (1 == 0)
			{
			}
			return result;
		}

		public static SubscriptionPlan ToSubscriptionPlan(string s)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (1 == 0)
			{
			}
			SubscriptionPlan result;
			switch (s)
			{
			case "Prime":
			case "prime":
				result = (SubscriptionPlan)1;
				break;
			case "1000":
				result = (SubscriptionPlan)2;
				break;
			case "2000":
				result = (SubscriptionPlan)3;
				break;
			case "3000":
				result = (SubscriptionPlan)4;
				break;
			default:
				throw new ArgumentException("Unhandled value " + s + " for UserType", "s");
			}
			if (1 == 0)
			{
			}
			return result;
		}

		public static bool ToBool(string s)
		{
			return s == "1";
		}

		public static DateTimeOffset ToDateTimeOffsetFromUnixMs(string s)
		{
			long milliseconds = long.Parse(s);
			return DateTimeOffset.FromUnixTimeMilliseconds(milliseconds);
		}
	}
	public static class Tags
	{
		public const string Badges = "badges";

		public const string BadgeInfo = "badge-info";

		public const string BanDuration = "ban-duration";

		public const string BanReason = "ban-reason";

		public const string BroadcasterLang = "broadcaster-lang";

		public const string Bits = "bits";

		public const string Color = "color";

		public const string CustomRewardId = "custom-reward-id";

		public const string DisplayName = "display-name";

		public const string Emotes = "emotes";

		public const string EmoteOnly = "emote-only";

		public const string EmotesSets = "emote-sets";

		public const string FirstMessage = "first-msg";

		public const string Flags = "flags";

		public const string FollowersOnly = "followers-only";

		public const string Id = "id";

		public const string Login = "login";

		public const string Mercury = "mercury";

		public const string MessageId = "message-id";

		public const string Mod = "mod";

		public const string MsgId = "msg-id";

		public const string MsgParamColor = "msg-param-color";

		public const string MsgParamDisplayname = "msg-param-displayName";

		public const string MsgParamLogin = "msg-param-login";

		public const string MsgParamCumulativeMonths = "msg-param-cumulative-months";

		public const string MsgParamGiftTheme = "msg-param-gift-theme";

		public const string MsgParamGoalContributionType = "msg-param-goal-contribution-type";

		public const string MsgParamGoalCurrentContributions = "msg-param-goal-current-contributions";

		public const string MsgParamGoalDescription = "msg-param-goal-description";

		public const string MsgParamGoalTargetContributions = "msg-param-goal-target-contributions";

		public const string MsgParamGoalUserContributions = "msg-param-goal-user-contributions";

		public const string MsgParamMonths = "msg-param-months";

		public const string MsgParamPriorGifterAnonymous = "msg-param-prior-gifter-anonymous";

		public const string MsgParamPriorGifterDisplayName = "msg-param-prior-gifter-display-name";

		public const string MsgParamPriorGifterId = "msg-param-prior-gifter-id";

		public const string MsgParamPriorGifterUserName = "msg-param-prior-gifter-user-name";

		public const string MsgParamPromoGiftTotal = "msg-param-promo-gift-total";

		public const string MsgParamPromoName = "msg-param-promo-name";

		public const string MsgParamShouldShareStreak = "msg-param-should-share-streak";

		public const string MsgParamStreakMonths = "msg-param-streak-months";

		public const string MsgParamSubPlan = "msg-param-sub-plan";

		public const string MsgParamSubPlanName = "msg-param-sub-plan-name";

		public const string MsgParamViewerCount = "msg-param-viewerCount";

		public const string MsgParamOriginId = "msg-param-origin-id";

		public const string MsgParamRecipientDisplayName = "msg-param-recipient-display-name";

		public const string MsgParamRecipientId = "msg-param-recipient-id";

		public const string MsgParamRecipientUsername = "msg-param-recipient-user-name";

		public const string MsgParamRitualName = "msg-param-ritual-name";

		public const string MsgParamMassGiftCount = "msg-param-mass-gift-count";

		public const string MsgParamSenderCount = "msg-param-sender-count";

		public const string MsgParamSenderLogin = "msg-param-sender-login";

		public const string MsgParamSenderName = "msg-param-sender-name";

		public const string MsgParamThreshold = "msg-param-threshold";

		public const string Noisy = "noisy";

		public const string PinnedChatPaidAmount = "pinned-chat-paid-amount";

		public const string PinnedChatPaidCurrency = "pinned-chat-paid-currency";

		public const string PinnedChatPaidExponent = "pinned-chat-paid-exponent";

		public const string PinnedChatPaidLevel = "pinned-chat-paid-level";

		public const string PinnedChatPaidIsSystemMessage = "pinned-chat-paid-is-system-message";

		public const string ReplyParentDisplayName = "reply-parent-display-name";

		public const string ReplyParentMsgBody = "reply-parent-msg-body";

		public const string ReplyParentMsgId = "reply-parent-msg-id";

		public const string ReplyParentUserId = "reply-parent-user-id";

		public const string ReplyParentUserLogin = "reply-parent-user-login";

		public const string ReplyThreadParentMsgId = "reply-thread-parent-msg-id";

		public const string ReplyThreadParentUserLogin = "reply-thread-parent-user-login";

		public const string Rituals = "rituals";

		public const string RoomId = "room-id";

		public const string R9K = "r9k";

		public const string Slow = "slow";

		public const string Subscriber = "subscriber";

		public const string SubsOnly = "subs-only";

		public const string SystemMsg = "system-msg";

		public const string ThreadId = "thread-id";

		public const string TmiSentTs = "tmi-sent-ts";

		public const string Turbo = "turbo";

		public const string UserId = "user-id";

		public const string UserType = "user-type";

		public const string MsgParamMultiMonthGiftDuration = "msg-param-gift-months";

		public const string TargetUserId = "target-user-id";
	}
}
namespace TwitchLib.Client.Models.Interfaces
{
	public interface IHexColorProperty
	{
		string HexColor { get; }
	}
	public interface ISendOptions
	{
		uint SendsAllowedInPeriod { get; }

		ushort SendDelay { get; }

		TimeSpan ThrottlingPeriod { get; }

		TimeSpan CacheItemTimeout { get; }

		uint QueueCapacity { get; }
	}
}
namespace TwitchLib.Client.Models.Extractors
{
	public static class EmoteExtractor
	{
		public static List<Emote> Extract(string? rawEmoteSetString, string message)
		{
			List<Emote> list = new List<Emote>();
			if (string.IsNullOrEmpty(rawEmoteSetString) || string.IsNullOrEmpty(message))
			{
				return list;
			}
			StringInfo stringInfo = new StringInfo(message);
			SpanSliceEnumerator spanSliceEnumerator = new SpanSliceEnumerator(rawEmoteSetString, '/');
			SpanSliceEnumerator enumerator = spanSliceEnumerator.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ReadOnlySpan<char> current = enumerator.Current;
				int num = current.IndexOf(':');
				string emoteId = current.Slice(0, num).ToString();
				spanSliceEnumerator = new SpanSliceEnumerator(current.Slice(num + 1), ',');
				SpanSliceEnumerator enumerator2 = spanSliceEnumerator.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					ReadOnlySpan<char> current2 = enumerator2.Current;
					num = current2.IndexOf('-');
					ReadOnlySpan<char> s = current2.Slice(0, num);
					ReadOnlySpan<char> s2 = current2.Slice(num + 1);
					int num2 = int.Parse(s);
					int num3 = int.Parse(s2);
					int num4 = stringInfo.SubstringByTextElements(0, num2 + 1).Length - 1;
					string text = stringInfo.SubstringByTextElements(num2, num3 - num2 + 1);
					int emoteEndIndex = num4 + text.Length - 1;
					list.Add(new Emote(emoteId, text, num4, emoteEndIndex));
				}
			}
			return list;
		}
	}
	internal static class UserDetailsExtractor
	{
		public static UserDetails Extract(List<KeyValuePair<string, string>> badges)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			UserDetails val = (UserDetails)0;
			foreach (KeyValuePair<string, string> badge in badges)
			{
				UserDetails val2 = val;
				string key = badge.Key;
				if (1 == 0)
				{
				}
				UserDetails val3;
				switch (key)
				{
				case "founder":
				case "subscriber":
					val3 = (UserDetails)4;
					break;
				case "admin":
				case "staff":
					val3 = (UserDetails)32;
					break;
				case "partner":
					val3 = (UserDetails)16;
					break;
				case "vip":
					val3 = (UserDetails)8;
					break;
				default:
					val3 = (UserDetails)0;
					break;
				}
				if (1 == 0)
				{
				}
				val = (UserDetails)(val2 | val3);
			}
			return val;
		}
	}
}
namespace TwitchLib.Client.Models.Extensions
{
	internal ref struct SpanSliceEnumerator
	{
		private ReadOnlySpan<char> _span;

		private readonly char _char;

		public ReadOnlySpan<char> Current { get; private set; }

		public SpanSliceEnumerator(ReadOnlySpan<char> span, char @char)
		{
			Current = default(ReadOnlySpan<char>);
			_span = span;
			_char = @char;
		}

		public SpanSliceEnumerator(string str, char @char)
			: this(str.AsSpan(), @char)
		{
		}

		public SpanSliceEnumerator GetEnumerator()
		{
			return this;
		}

		public bool MoveNext()
		{
			if (_span.IsEmpty)
			{
				return false;
			}
			int num = _span.IndexOf(_char);
			if (num == -1)
			{
				Current = _span;
				_span = default(ReadOnlySpan<char>);
			}
			else
			{
				Current = _span.Slice(0, num);
				_span = _span.Slice(num + 1);
			}
			return true;
		}
	}
}
namespace TwitchLib.Client.Models.Builders
{
	public sealed class ChannelStateBuilder : IBuilder<ChannelState>, IFromIrcMessageBuilder<ChannelState>
	{
		private string _broadcasterLanguage;

		private string _channel;

		private bool _emoteOnly;

		private TimeSpan _followersOnly;

		private bool _mercury;

		private bool _r9K;

		private bool _rituals;

		private string _roomId;

		private int _slowMode;

		private bool _subOnly;

		private ChannelStateBuilder()
		{
		}

		public ChannelStateBuilder WithBroadcasterLanguage(string broadcasterLanguage)
		{
			_broadcasterLanguage = broadcasterLanguage;
			return this;
		}

		public ChannelStateBuilder WithChannel(string channel)
		{
			_channel = channel;
			return this;
		}

		public ChannelStateBuilder WithEmoteOnly(bool emoteOnly)
		{
			_emoteOnly = emoteOnly;
			return this;
		}

		public ChannelStateBuilder WIthFollowersOnly(TimeSpan followersOnly)
		{
			_followersOnly = followersOnly;
			return this;
		}

		public ChannelStateBuilder WithMercury(bool mercury)
		{
			_mercury = mercury;
			return this;
		}

		public ChannelStateBuilder WithR9K(bool r9k)
		{
			_r9K = r9k;
			return this;
		}

		public ChannelStateBuilder WithRituals(bool rituals)
		{
			_rituals = rituals;
			return this;
		}

		public ChannelStateBuilder WithRoomId(string roomId)
		{
			_roomId = roomId;
			return this;
		}

		public ChannelStateBuilder WithSlowMode(int slowMode)
		{
			_slowMode = slowMode;
			return this;
		}

		public ChannelStateBuilder WithSubOnly(bool subOnly)
		{
			_subOnly = subOnly;
			return this;
		}

		public static ChannelStateBuilder Create()
		{
			return new ChannelStateBuilder();
		}

		public ChannelState Build()
		{
			return new ChannelState(_r9K, _rituals, _subOnly, _slowMode, _emoteOnly, _broadcasterLanguage, _channel, _followersOnly, _mercury, _roomId);
		}

		public ChannelState BuildFromIrcMessage(FromIrcMessageBuilderDataObject fromIrcMessageBuilderDataObject)
		{
			return new ChannelState(fromIrcMessageBuilderDataObject.Message);
		}
	}
	public sealed class ChatMessageBuilder : IBuilder<ChatMessage>
	{
		private TwitchLibMessage _twitchLibMessage;

		private readonly List<KeyValuePair<string, string>> BadgeInfo = new List<KeyValuePair<string, string>>();

		private int _bits;

		private double _bitsInDollars;

		private string _channel;

		private CheerBadge _cheerBadge;

		private string _emoteReplacedMessage;

		private string _id;

		private bool _isBroadcaster;

		private bool _isMe;

		private string _message;

		private Noisy _noisy;

		private string _rawIrcMessage;

		private string _roomId;

		private int _subscribedMonthCount;

		private ChatMessageBuilder()
		{
			_twitchLibMessage = TwitchLibMessageBuilder.Create().Build();
		}

		public ChatMessageBuilder WithTwitchLibMessage(TwitchLibMessage twitchLibMessage)
		{
			_twitchLibMessage = twitchLibMessage;
			return this;
		}

		public ChatMessageBuilder WithBadgeInfos(params KeyValuePair<string, string>[] badgeInfos)
		{
			BadgeInfo.AddRange(badgeInfos);
			return this;
		}

		public ChatMessageBuilder WithBits(int bits)
		{
			_bits = bits;
			return this;
		}

		public ChatMessageBuilder WithBitsInDollars(double bitsInDollars)
		{
			_bitsInDollars = bitsInDollars;
			return this;
		}

		public ChatMessageBuilder WithChannel(string channel)
		{
			_channel = channel;
			return this;
		}

		public ChatMessageBuilder WithCheerBadge(CheerBadge cheerBadge)
		{
			_cheerBadge = cheerBadge;
			return this;
		}

		public ChatMessageBuilder WithEmoteReplaceMessage(string emoteReplaceMessage)
		{
			_emoteReplacedMessage = emoteReplaceMessage;
			return this;
		}

		public ChatMessageBuilder WithId(string id)
		{
			_id = id;
			return this;
		}

		public ChatMessageBuilder WithIsBroadcaster(bool isBroadcaster)
		{
			_isBroadcaster = isBroadcaster;
			return this;
		}

		public ChatMessageBuilder WithIsMe(bool isMe)
		{
			_isMe = isMe;
			return this;
		}

		public ChatMessageBuilder WithMessage(string message)
		{
			_message = message;
			return this;
		}

		public ChatMessageBuilder WithNoisy(Noisy noisy)
		{
			//IL_0002: 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)
			_noisy = noisy;
			return this;
		}

		public ChatMessageBuilder WithRawIrcMessage(string rawIrcMessage)
		{
			_rawIrcMessage = rawIrcMessage;
			return this;
		}

		public ChatMessageBuilder WithRoomId(string roomId)
		{
			_roomId = roomId;
			return this;
		}

		public ChatMessageBuilder WithSubscribedMonthCount(int subscribedMonthCount)
		{
			_subscribedMonthCount = subscribedMonthCount;
			return this;
		}

		public static ChatMessageBuilder Create()
		{
			return new ChatMessageBuilder();
		}

		public ChatMessage Build()
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			return new ChatMessage(_twitchLibMessage.BotUsername, _twitchLibMessage.UserId, _twitchLibMessage.Username, _twitchLibMessage.DisplayName, _twitchLibMessage.HexColor, _twitchLibMessage.EmoteSet, _message, _twitchLibMessage.UserType, _channel, _id, _subscribedMonthCount, _roomId, _isMe, _isBroadcaster, _noisy, _rawIrcMessage, _emoteReplacedMessage, _twitchLibMessage.Badges, _cheerBadge, _bits, _bitsInDollars, _twitchLibMessage.UserDetail);
		}
	}
	public sealed class CheerBadgeBuilder : IBuilder<CheerBadge>
	{
		private int _cheerAmount;

		public CheerBadgeBuilder WithCheerAmount(int cheerAmount)
		{
			_cheerAmount = cheerAmount;
			return this;
		}

		public CheerBadge Build()
		{
			return new CheerBadge(_cheerAmount);
		}
	}
	public sealed class CommunitySubscriptionBuilder : IFromIrcMessageBuilder<CommunitySubscription>
	{
		private CommunitySubscriptionBuilder()
		{
		}

		public static CommunitySubscriptionBuilder Create()
		{
			return new CommunitySubscriptionBuilder();
		}

		public CommunitySubscription BuildFromIrcMessage(FromIrcMessageBuilderDataObject fromIrcMessageBuilderDataObject)
		{
			return new CommunitySubscription(fromIrcMessageBuilderDataObject.Message);
		}
	}
	public sealed class ConnectionCredentialsBuilder : IBuilder<ConnectionCredentials>
	{
		private string _twitchUsername;

		private string _twitchOAuth;

		private bool _disableUsernameCheck;

		private ConnectionCredentialsBuilder()
		{
		}

		public ConnectionCredentialsBuilder WithTwitchUsername(string twitchUsername)
		{
			_twitchUsername = twitchUsername;
			return this;
		}

		public ConnectionCredentialsBuilder WithTwitchOAuth(string twitchOAuth)
		{
			_twitchOAuth = twitchOAuth;
			return this;
		}

		public ConnectionCredentialsBuilder WithDisableUsernameCheck(bool disableUsernameCheck)
		{
			_disableUsernameCheck = disableUsernameCheck;
			return this;
		}

		public static ConnectionCredentialsBuilder Create()
		{
			return new ConnectionCredentialsBuilder();
		}

		public ConnectionCredentials Build()
		{
			return new ConnectionCredentials(_twitchUsername, _twitchOAuth, _disableUsernameCheck);
		}
	}
	public sealed class EmoteBuilder : IBuilder<Emote>
	{
		private string _id;

		private string _name;

		private int _startIndex;

		private int _endIndex;

		private EmoteBuilder()
		{
		}

		public static EmoteBuilder Create()
		{
			return new EmoteBuilder();
		}

		public EmoteBuilder WithId(string id)
		{
			_id = id;
			return this;
		}

		public EmoteBuilder WithName(string name)
		{
			_name = name;
			return this;
		}

		public EmoteBuilder WithStartIndex(int startIndex)
		{
			_startIndex = startIndex;
			return this;
		}

		public EmoteBuilder WithEndIndex(int endIndex)
		{
			_endIndex = endIndex;
			return this;
		}

		public Emote Build()
		{
			return new Emote(_id, _name, _startIndex, _endIndex);
		}
	}
	public sealed class ErrorEventBuilder : IBuilder<ErrorEvent>
	{
		private string _message;

		private ErrorEventB

TwitchLib.Communication.dll

Decompiled a month ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using TwitchLib.Communication.Clients;
using TwitchLib.Communication.Enums;
using TwitchLib.Communication.Events;
using TwitchLib.Communication.Extensions;
using TwitchLib.Communication.Interfaces;
using TwitchLib.Communication.Models;
using TwitchLib.Communication.Services;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2024")]
[assembly: AssemblyDescription("Connection library used throughout TwitchLib to replace third party depedencies.")]
[assembly: AssemblyFileVersion("2.0.1")]
[assembly: AssemblyInformationalVersion("2.0.1+d1904be8e8425cd4e35079a6a8024fe8b920fc58")]
[assembly: AssemblyProduct("TwitchLib.Communication")]
[assembly: AssemblyTitle("TwitchLib.Communication")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.Communication")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TwitchLib.Communication.Tests")]
[assembly: AssemblyVersion("2.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TwitchLib.Communication.Services
{
	internal class ConnectionWatchDog<T> where T : IDisposable
	{
		private readonly ILogger? _logger;

		private readonly ClientBase<T> _client;

		private CancellationTokenSource? _cancellationTokenSource;

		private const int MonitorTaskDelayInMilliseconds = 200;

		public bool IsRunning { get; private set; }

		internal ConnectionWatchDog(ClientBase<T> client, ILogger? logger = null)
		{
			_logger = logger;
			_client = client;
		}

		internal Task StartMonitorTaskAsync()
		{
			_logger?.TraceMethodCall(GetType(), "StartMonitorTaskAsync", 42);
			if (_cancellationTokenSource != null)
			{
				Exception ex = new InvalidOperationException("Monitor Task cant be started more than once!");
				_logger?.LogExceptionAsError(GetType(), ex, "StartMonitorTaskAsync", 47);
				throw ex;
			}
			_cancellationTokenSource = new CancellationTokenSource();
			IsRunning = true;
			return Task.Run((Func<Task?>)MonitorTaskActionAsync, _cancellationTokenSource.Token);
		}

		internal async Task StopAsync()
		{
			IsRunning = false;
			_logger?.TraceMethodCall(GetType(), "StopAsync", 61);
			_cancellationTokenSource?.Cancel();
			await Task.Delay(400);
			_cancellationTokenSource?.Dispose();
			_cancellationTokenSource = null;
		}

		private async Task MonitorTaskActionAsync()
		{
			_logger?.TraceMethodCall(GetType(), "MonitorTaskActionAsync", 73);
			try
			{
				while (_cancellationTokenSource != null && !_cancellationTokenSource.Token.IsCancellationRequested)
				{
					if (!_client.IsConnected)
					{
						_logger?.TraceAction(GetType(), "Client isn't connected anymore", "MonitorTaskActionAsync", 84);
						_logger?.TraceAction(GetType(), "Try to reconnect", "MonitorTaskActionAsync", 88);
						if (!(await _client.ReconnectInternalAsync()))
						{
							_logger?.TraceAction(GetType(), "Client couldn't reconnect", "MonitorTaskActionAsync", 93);
							await _client.CloseAsync();
							break;
						}
						_logger?.TraceAction(GetType(), "Client reconnected", "MonitorTaskActionAsync", 102);
					}
					await Task.Delay(200);
				}
			}
			catch (TaskCanceledException)
			{
			}
			catch (OperationCanceledException exception)
			{
				_logger?.LogExceptionAsInformation(GetType(), exception, "MonitorTaskActionAsync", 115);
			}
			catch (Exception exception2)
			{
				_logger?.LogExceptionAsError(GetType(), exception2, "MonitorTaskActionAsync", 119);
				await _client.RaiseError(new OnErrorEventArgs(exception2));
				await _client.RaiseFatal();
				await StopAsync();
			}
		}
	}
	internal class NetworkServices<T> where T : IDisposable
	{
		private Task? _listenTask;

		private Task? _monitorTask;

		private readonly ClientBase<T> _client;

		private readonly ILogger? _logger;

		private readonly ConnectionWatchDog<T> _connectionWatchDog;

		private CancellationToken Token => _client.Token;

		internal NetworkServices(ClientBase<T> client, ILogger? logger = null)
		{
			_logger = logger;
			_client = client;
			_connectionWatchDog = new ConnectionWatchDog<T>(_client, logger);
		}

		internal void Start()
		{
			_logger?.TraceMethodCall(GetType(), "Start", 31);
			if (_monitorTask == null || !_connectionWatchDog.IsRunning)
			{
				_monitorTask = _connectionWatchDog.StartMonitorTaskAsync();
			}
			_listenTask = Task.Run((Func<Task?>)_client.ListenTaskActionAsync, Token);
		}

		internal async Task StopAsync()
		{
			_logger?.TraceMethodCall(GetType(), "StopAsync", 48);
			await _connectionWatchDog.StopAsync();
		}
	}
}
namespace TwitchLib.Communication.Models
{
	public class ClientOptions : IClientOptions
	{
		public ReconnectionPolicy ReconnectionPolicy { get; }

		public bool UseSsl { get; }

		public uint DisconnectWait { get; }

		public ClientType ClientType { get; }

		public ClientOptions(ReconnectionPolicy? reconnectionPolicy = null, bool useSsl = true, uint disconnectWait = 1500u, ClientType clientType = ClientType.Chat)
		{
			ReconnectionPolicy = reconnectionPolicy ?? new ReconnectionPolicy(3000, (int?)10);
			UseSsl = useSsl;
			DisconnectWait = disconnectWait;
			ClientType = clientType;
		}
	}
	public class NoReconnectionPolicy : ReconnectionPolicy
	{
		public NoReconnectionPolicy()
			: base(0, (int?)1)
		{
		}
	}
	public class ReconnectionPolicy
	{
		private readonly int _reconnectStepInterval;

		private readonly int? _initMaxAttempts;

		private int _currentReconnectInterval;

		private readonly int _maxReconnectInterval;

		private int? _maxAttempts;

		private int _attemptsMade;

		public ReconnectionPolicy()
		{
			_reconnectStepInterval = 3000;
			_currentReconnectInterval = _reconnectStepInterval;
			_maxReconnectInterval = 30000;
			_maxAttempts = null;
			_initMaxAttempts = null;
			_attemptsMade = 0;
		}

		public ReconnectionPolicy(int minReconnectInterval, int maxReconnectInterval, int maxAttempts)
		{
			_reconnectStepInterval = minReconnectInterval;
			_currentReconnectInterval = ((minReconnectInterval > maxReconnectInterval) ? maxReconnectInterval : minReconnectInterval);
			_maxReconnectInterval = maxReconnectInterval;
			_maxAttempts = maxAttempts;
			_initMaxAttempts = maxAttempts;
			_attemptsMade = 0;
		}

		public ReconnectionPolicy(int minReconnectInterval, int maxReconnectInterval)
		{
			_reconnectStepInterval = minReconnectInterval;
			_currentReconnectInterval = ((minReconnectInterval > maxReconnectInterval) ? maxReconnectInterval : minReconnectInterval);
			_maxReconnectInterval = maxReconnectInterval;
			_maxAttempts = null;
			_initMaxAttempts = null;
			_attemptsMade = 0;
		}

		public ReconnectionPolicy(int reconnectInterval)
		{
			_reconnectStepInterval = reconnectInterval;
			_currentReconnectInterval = reconnectInterval;
			_maxReconnectInterval = reconnectInterval;
			_maxAttempts = null;
			_initMaxAttempts = null;
			_attemptsMade = 0;
		}

		public ReconnectionPolicy(int reconnectInterval, int? maxAttempts)
		{
			_reconnectStepInterval = reconnectInterval;
			_currentReconnectInterval = reconnectInterval;
			_maxReconnectInterval = reconnectInterval;
			_maxAttempts = maxAttempts;
			_initMaxAttempts = maxAttempts;
			_attemptsMade = 0;
		}

		internal void Reset(bool isReconnect)
		{
			if (!isReconnect)
			{
				_attemptsMade = 0;
				_currentReconnectInterval = _reconnectStepInterval;
				_maxAttempts = _initMaxAttempts;
			}
		}

		internal void ProcessValues()
		{
			_attemptsMade++;
			if (_currentReconnectInterval < _maxReconnectInterval)
			{
				_currentReconnectInterval += _reconnectStepInterval;
			}
			if (_currentReconnectInterval > _maxReconnectInterval)
			{
				_currentReconnectInterval = _maxReconnectInterval;
			}
		}

		public int GetReconnectInterval()
		{
			return _currentReconnectInterval;
		}

		public bool AreAttemptsComplete()
		{
			return _attemptsMade == _maxAttempts;
		}
	}
}
namespace TwitchLib.Communication.Interfaces
{
	public interface IClient : IDisposable
	{
		bool IsConnected { get; }

		IClientOptions Options { get; }

		event AsyncEventHandler<OnConnectedEventArgs>? OnConnected;

		event AsyncEventHandler<OnDisconnectedEventArgs>? OnDisconnected;

		event AsyncEventHandler<OnErrorEventArgs>? OnError;

		event AsyncEventHandler<OnFatalErrorEventArgs>? OnFatality;

		event AsyncEventHandler<OnMessageEventArgs>? OnMessage;

		event AsyncEventHandler<OnSendFailedEventArgs>? OnSendFailed;

		event AsyncEventHandler<OnConnectedEventArgs>? OnReconnected;

		Task<bool> OpenAsync();

		Task<bool> ReconnectAsync();

		Task CloseAsync();

		Task<bool> SendAsync(string message);
	}
	public interface IClientOptions
	{
		ClientType ClientType { get; }

		uint DisconnectWait { get; }

		ReconnectionPolicy ReconnectionPolicy { get; }

		bool UseSsl { get; }
	}
}
namespace TwitchLib.Communication.Extensions
{
	internal static class LogExtensions
	{
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		private readonly struct __TraceActionStruct : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>>
		{
			private readonly Type _type;

			private readonly string _action;

			private readonly string _callerMemberName;

			private readonly int _callerLineNumber;

			public static readonly Func<__TraceActionStruct, Exception?, string> Format = (__TraceActionStruct state, Exception? ex) => state.ToString();

			public int Count => 5;

			public KeyValuePair<string, object?> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>("type", _type), 
				1 => new KeyValuePair<string, object>("action", _action), 
				2 => new KeyValuePair<string, object>("callerMemberName", _callerMemberName), 
				3 => new KeyValuePair<string, object>("callerLineNumber", _callerLineNumber), 
				4 => new KeyValuePair<string, object>("{OriginalFormat}", "{type}.{callerMemberName} at line {callerLineNumber}: {action}"), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public __TraceActionStruct(Type type, string action, string callerMemberName, int callerLineNumber)
			{
				_type = type;
				_action = action;
				_callerMemberName = callerMemberName;
				_callerLineNumber = callerLineNumber;
			}

			public override string ToString()
			{
				Type type = _type;
				string callerMemberName = _callerMemberName;
				int callerLineNumber = _callerLineNumber;
				string action = _action;
				return $"{type}.{callerMemberName} at line {callerLineNumber}: {action}";
			}

			public IEnumerator<KeyValuePair<string, object?>> GetEnumerator()
			{
				for (int i = 0; i < 5; i++)
				{
					yield return this[i];
				}
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		private static readonly Action<ILogger, Type, string, int, Exception?> __TraceMethodCallCoreCallback = LoggerMessage.Define<Type, string, int>(LogLevel.Trace, new EventId(695858408, "TraceMethodCallCore"), "{type}.{callerMemberName} at line {callerLineNumber} is called", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		private static readonly Action<ILogger, Type, string, int, Exception?> __LogExceptionAsErrorCallback = LoggerMessage.Define<Type, string, int>(LogLevel.Error, new EventId(1118530440, "LogExceptionAsError"), "Exception in {type}.{callerMemberName} at line {callerLineNumber}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		private static readonly Action<ILogger, Type, string, int, Exception?> __LogExceptionAsInformationCallback = LoggerMessage.Define<Type, string, int>(LogLevel.Information, new EventId(1972195104, "LogExceptionAsInformation"), "Exception in {type}.{callerMemberName} at line {callerLineNumber}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		public static void TraceMethodCall(this ILogger logger, Type type, [CallerMemberName] string callerMemberName = "", [CallerLineNumber] int callerLineNumber = 0)
		{
			callerLineNumber -= 2;
			logger.TraceMethodCallCore(type, callerMemberName, callerLineNumber);
		}

		[LoggerMessage(LogLevel.Trace, "{type}.{callerMemberName} at line {callerLineNumber} is called")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		private static void TraceMethodCallCore(this ILogger logger, Type type, string callerMemberName, int callerLineNumber)
		{
			if (logger.IsEnabled(LogLevel.Trace))
			{
				__TraceMethodCallCoreCallback(logger, type, callerMemberName, callerLineNumber, null);
			}
		}

		[LoggerMessage(LogLevel.Error, "Exception in {type}.{callerMemberName} at line {callerLineNumber}")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		public static void LogExceptionAsError(this ILogger logger, Type type, Exception exception, [CallerMemberName] string callerMemberName = "", [CallerLineNumber] int callerLineNumber = 0)
		{
			if (logger.IsEnabled(LogLevel.Error))
			{
				__LogExceptionAsErrorCallback(logger, type, callerMemberName, callerLineNumber, exception);
			}
		}

		[LoggerMessage(LogLevel.Information, "Exception in {type}.{callerMemberName} at line {callerLineNumber}")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		public static void LogExceptionAsInformation(this ILogger logger, Type type, Exception exception, [CallerMemberName] string callerMemberName = "", [CallerLineNumber] int callerLineNumber = 0)
		{
			if (logger.IsEnabled(LogLevel.Information))
			{
				__LogExceptionAsInformationCallback(logger, type, callerMemberName, callerLineNumber, exception);
			}
		}

		[LoggerMessage(LogLevel.Trace, "{type}.{callerMemberName} at line {callerLineNumber}: {action}")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		public static void TraceAction(this ILogger logger, Type type, string action, [CallerMemberName] string callerMemberName = "", [CallerLineNumber] int callerLineNumber = 0)
		{
			if (logger.IsEnabled(LogLevel.Trace))
			{
				logger.Log(LogLevel.Trace, new EventId(843039716, "TraceAction"), new __TraceActionStruct(type, action, callerMemberName, callerLineNumber), null, __TraceActionStruct.Format);
			}
		}
	}
}
namespace TwitchLib.Communication.Events
{
	public delegate Task AsyncEventHandler<TEventArgs>(object? sender, TEventArgs e);
	public class OnConnectedEventArgs : EventArgs
	{
	}
	public class OnDisconnectedEventArgs : EventArgs
	{
	}
	public class OnErrorEventArgs : EventArgs
	{
		public Exception Exception { get; }

		public OnErrorEventArgs(Exception exception)
		{
			Exception = exception;
		}
	}
	public class OnFatalErrorEventArgs : EventArgs
	{
		public string Reason { get; }

		public OnFatalErrorEventArgs(string reason)
		{
			Reason = reason;
		}

		public OnFatalErrorEventArgs(Exception e)
		{
			Reason = e.ToString();
		}
	}
	public class OnMessageEventArgs : EventArgs
	{
		public string Message { get; }

		public OnMessageEventArgs(string message)
		{
			Message = message;
		}
	}
	public class OnSendFailedEventArgs : EventArgs
	{
		public string Message { get; }

		public Exception Exception { get; }

		public OnSendFailedEventArgs(Exception exception, string message)
		{
			Exception = exception;
			Message = message;
		}
	}
}
namespace TwitchLib.Communication.Enums
{
	public enum ClientType
	{
		Chat,
		PubSub
	}
}
namespace TwitchLib.Communication.Clients
{
	public abstract class ClientBase<T> : IClient, IDisposable where T : IDisposable
	{
		private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

		private readonly NetworkServices<T> _networkServices;

		private CancellationTokenSource _cancellationTokenSource;

		protected readonly ILogger<ClientBase<T>>? Logger;

		internal CancellationToken Token => _cancellationTokenSource.Token;

		internal static TimeSpan TimeOutEstablishConnection => TimeSpan.FromSeconds(15.0);

		protected abstract string Url { get; }

		public T? Client { get; private set; }

		public abstract bool IsConnected { get; }

		public IClientOptions Options { get; }

		public event AsyncEventHandler<OnConnectedEventArgs>? OnConnected;

		public event AsyncEventHandler<OnDisconnectedEventArgs>? OnDisconnected;

		public event AsyncEventHandler<OnErrorEventArgs>? OnError;

		public event AsyncEventHandler<OnFatalErrorEventArgs>? OnFatality;

		public event AsyncEventHandler<OnMessageEventArgs>? OnMessage;

		public event AsyncEventHandler<OnSendFailedEventArgs>? OnSendFailed;

		public event AsyncEventHandler<OnConnectedEventArgs>? OnReconnected;

		internal ClientBase(IClientOptions? options, ILogger<ClientBase<T>>? logger)
		{
			Logger = logger;
			_cancellationTokenSource = new CancellationTokenSource();
			Options = options ?? new ClientOptions();
			_networkServices = new NetworkServices<T>(this, logger);
		}

		private async Task RaiseSendFailed(OnSendFailedEventArgs eventArgs)
		{
			Logger?.TraceMethodCall(GetType(), "RaiseSendFailed", 88);
			if (!Token.IsCancellationRequested && this.OnSendFailed != null)
			{
				await this.OnSendFailed(this, eventArgs);
			}
		}

		internal async Task RaiseError(OnErrorEventArgs eventArgs)
		{
			Logger?.TraceMethodCall(GetType(), "RaiseError", 102);
			if (!Token.IsCancellationRequested && this.OnError != null)
			{
				await this.OnError(this, eventArgs);
			}
		}

		private async Task RaiseReconnected()
		{
			Logger?.TraceMethodCall(GetType(), "RaiseReconnected", 116);
			if (!Token.IsCancellationRequested && this.OnReconnected != null)
			{
				await this.OnReconnected(this, new OnConnectedEventArgs());
			}
		}

		internal async Task RaiseMessage(OnMessageEventArgs eventArgs)
		{
			Logger?.TraceMethodCall(GetType(), "RaiseMessage", 130);
			if (!Token.IsCancellationRequested && this.OnMessage != null)
			{
				await this.OnMessage(this, eventArgs);
			}
		}

		internal async Task RaiseFatal(Exception? ex = null)
		{
			Logger?.TraceMethodCall(GetType(), "RaiseFatal", 144);
			if (!Token.IsCancellationRequested)
			{
				OnFatalErrorEventArgs e = ((ex != null) ? new OnFatalErrorEventArgs(ex) : new OnFatalErrorEventArgs("Fatal network error."));
				if (this.OnFatality != null)
				{
					await this.OnFatality(this, e);
				}
			}
		}

		private async Task RaiseDisconnected()
		{
			Logger?.TraceMethodCall(GetType(), "RaiseDisconnected", 159);
			if (this.OnDisconnected != null)
			{
				await this.OnDisconnected(this, new OnDisconnectedEventArgs());
			}
		}

		private async Task RaiseConnected()
		{
			Logger?.TraceMethodCall(GetType(), "RaiseConnected", 165);
			if (this.OnConnected != null)
			{
				await this.OnConnected(this, new OnConnectedEventArgs());
			}
		}

		public async Task<bool> SendAsync(string message)
		{
			Logger?.TraceMethodCall(GetType(), "SendAsync", 172);
			await _semaphore.WaitAsync(Token);
			try
			{
				bool result = default(bool);
				object obj;
				int num;
				try
				{
					await ClientSendAsync(message);
					result = true;
					return result;
				}
				catch (Exception ex)
				{
					obj = ex;
					num = 1;
				}
				if (num != 1)
				{
					return result;
				}
				Exception exception = (Exception)obj;
				await RaiseSendFailed(new OnSendFailedEventArgs(exception, message));
				return false;
			}
			finally
			{
				_semaphore.Release();
			}
		}

		public Task<bool> OpenAsync()
		{
			Logger?.TraceMethodCall(GetType(), "OpenAsync", 194);
			return OpenPrivateAsync(isReconnect: false);
		}

		public async Task CloseAsync()
		{
			Logger?.TraceMethodCall(GetType(), "CloseAsync", 201);
			await ClosePrivateAsync();
		}

		public void Dispose()
		{
			Logger?.TraceMethodCall(GetType(), "Dispose", 212);
			CloseAsync().GetAwaiter().GetResult();
			GC.SuppressFinalize(this);
		}

		public async Task<bool> ReconnectAsync()
		{
			Logger?.TraceMethodCall(GetType(), "ReconnectAsync", 220);
			return await ReconnectInternalAsync();
		}

		private async Task<bool> OpenPrivateAsync(bool isReconnect)
		{
			Logger?.TraceMethodCall(GetType(), "OpenPrivateAsync", 227);
			bool result = default(bool);
			object obj;
			int num;
			try
			{
				if (Token.IsCancellationRequested)
				{
					result = false;
					return result;
				}
				if (IsConnected)
				{
					result = true;
					return result;
				}
				bool flag = true;
				Options.ReconnectionPolicy.Reset(isReconnect);
				while (!IsConnected && !Options.ReconnectionPolicy.AreAttemptsComplete())
				{
					Logger?.TraceAction(GetType(), "try to connect", "OpenPrivateAsync", 246);
					Client = CreateClient();
					if (!flag)
					{
						await Task.Delay(Options.ReconnectionPolicy.GetReconnectInterval(), CancellationToken.None);
					}
					await ConnectClientAsync();
					Options.ReconnectionPolicy.ProcessValues();
					flag = false;
				}
				if (!IsConnected)
				{
					Logger?.TraceAction(GetType(), "Client couldn't establish a connection", "OpenPrivateAsync", 263);
					await RaiseFatal();
					result = false;
					return result;
				}
				Logger?.TraceAction(GetType(), "Client established a connection", "OpenPrivateAsync", 268);
				_networkServices.Start();
				if (!isReconnect)
				{
					await RaiseConnected();
				}
				result = true;
				return result;
			}
			catch (Exception ex)
			{
				obj = ex;
				num = 1;
			}
			if (num != 1)
			{
				return result;
			}
			Exception exception = (Exception)obj;
			Logger?.LogExceptionAsError(GetType(), exception, "OpenPrivateAsync", 280);
			await RaiseError(new OnErrorEventArgs(exception));
			await RaiseFatal();
			return false;
		}

		private async Task ClosePrivateAsync()
		{
			Logger?.TraceMethodCall(GetType(), "ClosePrivateAsync", 301);
			await _networkServices.StopAsync();
			_cancellationTokenSource.Cancel();
			Logger?.TraceAction(GetType(), "_cancellationTokenSource.Cancel is called", "ClosePrivateAsync", 307);
			CloseClient();
			await RaiseDisconnected();
			_cancellationTokenSource = new CancellationTokenSource();
			await Task.Delay(TimeSpan.FromMilliseconds(Options.DisconnectWait), CancellationToken.None);
		}

		protected abstract Task ClientSendAsync(string message);

		protected abstract T CreateClient();

		protected abstract void CloseClient();

		protected abstract Task ConnectClientAsync();

		internal async Task<bool> ReconnectInternalAsync()
		{
			Logger?.TraceMethodCall(GetType(), "ReconnectInternalAsync", 368);
			await ClosePrivateAsync();
			bool reconnected = await OpenPrivateAsync(isReconnect: true);
			if (reconnected)
			{
				await RaiseReconnected();
			}
			return reconnected;
		}

		internal abstract Task ListenTaskActionAsync();
	}
	public class TcpClient : ClientBase<System.Net.Sockets.TcpClient>
	{
		private StreamReader? _reader;

		private StreamWriter? _writer;

		protected override string Url => "irc.chat.twitch.tv";

		private int Port
		{
			get
			{
				if (!base.Options.UseSsl)
				{
					return 6667;
				}
				return 6697;
			}
		}

		public override bool IsConnected => base.Client?.Connected ?? false;

		public TcpClient(IClientOptions? options = null, ILogger<TcpClient>? logger = null)
			: base(options, (ILogger<ClientBase<System.Net.Sockets.TcpClient>>?)logger)
		{
		}

		internal override async Task ListenTaskActionAsync()
		{
			Logger?.TraceMethodCall(GetType(), "ListenTaskActionAsync", 34);
			if (_reader == null)
			{
				InvalidOperationException ex = new InvalidOperationException("_reader was null!");
				Logger?.LogExceptionAsError(GetType(), ex, "ListenTaskActionAsync", 38);
				await RaiseFatal(ex);
				throw ex;
			}
			while (IsConnected)
			{
				try
				{
					string text = await _reader.ReadLineAsync();
					if (text != null)
					{
						await RaiseMessage(new OnMessageEventArgs(text));
					}
				}
				catch (Exception ex2) when (((ex2 is TaskCanceledException || ex2 is OperationCanceledException) ? 1 : 0) != 0)
				{
					Logger?.LogExceptionAsInformation(GetType(), ex2, "ListenTaskActionAsync", 58);
				}
				catch (Exception exception)
				{
					Logger?.LogExceptionAsError(GetType(), exception, "ListenTaskActionAsync", 62);
					await RaiseError(new OnErrorEventArgs(exception));
					break;
				}
			}
		}

		protected override async Task ClientSendAsync(string message)
		{
			Logger?.TraceMethodCall(GetType(), "ClientSendAsync", 72);
			if (_writer == null)
			{
				InvalidOperationException ex = new InvalidOperationException("_writer was null!");
				Logger?.LogExceptionAsError(GetType(), ex, "ClientSendAsync", 81);
				await RaiseFatal(ex);
				throw ex;
			}
			await _writer.WriteLineAsync(message);
			await _writer.FlushAsync();
		}

		protected override async Task ConnectClientAsync()
		{
			Logger?.TraceMethodCall(GetType(), "ConnectClientAsync", 93);
			if (base.Client == null)
			{
				Exception ex = new InvalidOperationException("Client was null!");
				Logger?.LogExceptionAsError(GetType(), ex, "ConnectClientAsync", 97);
				throw ex;
			}
			try
			{
				using (CancellationTokenSource delayTaskCancellationTokenSource = new CancellationTokenSource())
				{
					Task task = base.Client.ConnectAsync(Url, Port);
					Task task2 = Task.Delay((int)ClientBase<System.Net.Sockets.TcpClient>.TimeOutEstablishConnection.TotalMilliseconds, delayTaskCancellationTokenSource.Token);
					await Task.WhenAny(new Task[2] { task, task2 });
					delayTaskCancellationTokenSource.Cancel();
				}
				if (!base.Client.Connected)
				{
					Logger?.TraceAction(GetType(), "Client couldn't establish connection", "ConnectClientAsync", 133);
					return;
				}
				Logger?.TraceAction(GetType(), "Client established connection successfully", "ConnectClientAsync", 137);
				Stream stream = base.Client.GetStream();
				if (base.Options.UseSsl)
				{
					SslStream ssl = new SslStream(stream, leaveInnerStreamOpen: false);
					await ssl.AuthenticateAsClientAsync(Url);
					stream = ssl;
				}
				_reader = new StreamReader(stream);
				_writer = new StreamWriter(stream);
			}
			catch (Exception ex2) when (((ex2 is TaskCanceledException || ex2 is OperationCanceledException) ? 1 : 0) != 0)
			{
				Logger?.LogExceptionAsInformation(GetType(), ex2, "ConnectClientAsync", 151);
			}
			catch (Exception exception)
			{
				Logger?.LogExceptionAsError(GetType(), exception, "ConnectClientAsync", 155);
			}
		}

		protected override System.Net.Sockets.TcpClient CreateClient()
		{
			Logger?.TraceMethodCall(GetType(), "CreateClient", 162);
			return new System.Net.Sockets.TcpClient
			{
				LingerState = new LingerOption(enable: true, 0)
			};
		}

		protected override void CloseClient()
		{
			Logger?.TraceMethodCall(GetType(), "CloseClient", 174);
			_reader?.Dispose();
			_writer?.Dispose();
			base.Client?.Dispose();
		}
	}
	public class WebSocketClient : ClientBase<ClientWebSocket>
	{
		protected override string Url { get; }

		public override bool IsConnected
		{
			get
			{
				ClientWebSocket? client = base.Client;
				if (client == null)
				{
					return false;
				}
				return client.State == WebSocketState.Open;
			}
		}

		public WebSocketClient(IClientOptions? options = null, ILogger<WebSocketClient>? logger = null)
			: base(options, (ILogger<ClientBase<ClientWebSocket>>?)logger)
		{
			switch (base.Options.ClientType)
			{
			case ClientType.Chat:
				Url = (base.Options.UseSsl ? "wss://irc-ws.chat.twitch.tv:443" : "ws://irc-ws.chat.twitch.tv:80");
				break;
			case ClientType.PubSub:
				Url = (base.Options.UseSsl ? "wss://pubsub-edge.twitch.tv:443" : "ws://pubsub-edge.twitch.tv:80");
				break;
			default:
			{
				ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("ClientType");
				Logger?.LogExceptionAsError(GetType(), ex, ".ctor", 37);
				throw ex;
			}
			}
		}

		internal override async Task ListenTaskActionAsync()
		{
			Logger?.TraceMethodCall(GetType(), "ListenTaskActionAsync", 44);
			if (base.Client == null)
			{
				InvalidOperationException ex = new InvalidOperationException("Client was null!");
				Logger?.LogExceptionAsError(GetType(), ex, "ListenTaskActionAsync", 48);
				await RaiseFatal(ex);
				throw ex;
			}
			MemoryStream memoryStream = new MemoryStream();
			byte[] bytes = new byte[1024];
			ArraySegment<byte> buffer = new ArraySegment<byte>(bytes);
			while (IsConnected)
			{
				WebSocketReceiveResult result;
				try
				{
					result = await base.Client.ReceiveAsync(buffer, base.Token);
				}
				catch (TaskCanceledException)
				{
					break;
				}
				catch (OperationCanceledException exception)
				{
					Logger?.LogExceptionAsInformation(GetType(), exception, "ListenTaskActionAsync", 75);
					break;
				}
				catch (Exception exception2)
				{
					Logger?.LogExceptionAsError(GetType(), exception2, "ListenTaskActionAsync", 80);
					await RaiseError(new OnErrorEventArgs(exception2));
					break;
				}
				switch (result.MessageType)
				{
				case WebSocketMessageType.Close:
					await CloseAsync();
					break;
				case WebSocketMessageType.Text:
					if (result.EndOfMessage && memoryStream.Position == 0L)
					{
						string @string = Encoding.UTF8.GetString(bytes, 0, result.Count);
						await RaiseMessage(new OnMessageEventArgs(@string));
						break;
					}
					memoryStream.Write(bytes, 0, result.Count);
					if (result.EndOfMessage)
					{
						string string2 = Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Position);
						await RaiseMessage(new OnMessageEventArgs(string2));
						memoryStream.Position = 0L;
					}
					break;
				default:
				{
					Exception ex3 = new ArgumentOutOfRangeException();
					Logger?.LogExceptionAsError(GetType(), ex3, "ListenTaskActionAsync", 111);
					throw ex3;
				}
				case WebSocketMessageType.Binary:
					break;
				}
			}
		}

		protected override async Task ClientSendAsync(string message)
		{
			Logger?.TraceMethodCall(GetType(), "ClientSendAsync", 120);
			if (base.Client == null)
			{
				InvalidOperationException ex = new InvalidOperationException("Client was null!");
				Logger?.LogExceptionAsError(GetType(), ex, "ClientSendAsync", 134);
				await RaiseFatal(ex);
				throw ex;
			}
			byte[] bytes = Encoding.UTF8.GetBytes(message);
			await base.Client.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, endOfMessage: true, base.Token);
		}

		protected override async Task ConnectClientAsync()
		{
			Logger?.TraceMethodCall(GetType(), "ConnectClientAsync", 149);
			if (base.Client == null)
			{
				InvalidOperationException ex = new InvalidOperationException("Client was null!");
				Logger?.LogExceptionAsError(GetType(), ex, "ConnectClientAsync", 153);
				await RaiseFatal(ex);
				throw ex;
			}
			try
			{
				using (CancellationTokenSource delayTaskCancellationTokenSource = new CancellationTokenSource())
				{
					Task task = base.Client.ConnectAsync(new Uri(Url), base.Token);
					Task task2 = Task.Delay((int)ClientBase<ClientWebSocket>.TimeOutEstablishConnection.TotalMilliseconds, delayTaskCancellationTokenSource.Token);
					await Task.WhenAny(new Task[2] { task, task2 });
					delayTaskCancellationTokenSource.Cancel();
				}
				if (!IsConnected)
				{
					Logger?.TraceAction(GetType(), "Client couldn't establish connection", "ConnectClientAsync", 189);
				}
			}
			catch (Exception ex2) when (((ex2 is TaskCanceledException || ex2 is OperationCanceledException) ? 1 : 0) != 0)
			{
				Logger?.LogExceptionAsInformation(GetType(), ex2, "ConnectClientAsync", 195);
			}
			catch (Exception exception)
			{
				Logger?.LogExceptionAsError(GetType(), exception, "ConnectClientAsync", 199);
			}
		}

		protected override ClientWebSocket CreateClient()
		{
			Logger?.TraceMethodCall(GetType(), "CreateClient", 206);
			return new ClientWebSocket();
		}

		protected override void CloseClient()
		{
			Logger?.TraceMethodCall(GetType(), "CloseClient", 213);
			base.Client?.Abort();
			base.Client?.Dispose();
		}
	}
}

TwitchLib.PubSub.dll

Decompiled a month ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.WebSockets;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TwitchLib.Communication.Clients;
using TwitchLib.Communication.Enums;
using TwitchLib.Communication.Events;
using TwitchLib.Communication.Interfaces;
using TwitchLib.Communication.Models;
using TwitchLib.PubSub.Common;
using TwitchLib.PubSub.Enums;
using TwitchLib.PubSub.Events;
using TwitchLib.PubSub.Extensions;
using TwitchLib.PubSub.Interfaces;
using TwitchLib.PubSub.Models;
using TwitchLib.PubSub.Models.Responses;
using TwitchLib.PubSub.Models.Responses.Messages;
using TwitchLib.PubSub.Models.Responses.Messages.AutomodCaughtMessage;
using TwitchLib.PubSub.Models.Responses.Messages.HypeTrain;
using TwitchLib.PubSub.Models.Responses.Messages.Redemption;
using TwitchLib.PubSub.Models.Responses.Messages.UserModerationNotifications;
using TwitchLib.PubSub.Models.Responses.Messages.UserModerationNotificationsTypes;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("swiftyspiffy,Prom3theu5,Syzuna,LuckyNoS7evin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2022")]
[assembly: AssemblyDescription("PubSub component of TwitchLib. This component allows you to access Twitch's PubSub event system and subscribe/unsubscribe from topics.")]
[assembly: AssemblyFileVersion("4.0.0")]
[assembly: AssemblyInformationalVersion("4.0.0+10721e305d3e0b2ac6c93bb75d44140ce38b1322")]
[assembly: AssemblyProduct("TwitchLib.PubSub")]
[assembly: AssemblyTitle("TwitchLib.PubSub")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.PubSub")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("4.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TwitchLib.PubSub
{
	public class TwitchPubSub : ITwitchPubSub, IDisposable
	{
		private const string PingPayload = "{ \"type\": \"PING\" }";

		private static readonly Random Random = new Random();

		private readonly WebSocketClient _socket;

		private readonly List<PreviousRequest> _previousRequests = new List<PreviousRequest>();

		private readonly Semaphore _previousRequestsSemaphore = new Semaphore(1, 1);

		private readonly ILogger<TwitchPubSub> _logger;

		private readonly System.Timers.Timer _pingTimer = new System.Timers.Timer();

		private readonly System.Timers.Timer _pongTimer = new System.Timers.Timer();

		private bool _pongReceived = false;

		private readonly List<string> _topicList = new List<string>();

		private readonly Dictionary<string, string> _topicToChannelId = new Dictionary<string, string>();

		private bool _disposed = false;

		public event EventHandler OnPubSubServiceConnected;

		public event EventHandler<OnPubSubServiceErrorArgs> OnPubSubServiceError;

		public event EventHandler OnPubSubServiceClosed;

		public event EventHandler<OnListenResponseArgs> OnListenResponse;

		public event EventHandler<OnTimeoutArgs> OnTimeout;

		public event EventHandler<OnBanArgs> OnBan;

		public event EventHandler<OnMessageDeletedArgs> OnMessageDeleted;

		public event EventHandler<OnUnbanArgs> OnUnban;

		public event EventHandler<OnUntimeoutArgs> OnUntimeout;

		public event EventHandler<OnHostArgs> OnHost;

		public event EventHandler<OnSubscribersOnlyArgs> OnSubscribersOnly;

		public event EventHandler<OnSubscribersOnlyOffArgs> OnSubscribersOnlyOff;

		public event EventHandler<OnClearArgs> OnClear;

		public event EventHandler<OnEmoteOnlyArgs> OnEmoteOnly;

		public event EventHandler<OnEmoteOnlyOffArgs> OnEmoteOnlyOff;

		public event EventHandler<OnR9kBetaArgs> OnR9kBeta;

		public event EventHandler<OnR9kBetaOffArgs> OnR9kBetaOff;

		public event EventHandler<OnBitsReceivedV2Args> OnBitsReceivedV2;

		public event EventHandler<OnStreamUpArgs> OnStreamUp;

		public event EventHandler<OnStreamDownArgs> OnStreamDown;

		public event EventHandler<OnViewCountArgs> OnViewCount;

		public event EventHandler<OnWhisperArgs> OnWhisper;

		public event EventHandler<OnChannelSubscriptionArgs> OnChannelSubscription;

		public event EventHandler<OnChannelBitsBadgeUnlockArgs> OnChannelBitsBadgeUnlock;

		public event EventHandler<OnLowTrustUsersArgs> OnLowTrustUsers;

		public event EventHandler<OnChannelExtensionBroadcastArgs> OnChannelExtensionBroadcast;

		[Obsolete("This event fires on an undocumented/retired/obsolete topic.", false)]
		public event EventHandler<OnCustomRewardCreatedArgs> OnCustomRewardCreated;

		[Obsolete("This event fires on an undocumented/retired/obsolete topic.", false)]
		public event EventHandler<OnCustomRewardUpdatedArgs> OnCustomRewardUpdated;

		[Obsolete("This event fires on an undocumented/retired/obsolete topic.", false)]
		public event EventHandler<OnCustomRewardDeletedArgs> OnCustomRewardDeleted;

		[Obsolete("This event fires on an undocumented/retired/obsolete topic. Consider using OnChannelPointsRewardRedeemed", false)]
		public event EventHandler<OnRewardRedeemedArgs> OnRewardRedeemed;

		public event EventHandler<OnChannelPointsRewardRedeemedArgs> OnChannelPointsRewardRedeemed;

		public event EventHandler<OnLeaderboardEventArgs> OnLeaderboardSubs;

		public event EventHandler<OnLeaderboardEventArgs> OnLeaderboardBits;

		public event EventHandler<OnRaidUpdateArgs> OnRaidUpdate;

		public event EventHandler<OnRaidUpdateV2Args> OnRaidUpdateV2;

		public event EventHandler<OnRaidGoArgs> OnRaidGo;

		public event EventHandler<OnRaidCancelArgs> OnRaidCancel;

		public event EventHandler<OnLogArgs> OnLog;

		public event EventHandler<OnCommercialArgs> OnCommercial;

		public event EventHandler<OnPredictionArgs> OnPrediction;

		public event EventHandler<OnAutomodCaughtMessageArgs> OnAutomodCaughtMessage;

		public event EventHandler<OnAutomodCaughtUserMessage> OnAutomodCaughtUserMessage;

		public event EventHandler<OnHypeTrainProgressionArgs> OnHypeTrainProgression;

		public event EventHandler<OnHypeTrainLevelUp> OnHypeTrainLevelUp;

		public TwitchPubSub(ILogger<TwitchPubSub> logger = null)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			_logger = logger;
			ClientOptions val = new ClientOptions((ReconnectionPolicy)null, true, 1500u, (ClientType)1);
			_socket = new WebSocketClient((IClientOptions)(object)val, (ILogger<WebSocketClient>)null);
			((ClientBase<ClientWebSocket>)(object)_socket).OnConnected += Socket_OnConnectedAsync;
			((ClientBase<ClientWebSocket>)(object)_socket).OnError += OnErrorAsync;
			((ClientBase<ClientWebSocket>)(object)_socket).OnMessage += OnMessageAsync;
			((ClientBase<ClientWebSocket>)(object)_socket).OnDisconnected += Socket_OnDisconnectedAsync;
			_pongTimer.Interval = 15000.0;
			_pongTimer.Elapsed += PongTimerTickAsync;
		}

		private Task OnErrorAsync(object sender, OnErrorEventArgs e)
		{
			_logger?.LogOnError(e.Exception);
			this.OnPubSubServiceError?.Invoke(this, new OnPubSubServiceErrorArgs
			{
				Exception = e.Exception
			});
			return Task.CompletedTask;
		}

		private Task OnMessageAsync(object sender, OnMessageEventArgs e)
		{
			_logger?.LogReceivednMessage(e.Message);
			this.OnLog?.Invoke(this, new OnLogArgs
			{
				Data = e.Message
			});
			return ParseMessageAsync(e.Message);
		}

		private Task Socket_OnDisconnectedAsync(object sender, EventArgs e)
		{
			_logger?.LogConnectionClosed();
			_pingTimer.Stop();
			_pongTimer.Stop();
			this.OnPubSubServiceClosed?.Invoke(this, null);
			return Task.CompletedTask;
		}

		private Task Socket_OnConnectedAsync(object sender, EventArgs e)
		{
			_logger?.LogConnectionEstablished();
			_pingTimer.Interval = 180000.0;
			_pingTimer.Elapsed += PingTimerTickAsync;
			_pingTimer.Start();
			this.OnPubSubServiceConnected?.Invoke(this, null);
			return Task.CompletedTask;
		}

		private async void PingTimerTickAsync(object sender, ElapsedEventArgs e)
		{
			_pongReceived = false;
			await ((ClientBase<ClientWebSocket>)(object)_socket).SendAsync("{ \"type\": \"PING\" }");
			_pongTimer.Start();
		}

		private async void PongTimerTickAsync(object sender, ElapsedEventArgs e)
		{
			_pongTimer.Stop();
			if (_pongReceived)
			{
				_pongReceived = false;
			}
			else
			{
				await ((ClientBase<ClientWebSocket>)(object)_socket).CloseAsync();
			}
		}

		private async Task ParseMessageAsync(string message)
		{
			JObject parsedJson = JObject.Parse(message);
			switch ((((object)((JToken)parsedJson).SelectToken("type"))?.ToString())?.ToLower())
			{
			case "response":
			{
				Response resp = new Response(parsedJson);
				if (_previousRequests.Count == 0)
				{
					break;
				}
				bool handled = false;
				_previousRequestsSemaphore.WaitOne();
				try
				{
					int i = 0;
					while (i < _previousRequests.Count)
					{
						PreviousRequest request = _previousRequests[i];
						if (string.Equals(request.Nonce, resp.Nonce, StringComparison.CurrentCulture))
						{
							_previousRequests.RemoveAt(i);
							_topicToChannelId.TryGetValue(request.Topic, out var requestChannelId);
							this.OnListenResponse?.Invoke(this, new OnListenResponseArgs
							{
								Response = resp,
								Topic = request.Topic,
								Successful = resp.Successful,
								ChannelId = requestChannelId
							});
							handled = true;
							requestChannelId = null;
						}
						else
						{
							i++;
						}
					}
				}
				finally
				{
					_previousRequestsSemaphore.Release();
				}
				if (handled)
				{
					return;
				}
				break;
			}
			case "message":
			{
				TwitchLib.PubSub.Models.Responses.Message msg = new TwitchLib.PubSub.Models.Responses.Message(parsedJson);
				_topicToChannelId.TryGetValue(msg.Topic, out var channelId);
				channelId = channelId ?? "";
				switch (msg.Topic.Split('.')[0])
				{
				case "hype-train-events-v1":
				{
					HypeTrainEvent hypeTrainEvent = msg.MessageData as HypeTrainEvent;
					switch (hypeTrainEvent.Type)
					{
					case HypeTrainEventType.Progression:
					{
						HypeTrainProgression progression = hypeTrainEvent.Data as HypeTrainProgression;
						this.OnHypeTrainProgression?.Invoke(this, new OnHypeTrainProgressionArgs
						{
							ChannelId = channelId,
							Progression = progression
						});
						break;
					}
					case HypeTrainEventType.LevelUp:
					{
						HypeTrainLevelUp levelUp = hypeTrainEvent.Data as HypeTrainLevelUp;
						this.OnHypeTrainLevelUp?.Invoke(this, new OnHypeTrainLevelUp
						{
							ChannelId = channelId,
							LevelUp = levelUp
						});
						break;
					}
					}
					return;
				}
				case "user-moderation-notifications":
				{
					UserModerationNotifications userModerationNotifications = msg.MessageData as UserModerationNotifications;
					switch (userModerationNotifications.Type)
					{
					case UserModerationNotificationsType.AutomodCaughtMessage:
					{
						TwitchLib.PubSub.Models.Responses.Messages.UserModerationNotificationsTypes.AutomodCaughtMessage automodCaughtMessage = userModerationNotifications.Data as TwitchLib.PubSub.Models.Responses.Messages.UserModerationNotificationsTypes.AutomodCaughtMessage;
						this.OnAutomodCaughtUserMessage?.Invoke(this, new OnAutomodCaughtUserMessage
						{
							ChannelId = channelId,
							UserId = msg.Topic.Split('.')[2],
							AutomodCaughtMessage = automodCaughtMessage
						});
						break;
					}
					}
					return;
				}
				case "automod-queue":
				{
					AutomodQueue automodQueue = msg.MessageData as AutomodQueue;
					switch (automodQueue.Type)
					{
					case AutomodQueueType.CaughtMessage:
					{
						TwitchLib.PubSub.Models.Responses.Messages.AutomodCaughtMessage.AutomodCaughtMessage caughtMessage = automodQueue.Data as TwitchLib.PubSub.Models.Responses.Messages.AutomodCaughtMessage.AutomodCaughtMessage;
						this.OnAutomodCaughtMessage?.Invoke(this, new OnAutomodCaughtMessageArgs
						{
							ChannelId = channelId,
							AutomodCaughtMessage = caughtMessage
						});
						break;
					}
					case AutomodQueueType.Unknown:
						UnaccountedFor("Unknown automod queue type. Msg: " + automodQueue.RawData);
						break;
					}
					return;
				}
				case "channel-subscribe-events-v1":
				{
					ChannelSubscription subscription = msg.MessageData as ChannelSubscription;
					this.OnChannelSubscription?.Invoke(this, new OnChannelSubscriptionArgs
					{
						Subscription = subscription,
						ChannelId = channelId
					});
					return;
				}
				case "channel-bits-badge-unlocks":
				{
					BitsBadgeNotificationMessage channelBitsBadgeUnlocks = msg.MessageData as BitsBadgeNotificationMessage;
					this.OnChannelBitsBadgeUnlock?.Invoke(this, new OnChannelBitsBadgeUnlockArgs
					{
						BitsBadgeUnlocks = channelBitsBadgeUnlocks,
						ChannelId = channelId
					});
					break;
				}
				case "low-trust-users":
				{
					LowTrustUsers lowTrustUsers = msg.MessageData as LowTrustUsers;
					this.OnLowTrustUsers?.Invoke(this, new OnLowTrustUsersArgs
					{
						LowTrustUsers = lowTrustUsers,
						ChannelId = channelId
					});
					break;
				}
				case "whispers":
				{
					Whisper whisper = (Whisper)msg.MessageData;
					this.OnWhisper?.Invoke(this, new OnWhisperArgs
					{
						Whisper = whisper,
						ChannelId = channelId
					});
					return;
				}
				case "chat_moderator_actions":
				{
					ChatModeratorActions cma = msg.MessageData as ChatModeratorActions;
					string reason = "";
					switch (cma?.ModerationAction.ToLower())
					{
					case "timeout":
						if (cma.Args.Count > 2)
						{
							reason = cma.Args[2];
						}
						this.OnTimeout?.Invoke(this, new OnTimeoutArgs
						{
							TimedoutBy = cma.CreatedBy,
							TimedoutById = cma.CreatedByUserId,
							TimedoutUserId = cma.TargetUserId,
							TimeoutDuration = TimeSpan.FromSeconds(int.Parse(cma.Args[1])),
							TimeoutReason = reason,
							TimedoutUser = cma.Args[0],
							ChannelId = channelId
						});
						return;
					case "ban":
						if (cma.Args.Count > 1)
						{
							reason = cma.Args[1];
						}
						this.OnBan?.Invoke(this, new OnBanArgs
						{
							BannedBy = cma.CreatedBy,
							BannedByUserId = cma.CreatedByUserId,
							BannedUserId = cma.TargetUserId,
							BanReason = reason,
							BannedUser = cma.Args[0],
							ChannelId = channelId
						});
						return;
					case "delete":
						this.OnMessageDeleted?.Invoke(this, new OnMessageDeletedArgs
						{
							DeletedBy = cma.CreatedBy,
							DeletedByUserId = cma.CreatedByUserId,
							TargetUserId = cma.TargetUserId,
							TargetUser = cma.Args[0],
							Message = cma.Args[1],
							MessageId = cma.Args[2],
							ChannelId = channelId
						});
						return;
					case "unban":
						this.OnUnban?.Invoke(this, new OnUnbanArgs
						{
							UnbannedBy = cma.CreatedBy,
							UnbannedByUserId = cma.CreatedByUserId,
							UnbannedUserId = cma.TargetUserId,
							UnbannedUser = cma.Args[0],
							ChannelId = channelId
						});
						return;
					case "untimeout":
						this.OnUntimeout?.Invoke(this, new OnUntimeoutArgs
						{
							UntimeoutedBy = cma.CreatedBy,
							UntimeoutedByUserId = cma.CreatedByUserId,
							UntimeoutedUserId = cma.TargetUserId,
							UntimeoutedUser = cma.Args[0],
							ChannelId = channelId
						});
						return;
					case "host":
						this.OnHost?.Invoke(this, new OnHostArgs
						{
							HostedChannel = cma.Args[0],
							Moderator = cma.CreatedBy,
							ChannelId = channelId
						});
						return;
					case "subscribers":
						this.OnSubscribersOnly?.Invoke(this, new OnSubscribersOnlyArgs
						{
							Moderator = cma.CreatedBy,
							ChannelId = channelId
						});
						return;
					case "subscribersoff":
						this.OnSubscribersOnlyOff?.Invoke(this, new OnSubscribersOnlyOffArgs
						{
							Moderator = cma.CreatedBy,
							ChannelId = channelId
						});
						return;
					case "clear":
						this.OnClear?.Invoke(this, new OnClearArgs
						{
							Moderator = cma.CreatedBy,
							ChannelId = channelId
						});
						return;
					case "emoteonly":
						this.OnEmoteOnly?.Invoke(this, new OnEmoteOnlyArgs
						{
							Moderator = cma.CreatedBy,
							ChannelId = channelId
						});
						return;
					case "emoteonlyoff":
						this.OnEmoteOnlyOff?.Invoke(this, new OnEmoteOnlyOffArgs
						{
							Moderator = cma.CreatedBy,
							ChannelId = channelId
						});
						return;
					case "r9kbeta":
						this.OnR9kBeta?.Invoke(this, new OnR9kBetaArgs
						{
							Moderator = cma.CreatedBy,
							ChannelId = channelId
						});
						return;
					case "r9kbetaoff":
						this.OnR9kBetaOff?.Invoke(this, new OnR9kBetaOffArgs
						{
							Moderator = cma.CreatedBy,
							ChannelId = channelId
						});
						return;
					}
					break;
				}
				case "channel-bits-events-v2":
				{
					MessageData messageData = msg.MessageData;
					if (messageData is ChannelBitsEventsV2 cbev2)
					{
						this.OnBitsReceivedV2?.Invoke(this, new OnBitsReceivedV2Args
						{
							IsAnonymous = cbev2.IsAnonymous,
							BitsUsed = cbev2.BitsUsed,
							ChannelId = cbev2.ChannelId,
							ChannelName = cbev2.ChannelName,
							ChatMessage = cbev2.ChatMessage,
							Context = cbev2.Context,
							Time = cbev2.Time,
							TotalBitsUsed = cbev2.TotalBitsUsed,
							UserId = cbev2.UserId,
							UserName = cbev2.UserName
						});
						return;
					}
					break;
				}
				case "channel-ext-v1":
				{
					ChannelExtensionBroadcast cEB = msg.MessageData as ChannelExtensionBroadcast;
					this.OnChannelExtensionBroadcast?.Invoke(this, new OnChannelExtensionBroadcastArgs
					{
						Messages = cEB.Messages,
						ChannelId = channelId
					});
					return;
				}
				case "video-playback-by-id":
				{
					VideoPlayback vP = msg.MessageData as VideoPlayback;
					switch (vP?.Type)
					{
					case VideoPlaybackType.StreamDown:
						this.OnStreamDown?.Invoke(this, new OnStreamDownArgs
						{
							ServerTime = vP.ServerTime,
							ChannelId = channelId
						});
						return;
					case VideoPlaybackType.StreamUp:
						this.OnStreamUp?.Invoke(this, new OnStreamUpArgs
						{
							PlayDelay = vP.PlayDelay,
							ServerTime = vP.ServerTime,
							ChannelId = channelId
						});
						return;
					case VideoPlaybackType.ViewCount:
						this.OnViewCount?.Invoke(this, new OnViewCountArgs
						{
							ServerTime = vP.ServerTime,
							Viewers = vP.Viewers,
							ChannelId = channelId
						});
						return;
					case VideoPlaybackType.Commercial:
						this.OnCommercial?.Invoke(this, new OnCommercialArgs
						{
							ServerTime = vP.ServerTime,
							Length = vP.Length,
							ChannelId = channelId
						});
						return;
					}
					break;
				}
				case "community-points-channel-v1":
				{
					CommunityPointsChannel cpc = msg.MessageData as CommunityPointsChannel;
					CommunityPointsChannelType? communityPointsChannelType = cpc?.Type;
					CommunityPointsChannelType? communityPointsChannelType2 = communityPointsChannelType;
					if (communityPointsChannelType2.HasValue)
					{
						switch (communityPointsChannelType2.GetValueOrDefault())
						{
						case CommunityPointsChannelType.RewardRedeemed:
							this.OnRewardRedeemed?.Invoke(this, new OnRewardRedeemedArgs
							{
								TimeStamp = cpc.TimeStamp,
								ChannelId = cpc.ChannelId,
								Login = cpc.Login,
								DisplayName = cpc.DisplayName,
								Message = cpc.Message,
								RewardId = cpc.RewardId,
								RewardTitle = cpc.RewardTitle,
								RewardPrompt = cpc.RewardPrompt,
								RewardCost = cpc.RewardCost,
								Status = cpc.Status,
								RedemptionId = cpc.RedemptionId
							});
							break;
						case CommunityPointsChannelType.CustomRewardUpdated:
							this.OnCustomRewardUpdated?.Invoke(this, new OnCustomRewardUpdatedArgs
							{
								TimeStamp = cpc.TimeStamp,
								ChannelId = cpc.ChannelId,
								RewardId = cpc.RewardId,
								RewardTitle = cpc.RewardTitle,
								RewardPrompt = cpc.RewardPrompt,
								RewardCost = cpc.RewardCost
							});
							break;
						case CommunityPointsChannelType.CustomRewardCreated:
							this.OnCustomRewardCreated?.Invoke(this, new OnCustomRewardCreatedArgs
							{
								TimeStamp = cpc.TimeStamp,
								ChannelId = cpc.ChannelId,
								RewardId = cpc.RewardId,
								RewardTitle = cpc.RewardTitle,
								RewardPrompt = cpc.RewardPrompt,
								RewardCost = cpc.RewardCost
							});
							break;
						case CommunityPointsChannelType.CustomRewardDeleted:
							this.OnCustomRewardDeleted?.Invoke(this, new OnCustomRewardDeletedArgs
							{
								TimeStamp = cpc.TimeStamp,
								ChannelId = cpc.ChannelId,
								RewardId = cpc.RewardId,
								RewardTitle = cpc.RewardTitle,
								RewardPrompt = cpc.RewardPrompt
							});
							break;
						}
					}
					return;
				}
				case "channel-points-channel-v1":
				{
					ChannelPointsChannel channelPointsChannel = msg.MessageData as ChannelPointsChannel;
					switch (channelPointsChannel.Type)
					{
					case ChannelPointsChannelType.RewardRedeemed:
					{
						RewardRedeemed rewardRedeemed = channelPointsChannel.Data as RewardRedeemed;
						this.OnChannelPointsRewardRedeemed?.Invoke(this, new OnChannelPointsRewardRedeemedArgs
						{
							ChannelId = rewardRedeemed.Redemption.ChannelId,
							RewardRedeemed = rewardRedeemed
						});
						break;
					}
					case ChannelPointsChannelType.Unknown:
						UnaccountedFor("Unknown channel points type. Msg: " + channelPointsChannel.RawData);
						break;
					}
					return;
				}
				case "leaderboard-events-v1":
				{
					LeaderboardEvents lbe = msg.MessageData as LeaderboardEvents;
					LeaderBoardType? leaderBoardType = lbe?.Type;
					LeaderBoardType? leaderBoardType2 = leaderBoardType;
					if (leaderBoardType2.HasValue)
					{
						switch (leaderBoardType2.GetValueOrDefault())
						{
						case LeaderBoardType.BitsUsageByChannel:
							this.OnLeaderboardBits?.Invoke(this, new OnLeaderboardEventArgs
							{
								ChannelId = lbe.ChannelId,
								TopList = lbe.Top
							});
							break;
						case LeaderBoardType.SubGiftSent:
							this.OnLeaderboardSubs?.Invoke(this, new OnLeaderboardEventArgs
							{
								ChannelId = lbe.ChannelId,
								TopList = lbe.Top
							});
							break;
						}
					}
					return;
				}
				case "raid":
				{
					RaidEvents r = msg.MessageData as RaidEvents;
					RaidType? raidType = r?.Type;
					RaidType? raidType2 = raidType;
					if (raidType2.HasValue)
					{
						switch (raidType2.GetValueOrDefault())
						{
						case RaidType.RaidUpdate:
							this.OnRaidUpdate?.Invoke(this, new OnRaidUpdateArgs
							{
								Id = r.Id,
								ChannelId = r.ChannelId,
								TargetChannelId = r.TargetChannelId,
								AnnounceTime = r.AnnounceTime,
								RaidTime = r.RaidTime,
								RemainingDurationSeconds = r.RemainigDurationSeconds,
								ViewerCount = r.ViewerCount
							});
							break;
						case RaidType.RaidUpdateV2:
							this.OnRaidUpdateV2?.Invoke(this, new OnRaidUpdateV2Args
							{
								Id = r.Id,
								ChannelId = r.ChannelId,
								TargetChannelId = r.TargetChannelId,
								TargetLogin = r.TargetLogin,
								TargetDisplayName = r.TargetDisplayName,
								TargetProfileImage = r.TargetProfileImage,
								ViewerCount = r.ViewerCount
							});
							break;
						case RaidType.RaidGo:
							this.OnRaidGo?.Invoke(this, new OnRaidGoArgs
							{
								Id = r.Id,
								ChannelId = r.ChannelId,
								TargetChannelId = r.TargetChannelId,
								TargetLogin = r.TargetLogin,
								TargetDisplayName = r.TargetDisplayName,
								TargetProfileImage = r.TargetProfileImage,
								ViewerCount = r.ViewerCount
							});
							break;
						case RaidType.RaidCancel:
							this.OnRaidCancel?.Invoke(this, new OnRaidCancelArgs
							{
								Id = r.Id,
								ChannelId = r.ChannelId,
								TargetChannelId = r.TargetChannelId,
								TargetLogin = r.TargetLogin,
								TargetDisplayName = r.TargetDisplayName,
								TargetProfileImage = r.TargetProfileImage,
								ViewerCount = r.ViewerCount
							});
							break;
						}
					}
					return;
				}
				case "predictions-channel-v1":
				{
					PredictionEvents pred = msg.MessageData as PredictionEvents;
					PredictionType? predictionType = pred?.Type;
					PredictionType? predictionType2 = predictionType;
					if (predictionType2.HasValue)
					{
						switch (predictionType2.GetValueOrDefault())
						{
						case PredictionType.EventCreated:
							this.OnPrediction?.Invoke(this, new OnPredictionArgs
							{
								CreatedAt = pred.CreatedAt,
								Title = pred.Title,
								ChannelId = pred.ChannelId,
								EndedAt = pred.EndedAt,
								Id = pred.Id,
								Outcomes = pred.Outcomes,
								LockedAt = pred.LockedAt,
								PredictionTime = pred.PredictionTime,
								Status = pred.Status,
								WinningOutcomeId = pred.WinningOutcomeId,
								Type = pred.Type
							});
							break;
						case PredictionType.EventUpdated:
							this.OnPrediction?.Invoke(this, new OnPredictionArgs
							{
								CreatedAt = pred.CreatedAt,
								Title = pred.Title,
								ChannelId = pred.ChannelId,
								EndedAt = pred.EndedAt,
								Id = pred.Id,
								Outcomes = pred.Outcomes,
								LockedAt = pred.LockedAt,
								PredictionTime = pred.PredictionTime,
								Status = pred.Status,
								WinningOutcomeId = pred.WinningOutcomeId,
								Type = pred.Type
							});
							break;
						default:
							UnaccountedFor($"Prediction Type: {pred.Type}");
							break;
						}
					}
					else
					{
						UnaccountedFor("Prediction Type: null");
					}
					return;
				}
				}
				break;
			}
			case "pong":
				_pongReceived = true;
				return;
			case "reconnect":
				await ((ClientBase<ClientWebSocket>)(object)_socket).CloseAsync();
				break;
			}
			UnaccountedFor(message);
		}

		private static string GenerateNonce()
		{
			Span<char> span = stackalloc char[8];
			Span<char> span2 = span;
			for (int i = 0; i < span2.Length; i++)
			{
				ref char reference = ref span2[i];
				int index = Random.Next("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".Length);
				reference = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[index];
			}
			return span.ToString();
		}

		private void ListenToTopic(string topic)
		{
			_topicList.Add(topic);
		}

		private void ListenToTopics(params string[] topics)
		{
			foreach (string item in topics)
			{
				_topicList.Add(item);
			}
		}

		public void SendTopics(string oauth = null, bool unlisten = false)
		{
			SendTopicsAsync(oauth, unlisten).GetAwaiter().GetResult();
		}

		public async Task SendTopicsAsync(string oauth = null, bool unlisten = false)
		{
			if (oauth?.Contains("oauth:") ?? false)
			{
				oauth = oauth.Replace("oauth:", "");
			}
			string nonce = GenerateNonce();
			List<string> topics = new List<string>(_topicList.Count);
			_previousRequestsSemaphore.WaitOne();
			try
			{
				foreach (string val in _topicList)
				{
					_previousRequests.Add(new PreviousRequest(nonce, PubSubRequestType.ListenToTopic, val));
					topics.Add(val);
				}
			}
			finally
			{
				_previousRequestsSemaphore.Release();
			}
			Request request = new Request
			{
				Type = (unlisten ? "UNLISTEN" : "LISTEN"),
				Nonce = nonce,
				Data = new RequestData
				{
					Topics = topics,
					AuthToken = oauth
				}
			};
			string json = JsonConvert.SerializeObject((object)request);
			await ((ClientBase<ClientWebSocket>)(object)_socket).SendAsync(json);
			_topicList.Clear();
		}

		private void UnaccountedFor(string message)
		{
			_logger?.LogUnaccountedFor(message);
		}

		public void ListenToChatModeratorActions(string userId, string channelId)
		{
			string text = "chat_moderator_actions." + userId + "." + channelId;
			_topicToChannelId[text] = channelId;
			ListenToTopic(text);
		}

		public void ListenToUserModerationNotifications(string myTwitchId, string channelTwitchId)
		{
			string text = "user-moderation-notifications." + myTwitchId + "." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToAutomodQueue(string userTwitchId, string channelTwitchId)
		{
			string text = "automod-queue." + userTwitchId + "." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToChannelExtensionBroadcast(string channelId, string extensionId)
		{
			string text = "channel-ext-v1." + channelId + "-" + extensionId + "-broadcast";
			_topicToChannelId[text] = channelId;
			ListenToTopic(text);
		}

		public void ListenToBitsEventsV2(string channelTwitchId)
		{
			string text = "channel-bits-events-v2." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToVideoPlayback(string channelTwitchId)
		{
			string text = "video-playback-by-id." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToWhispers(string channelTwitchId)
		{
			string text = "whispers." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		[Obsolete("This method listens to an undocumented/retired/obsolete topic. Consider using ListenToChannelPoints()", false)]
		public void ListenToRewards(string channelTwitchId)
		{
			string text = "community-points-channel-v1." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToChannelPoints(string channelTwitchId)
		{
			string text = "channel-points-channel-v1." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToLeaderboards(string channelTwitchId)
		{
			string text = "leaderboard-events-v1.bits-usage-by-channel-v1-" + channelTwitchId + "-WEEK";
			string text2 = "leaderboard-events-v1.sub-gift-sent-" + channelTwitchId + "-WEEK";
			_topicToChannelId[text] = channelTwitchId;
			_topicToChannelId[text2] = channelTwitchId;
			ListenToTopics(text, text2);
		}

		public void ListenToRaid(string channelTwitchId)
		{
			string text = "raid." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToSubscriptions(string channelId)
		{
			string text = "channel-subscribe-events-v1." + channelId;
			_topicToChannelId[text] = channelId;
			ListenToTopic(text);
		}

		public void ListenToPredictions(string channelTwitchId)
		{
			string text = "predictions-channel-v1." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToChannelBitsBadgeUnlocks(string channelTwitchId)
		{
			string text = "channel-bits-badge-unlocks." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToLowTrustUsers(string channelTwitchId, string suspiciousUser)
		{
			string text = "low-trust-users." + channelTwitchId + "." + suspiciousUser;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void ListenToHypeTrains(string channelTwitchId)
		{
			string text = "hype-train-events-v1." + channelTwitchId;
			_topicToChannelId[text] = channelTwitchId;
			ListenToTopic(text);
		}

		public void Connect()
		{
			ConnectAsync().GetAwaiter().GetResult();
		}

		public async Task ConnectAsync()
		{
			await ((ClientBase<ClientWebSocket>)(object)_socket).OpenAsync();
		}

		public void Disconnect()
		{
			DisconnectAsync().GetAwaiter().GetResult();
		}

		public async Task DisconnectAsync()
		{
			await ((ClientBase<ClientWebSocket>)(object)_socket).CloseAsync();
		}

		public void TestMessageParser(string testJsonString)
		{
			ParseMessageAsync(testJsonString).GetAwaiter().GetResult();
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual async void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				if (disposing)
				{
					await ((ClientBase<ClientWebSocket>)(object)_socket).CloseAsync();
					((ClientBase<ClientWebSocket>)(object)_socket).Dispose();
					_previousRequestsSemaphore.Dispose();
					_pingTimer.Dispose();
					_pongTimer.Dispose();
				}
				_previousRequests.Clear();
				_topicList.Clear();
				_disposed = true;
			}
		}

		~TwitchPubSub()
		{
			Dispose(disposing: false);
		}
	}
}
namespace TwitchLib.PubSub.Models
{
	public class LeaderBoard
	{
		public int Place { get; set; }

		public int Score { get; set; }

		public string UserId { get; set; }
	}
	public class Outcome
	{
		public class Predictor
		{
			public long Points { get; set; }

			public string UserId { get; set; }

			public string DisplayName { get; set; }
		}

		public Guid Id { get; set; }

		public string Color { get; set; }

		public string Title { get; set; }

		public long TotalPoints { get; set; }

		public long TotalUsers { get; set; }

		public ICollection<Predictor> TopPredictors { get; set; } = new List<Predictor>();

	}
	public class PreviousRequest
	{
		public string Nonce { get; }

		public PubSubRequestType RequestType { get; }

		public string Topic { get; }

		public PreviousRequest(string nonce, PubSubRequestType requestType, string topic = "none set")
		{
			Nonce = nonce;
			RequestType = requestType;
			Topic = topic;
		}
	}
	internal class Request
	{
		[JsonProperty("type")]
		public string Type { get; set; }

		[JsonProperty("nonce")]
		public string Nonce { get; set; }

		[JsonProperty("data")]
		public RequestData Data { get; set; }
	}
	internal class RequestData
	{
		[JsonProperty("topics")]
		public List<string> Topics { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string AuthToken { get; set; }
	}
}
namespace TwitchLib.PubSub.Models.Responses
{
	public class Message
	{
		public readonly MessageData MessageData;

		public string Topic { get; }

		public Message(string jsonStr)
			: this(JObject.Parse(jsonStr))
		{
		}

		internal Message(JObject jsonObject)
		{
			JToken val = ((JToken)jsonObject).SelectToken("data");
			Topic = ((object)val.SelectToken("topic"))?.ToString();
			string text = ((object)val.SelectToken("message")).ToString();
			string topic = Topic;
			switch ((topic != null) ? topic.Split('.')[0] : null)
			{
			case "user-moderation-notifications":
				MessageData = new UserModerationNotifications(text);
				break;
			case "automod-queue":
				MessageData = new AutomodQueue(text);
				break;
			case "chat_moderator_actions":
				MessageData = new ChatModeratorActions(text);
				break;
			case "channel-bits-events-v2":
			{
				text = text.Replace("\\", "");
				string text3 = ((object)JObject.Parse(text)["data"]).ToString();
				MessageData = JsonConvert.DeserializeObject<ChannelBitsEventsV2>(text3);
				break;
			}
			case "video-playback-by-id":
				MessageData = new VideoPlayback(text);
				break;
			case "whispers":
				MessageData = new Whisper(text);
				break;
			case "channel-subscribe-events-v1":
				MessageData = new ChannelSubscription(text);
				break;
			case "channel-ext-v1":
				MessageData = new ChannelExtensionBroadcast(text);
				break;
			case "community-points-channel-v1":
				MessageData = new CommunityPointsChannel(text);
				break;
			case "channel-points-channel-v1":
				MessageData = new ChannelPointsChannel(text);
				break;
			case "leaderboard-events-v1":
				MessageData = new LeaderboardEvents(text);
				break;
			case "raid":
				MessageData = new RaidEvents(text);
				break;
			case "predictions-channel-v1":
				MessageData = new PredictionEvents(text);
				break;
			case "channel-bits-badge-unlocks":
			{
				text = text.Replace("\\", "");
				string text2 = ((object)JObject.Parse(text)["data"]).ToString();
				MessageData = JsonConvert.DeserializeObject<BitsBadgeNotificationMessage>(text2);
				break;
			}
			case "low-trust-users":
				MessageData = new LowTrustUsers(text);
				break;
			case "hype-train-events-v1":
				MessageData = new HypeTrainEvent(text);
				break;
			}
		}
	}
	public class Response
	{
		public string Error { get; }

		public string Nonce { get; }

		public bool Successful { get; }

		public Response(string json)
			: this(JObject.Parse(json))
		{
		}

		internal Response(JObject json)
		{
			Error = ((object)((JToken)json).SelectToken("error"))?.ToString();
			Nonce = ((object)((JToken)json).SelectToken("nonce"))?.ToString();
			if (string.IsNullOrWhiteSpace(Error))
			{
				Successful = true;
			}
		}
	}
}
namespace TwitchLib.PubSub.Models.Responses.Messages
{
	public class AutomodQueue : MessageData
	{
		public AutomodQueueType Type { get; private set; }

		public AutomodQueueData Data { get; private set; }

		public string RawData { get; private set; }

		public AutomodQueue(string jsonStr)
		{
			RawData = jsonStr;
			JToken val = (JToken)(object)JObject.Parse(jsonStr);
			string text = ((object)val.SelectToken("type")).ToString();
			string text2 = text;
			if (text2 == "automod_caught_message")
			{
				Type = AutomodQueueType.CaughtMessage;
				Data = JsonConvert.DeserializeObject<TwitchLib.PubSub.Models.Responses.Messages.AutomodCaughtMessage.AutomodCaughtMessage>(((object)val.SelectToken("data")).ToString());
			}
			else
			{
				Type = AutomodQueueType.Unknown;
			}
		}
	}
	public abstract class AutomodQueueData
	{
	}
	public class BitsBadgeNotificationMessage : MessageData
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "channel_id")]
		public string ChannelId { get; protected set; }

		[JsonProperty(PropertyName = "channel_name")]
		public string ChannelName { get; protected set; }

		[JsonProperty(PropertyName = "badge_tier")]
		public int BadgeTier { get; protected set; }

		[JsonProperty(PropertyName = "chat_message")]
		public string ChatMessage { get; protected set; }

		[JsonProperty(PropertyName = "time")]
		public DateTime Time { get; protected set; }
	}
	public class ChannelBitsEventsV2 : MessageData
	{
		[JsonProperty(PropertyName = "user_name")]
		public string UserName { get; protected set; }

		[JsonProperty(PropertyName = "channel_name")]
		public string ChannelName { get; protected set; }

		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "channel_id")]
		public string ChannelId { get; protected set; }

		[JsonProperty(PropertyName = "time")]
		public DateTime Time { get; protected set; }

		[JsonProperty(PropertyName = "chat_message")]
		public string ChatMessage { get; protected set; }

		[JsonProperty(PropertyName = "bits_used")]
		public int BitsUsed { get; protected set; }

		[JsonProperty(PropertyName = "total_bits_used")]
		public int TotalBitsUsed { get; protected set; }

		[JsonProperty(PropertyName = "is_anonymous")]
		public bool IsAnonymous { get; protected set; }

		[JsonProperty(PropertyName = "context")]
		public string Context { get; protected set; }
	}
	public class ChannelExtensionBroadcast : MessageData
	{
		public List<string> Messages { get; } = new List<string>();


		public ChannelExtensionBroadcast(string jsonStr)
		{
			JObject val = JObject.Parse(jsonStr);
			foreach (JToken item in (IEnumerable<JToken>)val["content"])
			{
				Messages.Add(((object)item).ToString());
			}
		}
	}
	public class ChannelPointsChannel : MessageData
	{
		public ChannelPointsChannelType Type { get; private set; }

		public ChannelPointsData Data { get; private set; }

		public string RawData { get; private set; }

		public ChannelPointsChannel(string jsonStr)
		{
			RawData = jsonStr;
			JToken val = (JToken)(object)JObject.Parse(jsonStr);
			string text = ((object)val.SelectToken("type")).ToString();
			string text2 = text;
			if (text2 == "reward-redeemed")
			{
				Type = ChannelPointsChannelType.RewardRedeemed;
				Data = JsonConvert.DeserializeObject<RewardRedeemed>(((object)val.SelectToken("data")).ToString());
			}
			else
			{
				Type = ChannelPointsChannelType.Unknown;
			}
		}
	}
	public abstract class ChannelPointsData
	{
	}
	public class ChannelSubscription : MessageData
	{
		public string Username { get; }

		public string DisplayName { get; }

		public string RecipientName { get; }

		public string RecipientDisplayName { get; }

		public string ChannelName { get; }

		public string UserId { get; }

		public string ChannelId { get; }

		public string RecipientId { get; }

		public DateTime Time { get; }

		public SubscriptionPlan SubscriptionPlan { get; }

		public string SubscriptionPlanName { get; }

		public int? Months { get; }

		public int? CumulativeMonths { get; }

		public int? StreakMonths { get; }

		public string Context { get; }

		public SubMessage SubMessage { get; }

		public bool? IsGift { get; }

		public int? MultiMonthDuration { get; }

		public ChannelSubscription(string jsonStr)
		{
			JObject val = JObject.Parse(jsonStr);
			Username = ((object)((JToken)val).SelectToken("user_name"))?.ToString();
			DisplayName = ((object)((JToken)val).SelectToken("display_name"))?.ToString();
			RecipientName = ((object)((JToken)val).SelectToken("recipient_user_name"))?.ToString();
			RecipientDisplayName = ((object)((JToken)val).SelectToken("recipient_display_name"))?.ToString();
			ChannelName = ((object)((JToken)val).SelectToken("channel_name"))?.ToString();
			UserId = ((object)((JToken)val).SelectToken("user_id"))?.ToString();
			RecipientId = ((object)((JToken)val).SelectToken("recipient_id"))?.ToString();
			ChannelId = ((object)((JToken)val).SelectToken("channel_id"))?.ToString();
			Time = Helpers.DateTimeStringToObject(((object)((JToken)val).SelectToken("time"))?.ToString());
			switch (((object)((JToken)val).SelectToken("sub_plan")).ToString().ToLower())
			{
			case "prime":
				SubscriptionPlan = SubscriptionPlan.Prime;
				break;
			case "1000":
				SubscriptionPlan = SubscriptionPlan.Tier1;
				break;
			case "2000":
				SubscriptionPlan = SubscriptionPlan.Tier2;
				break;
			case "3000":
				SubscriptionPlan = SubscriptionPlan.Tier3;
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
			SubscriptionPlanName = ((object)((JToken)val).SelectToken("sub_plan_name"))?.ToString();
			SubMessage = new SubMessage(((JToken)val).SelectToken("sub_message"));
			string text = ((object)((JToken)val).SelectToken("is_gift"))?.ToString();
			if (text != null)
			{
				IsGift = Convert.ToBoolean(text.ToString());
			}
			string text2 = ((object)((JToken)val).SelectToken("multi_month_duration"))?.ToString();
			if (text2 != null)
			{
				MultiMonthDuration = int.Parse(text2.ToString());
			}
			Context = ((object)((JToken)val).SelectToken("context"))?.ToString();
			JToken val2 = ((JToken)val).SelectToken("months");
			if (val2 != null)
			{
				Months = int.Parse(((object)val2).ToString());
			}
			JToken val3 = ((JToken)val).SelectToken("cumulative_months");
			if (val3 != null)
			{
				CumulativeMonths = int.Parse(((object)val3).ToString());
			}
			JToken val4 = ((JToken)val).SelectToken("streak_months");
			if (val4 != null)
			{
				StreakMonths = int.Parse(((object)val4).ToString());
			}
		}
	}
	public class ChatModeratorActions : MessageData
	{
		public string Type { get; }

		public string ModerationAction { get; }

		public List<string> Args { get; } = new List<string>();


		public string CreatedBy { get; }

		public string CreatedByUserId { get; }

		public string TargetUserId { get; }

		public ChatModeratorActions(string jsonStr)
		{
			JToken val = ((JToken)JObject.Parse(jsonStr)).SelectToken("data");
			Type = ((object)val.SelectToken("type"))?.ToString();
			ModerationAction = ((object)val.SelectToken("moderation_action"))?.ToString();
			if (val.SelectToken("args") != null)
			{
				foreach (JToken item in (IEnumerable<JToken>)val.SelectToken("args"))
				{
					Args.Add(((object)item).ToString());
				}
			}
			CreatedBy = ((object)val.SelectToken("created_by")).ToString();
			CreatedByUserId = ((object)val.SelectToken("created_by_user_id")).ToString();
			TargetUserId = ((object)val.SelectToken("target_user_id")).ToString();
		}
	}
	public class CommunityPointsChannel : MessageData
	{
		public CommunityPointsChannelType Type { get; protected set; }

		public DateTime TimeStamp { get; protected set; }

		public string ChannelId { get; protected set; }

		public string Login { get; protected set; }

		public string DisplayName { get; protected set; }

		public string Message { get; protected set; }

		public Guid RewardId { get; protected set; }

		public string RewardTitle { get; protected set; }

		public string RewardPrompt { get; protected set; }

		public int RewardCost { get; protected set; }

		public string Status { get; protected set; }

		public Guid RedemptionId { get; protected set; }

		public CommunityPointsChannel(string jsonStr)
		{
			JToken val = (JToken)(object)JObject.Parse(jsonStr);
			switch (((object)val.SelectToken("type")).ToString())
			{
			case "reward-redeemed":
			case "redemption-status-update":
				Type = CommunityPointsChannelType.RewardRedeemed;
				break;
			case "custom-reward-created":
				Type = CommunityPointsChannelType.CustomRewardCreated;
				break;
			case "custom-reward-updated":
				Type = CommunityPointsChannelType.CustomRewardUpdated;
				break;
			case "custom-reward-deleted":
				Type = CommunityPointsChannelType.CustomRewardDeleted;
				break;
			default:
				Type = (CommunityPointsChannelType)(-1);
				break;
			}
			TimeStamp = DateTime.Parse(((object)val.SelectToken("data.timestamp")).ToString());
			switch (Type)
			{
			case CommunityPointsChannelType.RewardRedeemed:
				ChannelId = ((object)val.SelectToken("data.redemption.channel_id")).ToString();
				Login = ((object)val.SelectToken("data.redemption.user.login")).ToString();
				DisplayName = ((object)val.SelectToken("data.redemption.user.display_name")).ToString();
				RewardId = Guid.Parse(((object)val.SelectToken("data.redemption.reward.id")).ToString());
				RewardTitle = ((object)val.SelectToken("data.redemption.reward.title")).ToString();
				RewardPrompt = ((object)val.SelectToken("data.redemption.reward.prompt")).ToString();
				RewardCost = int.Parse(((object)val.SelectToken("data.redemption.reward.cost")).ToString());
				Message = ((object)val.SelectToken("data.redemption.user_input"))?.ToString();
				Status = ((object)val.SelectToken("data.redemption.status")).ToString();
				RedemptionId = Guid.Parse(((object)val.SelectToken("data.redemption.id")).ToString());
				break;
			case CommunityPointsChannelType.CustomRewardUpdated:
				ChannelId = ((object)val.SelectToken("data.updated_reward.channel_id")).ToString();
				RewardId = Guid.Parse(((object)val.SelectToken("data.updated_reward.id")).ToString());
				RewardTitle = ((object)val.SelectToken("data.updated_reward.title")).ToString();
				RewardPrompt = ((object)val.SelectToken("data.updated_reward.prompt")).ToString();
				RewardCost = int.Parse(((object)val.SelectToken("data.updated_reward.cost")).ToString());
				break;
			case CommunityPointsChannelType.CustomRewardCreated:
				ChannelId = ((object)val.SelectToken("data.new_reward.channel_id")).ToString();
				RewardId = Guid.Parse(((object)val.SelectToken("data.new_reward.id")).ToString());
				RewardTitle = ((object)val.SelectToken("data.new_reward.title")).ToString();
				RewardPrompt = ((object)val.SelectToken("data.new_reward.prompt")).ToString();
				RewardCost = int.Parse(((object)val.SelectToken("data.new_reward.cost")).ToString());
				break;
			case CommunityPointsChannelType.CustomRewardDeleted:
				ChannelId = ((object)val.SelectToken("data.deleted_reward.channel_id")).ToString();
				RewardId = Guid.Parse(((object)val.SelectToken("data.deleted_reward.id")).ToString());
				RewardTitle = ((object)val.SelectToken("data.deleted_reward.title")).ToString();
				RewardPrompt = ((object)val.SelectToken("data.deleted_reward.prompt")).ToString();
				break;
			}
		}
	}
	public class LeaderboardEvents : MessageData
	{
		public LeaderBoardType Type { get; private set; }

		public string ChannelId { get; private set; }

		public List<LeaderBoard> Top { get; private set; } = new List<LeaderBoard>();


		public LeaderboardEvents(string jsonStr)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			JToken val = (JToken)(object)JObject.Parse(jsonStr);
			string text = ((object)val.SelectToken("identifier.domain")).ToString();
			string text2 = text;
			if (!(text2 == "bits-usage-by-channel-v1"))
			{
				if (text2 == "sub-gift-sent")
				{
					Type = LeaderBoardType.SubGiftSent;
				}
			}
			else
			{
				Type = LeaderBoardType.BitsUsageByChannel;
			}
			switch (Type)
			{
			case LeaderBoardType.BitsUsageByChannel:
				ChannelId = ((object)val.SelectToken("identifier.grouping_key")).ToString();
				{
					foreach (JToken item in val[(object)"top"].Children())
					{
						Top.Add(new LeaderBoard
						{
							Place = int.Parse(((object)item.SelectToken("rank")).ToString()),
							Score = int.Parse(((object)item.SelectToken("score")).ToString()),
							UserId = ((object)item.SelectToken("entry_key")).ToString()
						});
					}
					break;
				}
			case LeaderBoardType.SubGiftSent:
				ChannelId = ((object)val.SelectToken("identifier.grouping_key")).ToString();
				{
					foreach (JToken item2 in val[(object)"top"].Children())
					{
						Top.Add(new LeaderBoard
						{
							Place = int.Parse(((object)item2.SelectToken("rank")).ToString()),
							Score = int.Parse(((object)item2.SelectToken("score")).ToString()),
							UserId = ((object)item2.SelectToken("entry_key")).ToString()
						});
					}
					break;
				}
			}
		}
	}
	public class LowTrustUsers : MessageData
	{
		public string LowTrustId { get; protected set; }

		public string ChannelId { get; protected set; }

		public UpdatedBy UpdatedBy { get; protected set; }

		public DateTime? UpdatedAt { get; protected set; }

		public string TargetUserId { get; protected set; }

		public string TargetUser { get; protected set; }

		public string Treatment { get; protected set; }

		public string[] Types { get; protected set; }

		public string BanEvasionEvaluation { get; protected set; }

		public DateTime? EvaluatedAt { get; protected set; }

		public LowTrustUsers(string jsonStr)
		{
			JToken val = (JToken)(object)JObject.Parse(jsonStr);
			JToken val2 = val.SelectToken("data");
			LowTrustId = ((object)val2.SelectToken("low_trust_id"))?.ToString();
			ChannelId = ((object)val2.SelectToken("channel_id"))?.ToString();
			UpdatedBy = new UpdatedBy(val2.SelectToken("updated_by"));
			UpdatedAt = (val2.SelectToken("updated_at").IsEmpty() ? null : new DateTime?(DateTime.Parse(((object)val2.SelectToken("updated_at")).ToString())));
			TargetUserId = ((object)val2.SelectToken("target_user"))?.ToString();
			TargetUser = ((object)val2.SelectToken("target_user"))?.ToString();
			Treatment = ((object)val2.SelectToken("treatment"))?.ToString();
			JToken obj = val2.SelectToken("types");
			Types = ((obj != null) ? obj.ToObject<string[]>() : null);
			BanEvasionEvaluation = ((object)val2.SelectToken("ban_evasion_evaluation"))?.ToString();
			EvaluatedAt = (val2.SelectToken("evaluated_at").IsEmpty() ? null : new DateTime?(DateTime.Parse(((object)val2.SelectToken("evaluated_at")).ToString())));
		}
	}
	public class UpdatedBy
	{
		public string Id { get; protected set; }

		public string Login { get; protected set; }

		public string DisplayName { get; protected set; }

		public UpdatedBy(JToken? json)
		{
			Id = ((json == null) ? null : ((object)json.SelectToken("id"))?.ToString());
			Login = ((json == null) ? null : ((object)json.SelectToken("login"))?.ToString());
			DisplayName = ((json == null) ? null : ((object)json.SelectToken("display_name"))?.ToString());
		}
	}
	public abstract class MessageData
	{
	}
	public class PredictionEvents : MessageData
	{
		public PredictionType Type { get; protected set; }

		public Guid Id { get; protected set; }

		public string ChannelId { get; protected set; }

		public DateTime? CreatedAt { get; protected set; }

		public DateTime? LockedAt { get; protected set; }

		public DateTime? EndedAt { get; protected set; }

		public ICollection<Outcome> Outcomes { get; protected set; } = new List<Outcome>();


		public PredictionStatus Status { get; protected set; }

		public string Title { get; protected set; }

		public Guid? WinningOutcomeId { get; protected set; }

		public int PredictionTime { get; protected set; }

		public PredictionEvents(string jsonStr)
		{
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			JObject val = JObject.Parse(jsonStr);
			Type = (PredictionType)Enum.Parse(typeof(PredictionType), ((object)((JToken)val).SelectToken("type")).ToString().Replace("-", ""), ignoreCase: true);
			JToken val2 = ((JToken)val).SelectToken("data.event");
			Id = Guid.Parse(((object)val2.SelectToken("id")).ToString());
			ChannelId = ((object)val2.SelectToken("channel_id")).ToString();
			CreatedAt = (val2.SelectToken("created_at").IsEmpty() ? null : new DateTime?(DateTime.Parse(((object)val2.SelectToken("created_at")).ToString())));
			EndedAt = (val2.SelectToken("ended_at").IsEmpty() ? null : new DateTime?(DateTime.Parse(((object)val2.SelectToken("ended_at")).ToString())));
			LockedAt = (val2.SelectToken("locked_at").IsEmpty() ? null : new DateTime?(DateTime.Parse(((object)val2.SelectToken("locked_at")).ToString())));
			Status = (PredictionStatus)Enum.Parse(typeof(PredictionStatus), ((object)val2.SelectToken("status")).ToString().Replace("_", ""), ignoreCase: true);
			Title = ((object)val2.SelectToken("title")).ToString();
			WinningOutcomeId = (val2.SelectToken("winning_outcome_id").IsEmpty() ? null : new Guid?(Guid.Parse(((object)val2.SelectToken("winning_outcome_id")).ToString())));
			PredictionTime = int.Parse(((object)val2.SelectToken("prediction_window_seconds")).ToString());
			foreach (JToken item in val2.SelectToken("outcomes").Children())
			{
				Outcome outcome = new Outcome
				{
					Id = Guid.Parse(((object)item.SelectToken("id")).ToString()),
					Color = ((object)item.SelectToken("color")).ToString(),
					Title = ((object)item.SelectToken("title")).ToString(),
					TotalPoints = long.Parse(((object)item.SelectToken("total_points")).ToString()),
					TotalUsers = long.Parse(((object)item.SelectToken("total_users")).ToString())
				};
				foreach (JToken item2 in item.SelectToken("top_predictors").Children())
				{
					outcome.TopPredictors.Add(new Outcome.Predictor
					{
						DisplayName = ((object)item2.SelectToken("user_display_name")).ToString(),
						Points = int.Parse(((object)item2.SelectToken("points")).ToString()),
						UserId = ((object)item2.SelectToken("user_id")).ToString()
					});
				}
				Outcomes.Add(outcome);
			}
		}
	}
	public class RaidEvents : MessageData
	{
		public RaidType Type { get; protected set; }

		public Guid Id { get; protected set; }

		public string ChannelId { get; protected set; }

		public string TargetChannelId { get; protected set; }

		public string TargetLogin { get; protected set; }

		public string TargetDisplayName { get; protected set; }

		public string TargetProfileImage { get; protected set; }

		public DateTime AnnounceTime { get; protected set; }

		public DateTime RaidTime { get; protected set; }

		public int RemainigDurationSeconds { get; protected set; }

		public int ViewerCount { get; protected set; }

		public RaidEvents(string jsonStr)
		{
			JToken val = (JToken)(object)JObject.Parse(jsonStr);
			switch (((object)val.SelectToken("type")).ToString())
			{
			case "raid_update":
				Type = RaidType.RaidUpdate;
				break;
			case "raid_update_v2":
				Type = RaidType.RaidUpdateV2;
				break;
			case "raid_go_v2":
				Type = RaidType.RaidGo;
				break;
			case "raid_cancel_v2":
				Type = RaidType.RaidCancel;
				break;
			}
			switch (Type)
			{
			case RaidType.RaidUpdate:
				Id = Guid.Parse(((object)val.SelectToken("raid.id")).ToString());
				ChannelId = ((object)val.SelectToken("raid.source_id")).ToString();
				TargetChannelId = ((object)val.SelectToken("raid.target_id")).ToString();
				AnnounceTime = DateTime.Parse(((object)val.SelectToken("raid.announce_time")).ToString());
				RaidTime = DateTime.Parse(((object)val.SelectToken("raid.raid_time")).ToString());
				RemainigDurationSeconds = int.Parse(((object)val.SelectToken("raid.remaining_duration_seconds")).ToString());
				ViewerCount = int.Parse(((object)val.SelectToken("raid.viewer_count")).ToString());
				break;
			case RaidType.RaidUpdateV2:
				Id = Guid.Parse(((object)val.SelectToken("raid.id")).ToString());
				ChannelId = ((object)val.SelectToken("raid.source_id")).ToString();
				TargetChannelId = ((object)val.SelectToken("raid.target_id")).ToString();
				TargetLogin = ((object)val.SelectToken("raid.target_login")).ToString();
				TargetDisplayName = ((object)val.SelectToken("raid.target_display_name")).ToString();
				TargetProfileImage = ((object)val.SelectToken("raid.target_profile_image")).ToString();
				ViewerCount = int.Parse(((object)val.SelectToken("raid.viewer_count")).ToString());
				break;
			case RaidType.RaidGo:
				Id = Guid.Parse(((object)val.SelectToken("raid.id")).ToString());
				ChannelId = ((object)val.SelectToken("raid.source_id")).ToString();
				TargetChannelId = ((object)val.SelectToken("raid.target_id")).ToString();
				TargetLogin = ((object)val.SelectToken("raid.target_login")).ToString();
				TargetDisplayName = ((object)val.SelectToken("raid.target_display_name")).ToString();
				TargetProfileImage = ((object)val.SelectToken("raid.target_profile_image")).ToString();
				ViewerCount = int.Parse(((object)val.SelectToken("raid.viewer_count")).ToString());
				break;
			case RaidType.RaidCancel:
				Id = Guid.Parse(((object)val.SelectToken("raid.id")).ToString());
				ChannelId = ((object)val.SelectToken("raid.source_id")).ToString();
				TargetChannelId = ((object)val.SelectToken("raid.target_id")).ToString();
				TargetLogin = ((object)val.SelectToken("raid.target_login")).ToString();
				TargetDisplayName = ((object)val.SelectToken("raid.target_display_name")).ToString();
				TargetProfileImage = ((object)val.SelectToken("raid.target_profile_image")).ToString();
				ViewerCount = int.Parse(((object)val.SelectToken("raid.viewer_count")).ToString());
				break;
			}
		}
	}
	public class SubMessage : MessageData
	{
		public class Emote
		{
			public int Start { get; }

			public int End { get; }

			public string Id { get; }

			public Emote(JToken json)
			{
				Start = int.Parse(((object)json.SelectToken("start")).ToString());
				End = int.Parse(((object)json.SelectToken("end")).ToString());
				Id = ((object)json.SelectToken("id")).ToString();
			}
		}

		public string Message { get; }

		public List<Emote> Emotes { get; } = new List<Emote>();


		public SubMessage(JToken json)
		{
			Message = ((object)json.SelectToken("message"))?.ToString();
			foreach (JToken item in (IEnumerable<JToken>)json.SelectToken("emotes"))
			{
				Emotes.Add(new Emote(item));
			}
		}
	}
	public class User
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "login")]
		public string Login { get; protected set; }

		[JsonProperty(PropertyName = "display_name")]
		public string DisplayName { get; protected set; }
	}
	public abstract class UserModerationNotificationsData
	{
	}
	public class VideoPlayback : MessageData
	{
		public VideoPlaybackType Type { get; }

		public string ServerTime { get; }

		public int PlayDelay { get; }

		public int Viewers { get; }

		public int Length { get; }

		public VideoPlayback(string jsonStr)
		{
			JToken val = (JToken)(object)JObject.Parse(jsonStr);
			switch (((object)val.SelectToken("type")).ToString())
			{
			case "stream-up":
				Type = VideoPlaybackType.StreamUp;
				break;
			case "stream-down":
				Type = VideoPlaybackType.StreamDown;
				break;
			case "viewcount":
				Type = VideoPlaybackType.ViewCount;
				break;
			case "commercial":
				Type = VideoPlaybackType.Commercial;
				break;
			}
			ServerTime = ((object)val.SelectToken("server_time"))?.ToString();
			switch (Type)
			{
			case VideoPlaybackType.StreamUp:
				PlayDelay = int.Parse(((object)val.SelectToken("play_delay")).ToString());
				break;
			case VideoPlaybackType.ViewCount:
				Viewers = int.Parse(((object)val.SelectToken("viewers")).ToString());
				break;
			case VideoPlaybackType.StreamDown:
				break;
			case VideoPlaybackType.Commercial:
				Length = int.Parse(((object)val.SelectToken("length")).ToString());
				break;
			}
		}
	}
	public class Whisper : MessageData
	{
		public class DataObjThread
		{
			public class SpamInfoObj
			{
				public string Likelihood { get; }

				public long LastMarkedNotSpam { get; }

				public SpamInfoObj(JToken json)
				{
					Likelihood = ((object)json.SelectToken("likelihood")).ToString();
					LastMarkedNotSpam = long.Parse(((object)json.SelectToken("last_marked_not_spam")).ToString());
				}
			}

			public string Id { get; }

			public long LastRead { get; }

			public bool Archived { get; }

			public bool Muted { get; }

			public SpamInfoObj SpamInfo { get; }

			public DataObjThread(JToken json)
			{
				Id = ((object)json.SelectToken("id")).ToString();
				LastRead = long.Parse(((object)json.SelectToken("last_read")).ToString());
				Archived = bool.Parse(((object)json.SelectToken("archived")).ToString());
				Muted = bool.Parse(((object)json.SelectToken("muted")).ToString());
				SpamInfo = new SpamInfoObj(json.SelectToken("spam_info"));
			}
		}

		public class DataObjWhisperReceived
		{
			public class TagsObj
			{
				public class EmoteObj
				{
					public string Id { get; protected set; }

					public int Start { get; protected set; }

					public int End { get; protected set; }

					public EmoteObj(JToken json)
					{
						Id = ((object)json.SelectToken("emote_id")).ToString();
						Start = int.Parse(((object)json.SelectToken("start")).ToString());
						End = int.Parse(((object)json.SelectToken("end")).ToString());
					}
				}

				public readonly List<EmoteObj> Emotes = new List<EmoteObj>();

				public readonly List<Badge> Badges = new List<Badge>();

				public string Login { get; protected set; }

				public string DisplayName { get; protected set; }

				public string Color { get; protected set; }

				public string UserType { get; protected set; }

				public TagsObj(JToken json)
				{
					Login = ((object)json.SelectToken("login"))?.ToString();
					DisplayName = ((object)json.SelectToken("login"))?.ToString();
					Color = ((object)json.SelectToken("color"))?.ToString();
					UserType = ((object)json.SelectToken("user_type"))?.ToString();
					foreach (JToken item in (IEnumerable<JToken>)json.SelectToken("emotes"))
					{
						Emotes.Add(new EmoteObj(item));
					}
					foreach (JToken item2 in (IEnumerable<JToken>)json.SelectToken("badges"))
					{
						Badges.Add(new Badge(item2));
					}
				}
			}

			public class RecipientObj
			{
				public string Id { get; protected set; }

				public string Username { get; protected set; }

				public string DisplayName { get; protected set; }

				public string Color { get; protected set; }

				public string UserType { get; protected set; }

				public RecipientObj(JToken json)
				{
					Id = ((object)json.SelectToken("id")).ToString();
					Username = ((object)json.SelectToken("username"))?.ToString();
					DisplayName = ((object)json.SelectToken("display_name"))?.ToString();
					Color = ((object)json.SelectToken("color"))?.ToString();
					UserType = ((object)json.SelectToken("user_type"))?.ToString();
				}
			}

			public class Badge
			{
				public string Id { get; protected set; }

				public string Version { get; protected set; }

				public Badge(JToken json)
				{
					Id = ((object)json.SelectToken("id"))?.ToString();
					Version = ((object)json.SelectToken("version"))?.ToString();
				}
			}

			public string Id { get; protected set; }

			public string ThreadId { get; protected set; }

			public string Body { get; protected set; }

			public long SentTs { get; protected set; }

			public string FromId { get; protected set; }

			public TagsObj Tags { get; protected set; }

			public RecipientObj Recipient { get; protected set; }

			public string Nonce { get; protected set; }

			public DataObjWhisperReceived(JToken json)
			{
				Id = ((object)json.SelectToken("id")).ToString();
				ThreadId = ((object)json.SelectToken("thread_id"))?.ToString();
				Body = ((object)json.SelectToken("body"))?.ToString();
				SentTs = long.Parse(((object)json.SelectToken("sent_ts")).ToString());
				FromId = ((object)json.SelectToken("from_id")).ToString();
				Tags = new TagsObj(json.SelectToken("tags"));
				Recipient = new RecipientObj(json.SelectToken("recipient"));
				Nonce = ((object)json.SelectToken("nonce"))?.ToString();
			}
		}

		public string Type { get; }

		public WhisperType TypeEnum { get; }

		public string Data { get; }

		public DataObjWhisperReceived DataObjectWhisperReceived { get; }

		public DataObjThread DataObjectThread { get; }

		public Whisper(string jsonStr)
		{
			JObject val = JObject.Parse(jsonStr);
			Type = ((object)((JToken)val).SelectToken("type")).ToString();
			Data = ((object)((JToken)val).SelectToken("data")).ToString();
			string type = Type;
			string text = type;
			if (!(text == "whisper_received"))
			{
				if (text == "thread")
				{
					TypeEnum = WhisperType.Thread;
					DataObjectThread = new DataObjThread(((JToken)val).SelectToken("data_object"));
				}
				else
				{
					TypeEnum = WhisperType.Unknown;
				}
			}
			else
			{
				TypeEnum = WhisperType.WhisperReceived;
				DataObjectWhisperReceived = new DataObjWhisperReceived(((JToken)val).SelectToken("data_object"));
			}
		}
	}
}
namespace TwitchLib.PubSub.Models.Responses.Messages.UserModerationNotificationsTypes
{
	public class AutomodCaughtMessage : UserModerationNotificationsData
	{
		[JsonProperty(PropertyName = "message_id")]
		public string MessageId { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public string Status { get; protected set; }
	}
}
namespace TwitchLib.PubSub.Models.Responses.Messages.UserModerationNotifications
{
	public class UserModerationNotifications : MessageData
	{
		public UserModerationNotificationsType Type { get; private set; }

		public UserModerationNotificationsData Data { get; private set; }

		public string RawData { get; private set; }

		public UserModerationNotifications(string jsonStr)
		{
			RawData = jsonStr;
			JToken val = (JToken)(object)JObject.Parse(jsonStr);
			string text = ((object)val.SelectToken("type")).ToString();
			string text2 = text;
			if (text2 == "automod_caught_message")
			{
				Type = UserModerationNotificationsType.AutomodCaughtMessage;
				Data = JsonConvert.DeserializeObject<TwitchLib.PubSub.Models.Responses.Messages.UserModerationNotificationsTypes.AutomodCaughtMessage>(((object)val.SelectToken("data")).ToString());
			}
			else
			{
				Type = UserModerationNotificationsType.Unknown;
			}
		}
	}
}
namespace TwitchLib.PubSub.Models.Responses.Messages.Redemption
{
	public class GlobalCooldown
	{
		[JsonProperty(PropertyName = "is_enabled")]
		public string IsEnabled { get; protected set; }

		[JsonProperty(PropertyName = "global_cooldown_seconds")]
		public int GlobalCooldownSeconds { get; protected set; }
	}
	public class MaxPerStream
	{
		[JsonProperty(PropertyName = "is_enabled")]
		public bool IsEnabled { get; protected set; }

		[JsonProperty(PropertyName = "max_per_stream")]
		public int MaxPerStreamValue { get; protected set; }
	}
	public class MaxPerUserPerStream
	{
		[JsonProperty(PropertyName = "is_enabled")]
		public string IsEnabled { get; protected set; }

		[JsonProperty(PropertyName = "max_per_user_per_stream")]
		public int MaxPerUserPerStreamValue { get; protected set; }
	}
	public class Redemption
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "user")]
		public User User { get; protected set; }

		[JsonProperty(PropertyName = "channel_id")]
		public string ChannelId { get; protected set; }

		[JsonProperty(PropertyName = "redeemed_at")]
		public DateTime RedeemedAt { get; protected set; }

		[JsonProperty(PropertyName = "reward")]
		public Reward Reward { get; protected set; }

		[JsonProperty(PropertyName = "user_input")]
		public string UserInput { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public string Status { get; protected set; }
	}
	public class RedemptionImage
	{
		[JsonProperty(PropertyName = "url_1x")]
		public string Url1x { get; protected set; }

		[JsonProperty(PropertyName = "url_2x")]
		public string Url2x { get; protected set; }

		[JsonProperty(PropertyName = "url_4x")]
		public string Url4x { get; protected set; }
	}
	public class Reward
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "channel_id")]
		public string ChannelId { get; protected set; }

		[JsonProperty(PropertyName = "title")]
		public string Title { get; protected set; }

		[JsonProperty(PropertyName = "prompt")]
		public string Prompt { get; protected set; }

		[JsonProperty(PropertyName = "cost")]
		public int Cost { get; protected set; }

		[JsonProperty(PropertyName = "is_user_input_required")]
		public bool IsUserInputRequired { get; protected set; }

		[JsonProperty(PropertyName = "is_sub_only")]
		public bool IsSubOnly { get; protected set; }

		[JsonProperty(PropertyName = "image")]
		public RedemptionImage Image { get; protected set; }

		[JsonProperty(PropertyName = "default_image")]
		public RedemptionImage DefaultImage { get; protected set; }

		[JsonProperty(PropertyName = "background_color")]
		public string BackgroundColor { get; protected set; }

		[JsonProperty(PropertyName = "is_enabled")]
		public bool IsEnabled { get; protected set; }

		[JsonProperty(PropertyName = "is_paused")]
		public bool IsPaused { get; protected set; }

		[JsonProperty(PropertyName = "is_in_stock")]
		public bool IsInStock { get; protected set; }

		[JsonProperty(PropertyName = "max_per_stream")]
		public MaxPerStream MaxPerStream { get; protected set; }

		[JsonProperty(PropertyName = "should_redemptions_skip_request_queue")]
		public bool ShouldRedemptionsSkipRequestQueue { get; protected set; }

		[JsonProperty(PropertyName = "template_id")]
		public string TemplateId { get; protected set; }

		[JsonProperty(PropertyName = "updated_for_indicator_at")]
		public DateTime UpdatedForIndicatorAt { get; protected set; }

		[JsonProperty(PropertyName = "max_per_user_per_stream")]
		public MaxPerUserPerStream MaxPerUserPerStream { get; protected set; }

		[JsonProperty(PropertyName = "global_cooldown")]
		public GlobalCooldown GlobalCooldown { get; protected set; }

		[JsonProperty(PropertyName = "cooldown_expires_at")]
		public DateTime? CooldownExpiresAt { get; protected set; }
	}
	public class RewardRedeemed : ChannelPointsData
	{
		[JsonProperty(PropertyName = "timestamp")]
		public DateTime Timestamp { get; protected set; }

		[JsonProperty(PropertyName = "redemption")]
		public Redemption Redemption { get; protected set; }
	}
}
namespace TwitchLib.PubSub.Models.Responses.Messages.HypeTrain
{
	public class HypeTrainEvent : MessageData
	{
		public HypeTrainEventType Type { get; protected set; }

		public HypeTrainEventData Data { get; protected set; }

		public HypeTrainEvent(string jsonStr)
		{
			JToken val = (JToken)(object)JObject.Parse(jsonStr);
			string text = ((object)val.SelectToken("type")).ToString();
			string text2 = text;
			if (!(text2 == "hype-train-progression"))
			{
				if (text2 == "hype-train-level-up")
				{
					Type = HypeTrainEventType.LevelUp;
					Data = val[(object)"data"].ToObject<HypeTrainLevelUp>();
				}
			}
			else
			{
				Type = HypeTrainEventType.Progression;
				Data = val[(object)"data"].ToObject<HypeTrainProgression>();
			}
		}
	}
	public abstract class HypeTrainEventData
	{
	}
	public class HypeTrainLevelUp : HypeTrainEventData
	{
		[JsonProperty(PropertyName = "time_to_expire")]
		public long TimeToExpire { get; protected set; }

		[JsonProperty(PropertyName = "progress")]
		public Progress Progress { get; protected set; }
	}
	public class HypeTrainProgression : HypeTrainEventData
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId { get; protected set; }

		[JsonProperty(PropertyName = "sequence_id")]
		public int SequenceId { get; protected set; }

		[JsonProperty(PropertyName = "action")]
		public string Action { get; protected set; }

		[JsonProperty(PropertyName = "source")]
		public string Source { get; protected set; }

		[JsonProperty(PropertyName = "quantity")]
		public int Quantity { get; protected set; }

		[JsonProperty(PropertyName = "progress")]
		public Progress Progress { get; protected set; }
	}
	public class Level
	{
		[JsonProperty(PropertyName = "value")]
		public int Value { get; protected set; }

		[JsonProperty(PropertyName = "goal")]
		public int Goal { get; protected set; }

		[JsonProperty(PropertyName = "rewards")]
		public Reward[] Rewards { get; protected set; }
	}
	public class Progress
	{
		[JsonProperty(PropertyName = "level")]
		public Level Level { get; protected set; }

		[JsonProperty(PropertyName = "value")]
		public int Value { get; protected set; }

		[JsonProperty(PropertyName = "goal")]
		public int Goal { get; protected set; }

		[JsonProperty(PropertyName = "total")]
		public int Total { get; protected set; }

		[JsonProperty(PropertyName = "remaining_seconds")]
		public int RemainingSeconds { get; protected set; }
	}
	public class Reward
	{
		[JsonProperty(PropertyName = "id")]
		public string Id { get; protected set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; protected set; }

		[JsonProperty(PropertyName = "group_id")]
		public string GroupId { get; protected set; }

		[JsonProperty(PropertyName = "reward_level")]
		public int RewardLevel { get; protected set; }
	}
}
namespace TwitchLib.PubSub.Models.Responses.Messages.AutomodCaughtMessage
{
	public class Automod
	{
		[JsonProperty(PropertyName = "topics")]
		public Dictionary<string, int> Topics;
	}
	public class AutomodCaughtMessage : AutomodQueueData
	{
		[JsonProperty(PropertyName = "content_classification")]
		public ContentClassification ContentClassification { get; protected set; }

		[JsonProperty(PropertyName = "message")]
		public Message Message { get; protected set; }

		[JsonProperty(PropertyName = "reason_code")]
		public string ReasonCode { get; protected set; }

		[JsonProperty(PropertyName = "resolver_id")]
		public string ResolverId { get; protected set; }

		[JsonProperty(PropertyName = "resolver_login")]
		public string ResolverLogin { get; protected set; }

		[JsonProperty(PropertyName = "status")]
		public string Status { get; protected set; }
	}
	public class Content
	{
		[JsonProperty(PropertyName = "text")]
		public string Text;

		[JsonProperty(PropertyName = "fragments")]
		public Fragment[] Fragments;
	}
	public class ContentClassification
	{
		public string Category;

		public int Level;
	}
	public class Fragment
	{
		[JsonProperty(PropertyName = "text")]
		public string Text;

		[JsonProperty(PropertyName = "automod")]
		public Automod Automod;
	}
	public class Message
	{
		[JsonProperty(PropertyName = "content")]
		public Content Content;

		[JsonProperty(PropertyName = "id")]
		public string Id;

		[JsonProperty(PropertyName = "sender")]
		public Sender Sender;

		[JsonProperty(PropertyName = "sent_at")]
		public DateTime SentAt;
	}
	public class Sender
	{
		[JsonProperty(PropertyName = "user_id")]
		public string UserId;

		[JsonProperty(PropertyName = "login")]
		public string Login;

		[JsonProperty(PropertyName = "display_name")]
		public string DisplayName;
	}
}
namespace TwitchLib.PubSub.Interfaces
{
	public interface ITwitchPubSub
	{
		event EventHandler<OnAutomodCaughtUserMessage> OnAutomodCaughtUserMessage;

		event EventHandler<OnAutomodCaughtMessageArgs> OnAutomodCaughtMessage;

		event EventHandler<OnBanArgs> OnBan;

		event EventHandler<OnBitsReceivedV2Args> OnBitsReceivedV2;

		event EventHandler<OnChannelBitsBadgeUnlockArgs> OnChannelBitsBadgeUnlock;

		event EventHandler<OnChannelExtensionBroadcastArgs> OnChannelExtensionBroadcast;

		event EventHandler<OnChannelSubscriptionArgs> OnChannelSubscription;

		event EventHandler<OnClearArgs> OnClear;

		event EventHandler<OnEmoteOnlyArgs> OnEmoteOnly;

		event EventHandler<OnEmoteOnlyOffArgs> OnEmoteOnlyOff;

		event EventHandler<OnHostArgs> OnHost;

		event EventHandler<OnMessageDeletedArgs> OnMessageDeleted;

		event EventHandler<OnListenResponseArgs> OnListenResponse;

		event EventHandler<OnLowTrustUsersArgs> OnLowTrustUsers;

		event EventHandler OnPubSubServiceClosed;

		event EventHandler OnPubSubServiceConnected;

		event EventHandler<OnPubSubServiceErrorArgs> OnPubSubServiceError;

		event EventHandler<OnR9kBetaArgs> OnR9kBeta;

		event EventHandler<OnR9kBetaOffArgs> OnR9kBetaOff;

		event EventHandler<OnRaidCancelArgs> OnRaidCancel;

		event EventHandler<OnStreamDownArgs> OnStreamDown;

		event EventHandler<OnStreamUpArgs> OnStreamUp;

		event EventHandler<OnSubscribersOnlyArgs> OnSubscribersOnly;

		event EventHandler<OnSubscribersOnlyOffArgs> OnSubscribersOnlyOff;

		event EventHandler<OnTimeoutArgs> OnTimeout;

		event EventHandler<OnUnbanArgs> OnUnban;

		event EventHandler<OnUntimeoutArgs> OnUntimeout;

		event EventHandler<OnViewCountArgs> OnViewCount;

		event EventHandler<OnWhisperArgs> OnWhisper;

		[Obsolete("This event fires on an undocumented/retired/obsolete topic.", false)]
		event EventHandler<OnCustomRewardCreatedArgs> OnCustomRewardCreated;

		[Obsolete("This event fires on an undocumented/retired/obsolete topic.", false)]
		event EventHandler<OnCustomRewardUpdatedArgs> OnCustomRewardUpdated;

		[Obsolete("This event fires on an undocumented/retired/obsolete topic.", false)]
		event EventHandler<OnCustomRewardDeletedArgs> OnCustomRewardDeleted;

		[Obsolete("This event fires on an undocumented/retired/obsolete topic.", false)]
		event EventHandler<OnRewardRedeemedArgs> OnRewardRedeemed;

		event EventHandler<OnChannelPointsRewardRedeemedArgs> OnChannelPointsRewardRedeemed;

		event EventHandler<OnLeaderboardEventArgs> OnLeaderboardSubs;

		event EventHandler<OnLeaderboardEventArgs> OnLeaderboardBits;

		event EventHandler<OnRaidUpdateArgs> OnRaidUpdate;

		event EventHandler<OnRaidUpdateV2Args> OnRaidUpdateV2;

		event EventHandler<OnRaidGoArgs> OnRaidGo;

		event EventHandler<OnLogArgs> OnLog;

		event EventHandler<OnCommercialArgs> OnCommercial;

		event EventHandler<OnPredictionArgs> OnPrediction;

		void Connect();

		Task ConnectAsync();

		void Disconnect();

		Task DisconnectAsync();

		void ListenToBitsEventsV2(string channelTwitchId);

		void ListenToChannelExtensionBroadcast(string channelId, string extensionId);

		void ListenToChatModeratorActions(string myTwitchId, string channelTwitchId);

		void ListenToSubscriptions(string channelId);

		void ListenToVideoPlayback(string channelName);

		void ListenToWhispers(string channelTwitchId);

		[Obsolete("This method listens to an undocumented/retired/obsolete topic. Consider using ListenToChannelPoints()", false)]
		void ListenToRewards(string channelTwitchId);

		void ListenToChannelPoints(string channelTwitchId);

		void ListenToLeaderboards(string channelTwitchId);

		void ListenToRaid(string channelTwitchId);

		void ListenToPredictions(string channelTwitchId);

		void ListenToUserModerationNotifications(string myTwitchId, string channelTwitchId);

		void ListenToAutomodQueue(string userTwitchId, string channelTwitchId);

		void ListenToChannelBitsBadgeUnlocks(string channelTwitchId);

		void ListenToLowTrustUsers(string channelTwitchId, string suspiciousUser);

		void SendTopics(string oauth = null, bool unlisten = false);

		Task SendTopicsAsync(string oauth = null, bool unlisten = false);

		void TestMessageParser(string testJsonString);
	}
}
namespace TwitchLib.PubSub.Extensions
{
	public static class JSONObjectExtensions
	{
		public static bool IsEmpty(this JToken token)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Invalid comparison between Unknown and I4
			return token == null || ((int)token.Type == 2 && !token.HasValues) || ((int)token.Type == 1 && !token.HasValues) || ((int)token.Type == 8 && ((object)token).ToString() == string.Empty) || (int)token.Type == 10;
		}
	}
	internal static class LoggingExtesions
	{
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		private static readonly Action<ILogger, Exception, Exception?> __LogOnErrorCallback = LoggerMessage.Define<Exception>(LogLevel.Error, new EventId(1347194570, "LogOnError"), "OnError in PubSub Websocket connection occured! Exception: {ex}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		private static readonly Action<ILogger, string, Exception?> __LogReceivednMessageCallback = LoggerMessage.Define<string>(LogLevel.Debug, new EventId(1510361857, "LogReceivednMessage"), "Received Websocket OnMessage: {message}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		private static readonly Action<ILogger, Exception?> __LogConnectionClosedCallback = LoggerMessage.Define(LogLevel.Warning, new EventId(1672666189, "LogConnectionClosed"), "PubSub Websocket connection closed", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		private static readonly Action<ILogger, Exception?> __LogConnectionEstablishedCallback = LoggerMessage.Define(LogLevel.Information, new EventId(185409707, "LogConnectionEstablished"), "PubSub Websocket connection established", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		private static readonly Action<ILogger, string, Exception?> __LogUnaccountedForCallback = LoggerMessage.Define<string>(LogLevel.Information, new EventId(1006327295, "LogUnaccountedFor"), "[TwitchPubSub] {message}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[LoggerMessage(LogLevel.Error, "OnError in PubSub Websocket connection occured! Exception: {ex}")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		public static void LogOnError(this ILogger<TwitchPubSub> logger, Exception ex)
		{
			if (logger.IsEnabled(LogLevel.Error))
			{
				__LogOnErrorCallback(logger, ex, ex);
			}
		}

		[LoggerMessage(LogLevel.Debug, "Received Websocket OnMessage: {message}")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		public static void LogReceivednMessage(this ILogger<TwitchPubSub> logger, string message)
		{
			if (logger.IsEnabled(LogLevel.Debug))
			{
				__LogReceivednMessageCallback(logger, message, null);
			}
		}

		[LoggerMessage(LogLevel.Warning, "PubSub Websocket connection closed")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		public static void LogConnectionClosed(this ILogger<TwitchPubSub> logger)
		{
			if (logger.IsEnabled(LogLevel.Warning))
			{
				__LogConnectionClosedCallback(logger, null);
			}
		}

		[LoggerMessage(LogLevel.Information, "PubSub Websocket connection established")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		public static void LogConnectionEstablished(this ILogger<TwitchPubSub> logger)
		{
			if (logger.IsEnabled(LogLevel.Information))
			{
				__LogConnectionEstablishedCallback(logger, null);
			}
		}

		[LoggerMessage(LogLevel.Information, "[TwitchPubSub] {message}")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.9.3103")]
		public static void LogUnaccountedFor(this ILogger<TwitchPubSub> logger, string message)
		{
			if (logger.IsEnabled(LogLevel.Information))
			{
				__LogUnaccountedForCallback(logger, message, null);
			}
		}
	}
}
namespace TwitchLib.PubSub.Events
{
	public class OnAutomodCaughtMessageArgs
	{
		public TwitchLib.PubSub.Models.Responses.Messages.AutomodCaughtMessage.AutomodCaughtMessage AutomodCaughtMessage;

		public string ChannelId;
	}
	public class OnAutomodCaughtUserMessage
	{
		public TwitchLib.PubSub.Models.Responses.Messages.UserModerationNotificationsTypes.AutomodCaughtMessage AutomodCaughtMessage;

		public string ChannelId;

		public string UserId;
	}
	public class OnBanArgs : EventArgs
	{
		public string BannedUserId;

		public string BannedUser;

		public string BanReason;

		public string BannedBy;

		public string BannedByUserId;

		public string ChannelId;
	}
	public class OnBitsReceivedArgs : EventArgs
	{
		public string Username;

		public string ChannelName;

		public string UserId;

		public string ChannelId;

		public string Time;

		public string ChatMessage;

		public int BitsUsed;

		public int TotalBitsUsed;

		public string Context;
	}
	public class OnBitsReceivedV2Args
	{
		public string UserName { get; internal set; }

		public string ChannelName { get; internal set; }

		public string UserId { get; internal set; }

		public string ChannelId { get; internal set; }

		public DateTime Time { get; internal set; }

		public string ChatMessage { get; internal set; }

		public int BitsUsed { get; internal set; }

		public int TotalBitsUsed { get; internal set; }

		public bool IsAnonymous { get; internal set; }

		public string Context { get; internal set; }
	}
	public class OnChannelBitsBadgeUnlockArgs : EventArgs
	{
		public BitsBadgeNotificationMessage BitsBadgeUnlocks;

		public string ChannelId;
	}
	public class OnChannelExtensionBroadcastArgs : EventArgs
	{
		public List<string> Messages;

		public string ChannelId;
	}
	public class OnChannelPointsRewardRedeemedArgs : EventArgs
	{
		public string ChannelId { get; internal set; }

		public RewardRedeemed RewardRedeemed { get; internal set; }
	}
	public class OnChannelSubscriptionArgs : EventArgs
	{
		public ChannelSubscription Subscription;

		public string ChannelId;
	}
	public class OnClearArgs : EventArgs
	{
		public string Moderator;

		public string ChannelId;
	}
	public class OnCommercialArgs : EventArgs
	{
		public int Length;

		public string ServerTime;

		public string ChannelId;
	}
	public class OnCustomRewardCreatedArgs : EventArgs
	{
		public DateTime TimeStamp;

		public string ChannelId;

		public Guid RewardId;

		public string RewardTitle;

		public string RewardPrompt;

		public int RewardCost;
	}
	public class OnCustomRewardDeletedArgs
	{
		public DateTime TimeStamp;

		public string ChannelId;

		public Guid RewardId;

		public string RewardTitle;

		public string RewardPrompt;
	}
	public class OnCustomRewardUpdatedArgs : EventArgs
	{
		public DateTime TimeStamp;

		public string ChannelId;

		public Guid RewardId;

		public string RewardTitle;

		public string RewardPrompt;

		public int RewardCost;
	}
	public class OnEmoteOnlyArgs : EventArgs
	{
		public string Moderator;

		public string ChannelId;
	}
	public class OnEmoteOnlyOffArgs : EventArgs
	{
		public string Moderator;

		public string ChannelId;
	}
	public class OnHostArgs : EventArgs
	{
		public string Moderator;

		public string HostedChannel;

		public string ChannelId;
	}
	public class OnHypeTrainLevelUp
	{
		public HypeTrainLevelUp LevelUp;

		public string ChannelId;
	}
	public class OnHypeTrainProgressionArgs
	{
		public HypeTrainProgression Progression;

		public string ChannelId;
	}
	public class OnLeaderboardEventArgs : EventArgs
	{
		public string ChannelId;

		public List<LeaderBoard> TopList;
	}
	public class OnListenResponseArgs : EventArgs
	{
		public string Topic;

		public Response Response;

		public bool Successful;

		public string ChannelId;
	}
	public class OnLogArgs : EventArgs
	{
		public string Data;
	}
	public class OnLowTrustUsersArgs : EventArgs
	{
		public LowTrustUsers LowTrustUsers;

		public string ChannelId;
	}
	public class OnMessageDeletedArgs : EventArgs
	{
		public string TargetUser;

		public string TargetUserId;

		public string DeletedBy;

		public string DeletedByUserId;

		public string Message;

		public string MessageId;

		public string ChannelId;
	}
	public class OnPredictionArgs : EventArgs
	{
		public PredictionType Type;

		public Guid Id;

		public string ChannelId;

		public DateTime? CreatedAt;

		public DateTime? LockedAt;

		public DateTime? EndedAt;

		public ICollection<Outcome> Outcomes;

		public PredictionStatus Status;

		public string Title;

		public Guid? WinningOutcomeId;

		public int PredictionTime;
	}
	public class OnPubSubServiceErrorArgs : EventArgs
	{
		public Exception Exception;
	}
	public class OnR9kBetaArgs : EventArgs
	{
		public string Moderator;

		public string ChannelId;
	}
	public class OnR9kBetaOffArgs : EventArgs
	{
		public string Moderator;

		public string ChannelId;
	}
	public class OnRaidCancelArgs : EventArgs
	{
		public string ChannelId;

		public Guid Id;

		public string TargetChannelId;

		public string TargetLogin;

		public string TargetDisplayName;

		public string TargetProfileImage;

		public int ViewerCount;
	}
	public class OnRaidGoArgs : EventArgs
	{
		public string ChannelId;

		public Guid Id;

		public string TargetChannelId;

		public string TargetLogin;

		public string TargetDisplayName;

		public string TargetProfileImage;

		public int ViewerCount;
	}
	public class OnRaidUpdateArgs : EventArgs
	{
		public string ChannelId;

		public Guid Id;

		public string TargetChannelId;

		public DateTime AnnounceTime;

		public DateTime RaidTime;

		public int RemainingDurationSeconds;

		public int ViewerCount;
	}
	public class OnRaidUpdateV2Args : EventArgs
	{
		public string ChannelId;

		public Guid Id;

		public string TargetChannelId;

		public string TargetLogin;

		public string TargetDisplayName;

		public string TargetProfileImage;

		public int ViewerCount;
	}
	public class OnRewardRedeemedArgs : EventArgs
	{
		public DateTime TimeStamp;

		public string ChannelId;

		public string Login;

		public string DisplayName;

		public string Message;

		public Guid RewardId;

		public string RewardTitle;

		public string RewardPrompt;

		public int RewardCost;

		public string Status;

		public Guid RedemptionId;
	}
	public class OnStreamDownArgs : EventArgs
	{
		public string ServerTime;

		public string ChannelId;
	}
	public class OnStreamUpArgs : EventArgs
	{
		public string ServerTime;

		public int PlayDelay;

		public string ChannelId;
	}
	public class OnSubscribersOnlyArgs : EventArgs
	{
		public string Moderator;

		public string ChannelId;
	}
	public class OnSubscribersOnlyOffArgs : EventArgs
	{
		public string Moderator;

		public string ChannelId;
	}
	public class OnTimeoutArgs : EventArgs
	{
		public string TimedoutUserId;

		public string TimedoutUser;

		public TimeSpan TimeoutDuration;

		public string TimeoutReason;

		public string TimedoutBy;

		public string TimedoutById;

		public string ChannelId;
	}
	public class OnUnbanArgs : EventArgs
	{
		public string UnbannedUser;

		public string UnbannedUserId;

		public string UnbannedBy;

		public string UnbannedByUserId;

		public string ChannelId;
	}
	public class OnUntimeoutArgs : EventArgs
	{
		public string UntimeoutedUser;

		public string UntimeoutedUserId;

		public string UntimeoutedBy;

		public string UntimeoutedByUserId;

		public string ChannelId;
	}
	public class OnViewCountArgs : EventArgs
	{
		public string ServerTime;

		public int Viewers;

		public string ChannelId;
	}
	public class OnWhisperArgs : EventArgs
	{
		public Whisper Whisper;

		public string ChannelId;
	}
}
namespace TwitchLib.PubSub.Enums
{
	public enum AutomodQueueType
	{
		CaughtMessage,
		Unknown
	}
	public enum ChannelPointsChannelType
	{
		RewardRedeemed,
		Unknown
	}
	public enum CommunityPointsChannelType
	{
		RewardRedeemed,
		CustomRewardUpdated,
		CustomRewardCreated,
		CustomRewardDeleted
	}
	public enum HypeTrainEventType
	{
		Progression,
		LevelUp
	}
	public enum LeaderBoardType
	{
		BitsUsageByChannel,
		SubGiftSent
	}
	public enum PredictionStatus
	{
		Canceled = -4,
		CancelPending,
		Resolved,
		ResolvePending,
		Locked,
		Active
	}
	public enum PredictionType
	{
		EventCreated,
		EventUpdated
	}
	public enum PubSubRequestType
	{
		ListenToTopic
	}
	public enum RaidType
	{
		RaidUpdate,
		RaidUpdateV2,
		RaidGo,
		RaidCancel
	}
	public enum SubscriptionPlan
	{
		NotSet,
		Prime,
		Tier1,
		Tier2,
		Tier3
	}
	public enum UserModerationNotificationsType
	{
		AutomodCaughtMessage,
		Unknown
	}
	public enum VideoPlaybackType
	{
		StreamUp,
		StreamDown,
		ViewCount,
		Commercial
	}
	public enum WhisperType
	{
		WhisperReceived,
		Thread,
		Unknown
	}
}
namespace TwitchLib.PubSub.Common
{
	public static class Helpers
	{
		public static DateTime DateTimeStringToObject(string dateTime)
		{
			return (dateTime == null) ? default(DateTime) : Convert.ToDateTime(dateTime);
		}

		public static string Base64Encode(string plainText)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(plainText);
			return Convert.ToBase64String(bytes);
		}
	}
}

TwitchLib.Unity.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Drawing;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using TwitchLib.Api;
using TwitchLib.Api.Core.Interfaces;
using TwitchLib.Api.Interfaces;
using TwitchLib.Api.Services;
using TwitchLib.Api.Services.Events;
using TwitchLib.Api.Services.Events.FollowerService;
using TwitchLib.Api.Services.Events.LiveStreamMonitor;
using TwitchLib.Client;
using TwitchLib.Client.Enums;
using TwitchLib.Client.Events;
using TwitchLib.Client.Exceptions;
using TwitchLib.Client.Interfaces;
using TwitchLib.Client.Models.Interfaces;
using TwitchLib.Communication.Events;
using TwitchLib.Communication.Interfaces;
using TwitchLib.PubSub;
using TwitchLib.PubSub.Events;
using TwitchLib.PubSub.Interfaces;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("TwitchLib")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright 2021")]
[assembly: AssemblyDescription("Unity wrapper system for TwitchLib")]
[assembly: AssemblyFileVersion("1.0.4.0")]
[assembly: AssemblyInformationalVersion("1.0.4+8ed36f4eec943da62d60f8eec7dbc42a0fa8271b")]
[assembly: AssemblyProduct("TwitchLib.Unity")]
[assembly: AssemblyTitle("TwitchLib.Unity")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.Unity")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("1.0.4.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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;
		}
	}
}
namespace TwitchLib.Unity
{
	public class Api : TwitchAPI
	{
		public void Invoke<T>(Task<T> func, Action<T> action)
		{
			if (func == null)
			{
				throw new ArgumentNullException("func");
			}
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}
			InvokeInternal(func, action);
		}

		public void Invoke(Task func, Action action)
		{
			if (func == null)
			{
				throw new ArgumentNullException("func");
			}
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}
			InvokeInternal(func, action);
		}

		public IEnumerator InvokeAsync<T>(Task<T> func, Action<T> action)
		{
			if (func == null)
			{
				throw new ArgumentNullException("func");
			}
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}
			bool requestCompleted = false;
			InvokeInternal(func, delegate(T result)
			{
				action(result);
				requestCompleted = true;
			});
			yield return (object)new WaitUntil((Func<bool>)(() => requestCompleted));
		}

		public IEnumerator InvokeAsync(Task func)
		{
			if (func == null)
			{
				throw new ArgumentNullException("func");
			}
			bool requestCompleted = false;
			InvokeInternal(func, delegate
			{
				requestCompleted = true;
			});
			yield return (object)new WaitUntil((Func<bool>)(() => requestCompleted));
		}

		private void InvokeInternal(Task func, Action action)
		{
			ThreadDispatcher.EnsureCreated("InvokeInternal");
			func.ContinueWith(delegate(Task x)
			{
				x.Wait();
				ThreadDispatcher.Enqueue(delegate
				{
					action();
				});
			});
		}

		private void InvokeInternal<T>(Task<T> func, Action<T> action)
		{
			ThreadDispatcher.EnsureCreated("InvokeInternal");
			func.ContinueWith(delegate(Task<T> x)
			{
				T value = x.Result;
				ThreadDispatcher.Enqueue(delegate
				{
					action(value);
				});
			});
		}

		public Api()
			: base((ILoggerFactory)null, (IRateLimiter)null, (IApiSettings)null, (IHttpCallHandler)null)
		{
		}
	}
	public class CertificateValidationFix : MonoBehaviour
	{
		[RuntimeInitializeOnLoadMethod(/*Could not decode attribute arguments.*/)]
		private static void FixCertificateValidation()
		{
			ServicePointManager.ServerCertificateValidationCallback = CertificateValidationMonoFix;
		}

		private static bool CertificateValidationMonoFix(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
		{
			bool result = true;
			if (sslPolicyErrors == SslPolicyErrors.None)
			{
				return true;
			}
			X509ChainStatus[] chainStatus = chain.ChainStatus;
			foreach (X509ChainStatus x509ChainStatus in chainStatus)
			{
				if (x509ChainStatus.Status != X509ChainStatusFlags.RevocationStatusUnknown)
				{
					chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
					chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
					chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
					chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
					if (!chain.Build((X509Certificate2)certificate))
					{
						result = false;
					}
				}
			}
			return result;
		}
	}
	public class Client : TwitchClient, ITwitchClient
	{
		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnConnectedEventArgs> m_OnConnected;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnConnectedEventArgs> m_OnReconnected;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnJoinedChannelArgs> m_OnJoinedChannel;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnIncorrectLoginArgs> m_OnIncorrectLogin;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnChannelStateChangedArgs> m_OnChannelStateChanged;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserStateChangedArgs> m_OnUserStateChanged;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnMessageReceivedArgs> m_OnMessageReceived;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnWhisperReceivedArgs> m_OnWhisperReceived;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnMessageSentArgs> m_OnMessageSent;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnChatCommandReceivedArgs> m_OnChatCommandReceived;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnWhisperCommandReceivedArgs> m_OnWhisperCommandReceived;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserJoinedArgs> m_OnUserJoined;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnNewSubscriberArgs> m_OnNewSubscriber;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnReSubscriberArgs> m_OnReSubscriber;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnPrimePaidSubscriberArgs> m_OnPrimePaidSubscriber;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> m_OnContinuedGiftedSubscription;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnExistingUsersDetectedArgs> m_OnExistingUsersDetected;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserLeftArgs> m_OnUserLeft;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnDisconnectedArgs> m_OnDisconnected;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnConnectionErrorArgs> m_OnConnectionError;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnChatClearedArgs> m_OnChatCleared;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserTimedoutArgs> m_OnUserTimedout;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnLeftChannelArgs> m_OnLeftChannel;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserBannedArgs> m_OnUserBanned;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnSendReceiveDataArgs> m_OnSendReceiveData;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnRaidNotificationArgs> m_OnRaidNotification;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnGiftedSubscriptionArgs> m_OnGiftedSubscription;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnSelfRaidError;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnNoPermissionError;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnRaidedChannelIsMatureAudience;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> m_OnFailureToReceiveJoinConfirmation;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUnaccountedForArgs> m_OnUnaccountedFor;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnMessageClearedArgs> m_OnMessageCleared;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnCommunitySubscriptionArgs> m_OnCommunitySubscription;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnErrorEventArgs> m_OnError;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnAnnouncementArgs> m_OnAnnouncement;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnMessageThrottledArgs> m_OnMessageThrottled;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnRequiresVerifiedPhoneNumber;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnFollowersOnly;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnSubsOnly;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnEmoteOnly;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnSuspended;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnBanned;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnSlowMode;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<NoticeEventArgs> m_OnR9kMode;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUserIntroArgs> m_OnUserIntro;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> m_OnAnonGiftPaidUpgrade;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnUnraidNotificationArgs> m_OnUnraidNotification;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnRitualArgs> m_OnRitual;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnBitsBadgeTierArgs> m_OnBitsBadgeTier;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnCommunityPayForwardArgs> m_OnCommunityPayForward;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AsyncEventHandler<OnStandardPayForwardArgs> m_OnStandardPayForward;

		public event AsyncEventHandler<OnConnectedEventArgs> OnConnected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnConnectedEventArgs> val = this.m_OnConnected;
				AsyncEventHandler<OnConnectedEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectedEventArgs> value2 = (AsyncEventHandler<OnConnectedEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnConnectedEventArgs> val = this.m_OnConnected;
				AsyncEventHandler<OnConnectedEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectedEventArgs> value2 = (AsyncEventHandler<OnConnectedEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnected, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnConnectedEventArgs> OnReconnected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnConnectedEventArgs> val = this.m_OnReconnected;
				AsyncEventHandler<OnConnectedEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectedEventArgs> value2 = (AsyncEventHandler<OnConnectedEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnReconnected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnConnectedEventArgs> val = this.m_OnReconnected;
				AsyncEventHandler<OnConnectedEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectedEventArgs> value2 = (AsyncEventHandler<OnConnectedEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnReconnected, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnJoinedChannelArgs> OnJoinedChannel
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnJoinedChannelArgs> val = this.m_OnJoinedChannel;
				AsyncEventHandler<OnJoinedChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnJoinedChannelArgs> value2 = (AsyncEventHandler<OnJoinedChannelArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnJoinedChannel, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnJoinedChannelArgs> val = this.m_OnJoinedChannel;
				AsyncEventHandler<OnJoinedChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnJoinedChannelArgs> value2 = (AsyncEventHandler<OnJoinedChannelArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnJoinedChannel, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnIncorrectLoginArgs> OnIncorrectLogin
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnIncorrectLoginArgs> val = this.m_OnIncorrectLogin;
				AsyncEventHandler<OnIncorrectLoginArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnIncorrectLoginArgs> value2 = (AsyncEventHandler<OnIncorrectLoginArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnIncorrectLogin, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnIncorrectLoginArgs> val = this.m_OnIncorrectLogin;
				AsyncEventHandler<OnIncorrectLoginArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnIncorrectLoginArgs> value2 = (AsyncEventHandler<OnIncorrectLoginArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnIncorrectLogin, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnChannelStateChangedArgs> OnChannelStateChanged
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnChannelStateChangedArgs> val = this.m_OnChannelStateChanged;
				AsyncEventHandler<OnChannelStateChangedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChannelStateChangedArgs> value2 = (AsyncEventHandler<OnChannelStateChangedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChannelStateChanged, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnChannelStateChangedArgs> val = this.m_OnChannelStateChanged;
				AsyncEventHandler<OnChannelStateChangedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChannelStateChangedArgs> value2 = (AsyncEventHandler<OnChannelStateChangedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChannelStateChanged, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserStateChangedArgs> OnUserStateChanged
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserStateChangedArgs> val = this.m_OnUserStateChanged;
				AsyncEventHandler<OnUserStateChangedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserStateChangedArgs> value2 = (AsyncEventHandler<OnUserStateChangedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserStateChanged, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserStateChangedArgs> val = this.m_OnUserStateChanged;
				AsyncEventHandler<OnUserStateChangedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserStateChangedArgs> value2 = (AsyncEventHandler<OnUserStateChangedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserStateChanged, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnMessageReceivedArgs> OnMessageReceived
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnMessageReceivedArgs> val = this.m_OnMessageReceived;
				AsyncEventHandler<OnMessageReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageReceivedArgs> value2 = (AsyncEventHandler<OnMessageReceivedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageReceived, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnMessageReceivedArgs> val = this.m_OnMessageReceived;
				AsyncEventHandler<OnMessageReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageReceivedArgs> value2 = (AsyncEventHandler<OnMessageReceivedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageReceived, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnWhisperReceivedArgs> OnWhisperReceived
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnWhisperReceivedArgs> val = this.m_OnWhisperReceived;
				AsyncEventHandler<OnWhisperReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnWhisperReceivedArgs> value2 = (AsyncEventHandler<OnWhisperReceivedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnWhisperReceived, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnWhisperReceivedArgs> val = this.m_OnWhisperReceived;
				AsyncEventHandler<OnWhisperReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnWhisperReceivedArgs> value2 = (AsyncEventHandler<OnWhisperReceivedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnWhisperReceived, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnMessageSentArgs> OnMessageSent
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnMessageSentArgs> val = this.m_OnMessageSent;
				AsyncEventHandler<OnMessageSentArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageSentArgs> value2 = (AsyncEventHandler<OnMessageSentArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageSent, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnMessageSentArgs> val = this.m_OnMessageSent;
				AsyncEventHandler<OnMessageSentArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageSentArgs> value2 = (AsyncEventHandler<OnMessageSentArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageSent, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnChatCommandReceivedArgs> OnChatCommandReceived
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnChatCommandReceivedArgs> val = this.m_OnChatCommandReceived;
				AsyncEventHandler<OnChatCommandReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChatCommandReceivedArgs> value2 = (AsyncEventHandler<OnChatCommandReceivedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChatCommandReceived, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnChatCommandReceivedArgs> val = this.m_OnChatCommandReceived;
				AsyncEventHandler<OnChatCommandReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChatCommandReceivedArgs> value2 = (AsyncEventHandler<OnChatCommandReceivedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChatCommandReceived, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnWhisperCommandReceivedArgs> OnWhisperCommandReceived
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnWhisperCommandReceivedArgs> val = this.m_OnWhisperCommandReceived;
				AsyncEventHandler<OnWhisperCommandReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnWhisperCommandReceivedArgs> value2 = (AsyncEventHandler<OnWhisperCommandReceivedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnWhisperCommandReceived, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnWhisperCommandReceivedArgs> val = this.m_OnWhisperCommandReceived;
				AsyncEventHandler<OnWhisperCommandReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnWhisperCommandReceivedArgs> value2 = (AsyncEventHandler<OnWhisperCommandReceivedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnWhisperCommandReceived, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserJoinedArgs> OnUserJoined
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserJoinedArgs> val = this.m_OnUserJoined;
				AsyncEventHandler<OnUserJoinedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserJoinedArgs> value2 = (AsyncEventHandler<OnUserJoinedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserJoined, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserJoinedArgs> val = this.m_OnUserJoined;
				AsyncEventHandler<OnUserJoinedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserJoinedArgs> value2 = (AsyncEventHandler<OnUserJoinedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserJoined, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnNewSubscriberArgs> OnNewSubscriber
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnNewSubscriberArgs> val = this.m_OnNewSubscriber;
				AsyncEventHandler<OnNewSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnNewSubscriberArgs> value2 = (AsyncEventHandler<OnNewSubscriberArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnNewSubscriber, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnNewSubscriberArgs> val = this.m_OnNewSubscriber;
				AsyncEventHandler<OnNewSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnNewSubscriberArgs> value2 = (AsyncEventHandler<OnNewSubscriberArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnNewSubscriber, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnReSubscriberArgs> OnReSubscriber
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnReSubscriberArgs> val = this.m_OnReSubscriber;
				AsyncEventHandler<OnReSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnReSubscriberArgs> value2 = (AsyncEventHandler<OnReSubscriberArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnReSubscriber, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnReSubscriberArgs> val = this.m_OnReSubscriber;
				AsyncEventHandler<OnReSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnReSubscriberArgs> value2 = (AsyncEventHandler<OnReSubscriberArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnReSubscriber, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnPrimePaidSubscriberArgs> OnPrimePaidSubscriber
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnPrimePaidSubscriberArgs> val = this.m_OnPrimePaidSubscriber;
				AsyncEventHandler<OnPrimePaidSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnPrimePaidSubscriberArgs> value2 = (AsyncEventHandler<OnPrimePaidSubscriberArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnPrimePaidSubscriber, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnPrimePaidSubscriberArgs> val = this.m_OnPrimePaidSubscriber;
				AsyncEventHandler<OnPrimePaidSubscriberArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnPrimePaidSubscriberArgs> value2 = (AsyncEventHandler<OnPrimePaidSubscriberArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnPrimePaidSubscriber, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> OnContinuedGiftedSubscription
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> val = this.m_OnContinuedGiftedSubscription;
				AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> value2 = (AsyncEventHandler<OnContinuedGiftedSubscriptionArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnContinuedGiftedSubscription, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> val = this.m_OnContinuedGiftedSubscription;
				AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnContinuedGiftedSubscriptionArgs> value2 = (AsyncEventHandler<OnContinuedGiftedSubscriptionArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnContinuedGiftedSubscription, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnExistingUsersDetectedArgs> OnExistingUsersDetected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnExistingUsersDetectedArgs> val = this.m_OnExistingUsersDetected;
				AsyncEventHandler<OnExistingUsersDetectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnExistingUsersDetectedArgs> value2 = (AsyncEventHandler<OnExistingUsersDetectedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnExistingUsersDetected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnExistingUsersDetectedArgs> val = this.m_OnExistingUsersDetected;
				AsyncEventHandler<OnExistingUsersDetectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnExistingUsersDetectedArgs> value2 = (AsyncEventHandler<OnExistingUsersDetectedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnExistingUsersDetected, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserLeftArgs> OnUserLeft
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserLeftArgs> val = this.m_OnUserLeft;
				AsyncEventHandler<OnUserLeftArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserLeftArgs> value2 = (AsyncEventHandler<OnUserLeftArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserLeft, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserLeftArgs> val = this.m_OnUserLeft;
				AsyncEventHandler<OnUserLeftArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserLeftArgs> value2 = (AsyncEventHandler<OnUserLeftArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserLeft, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnDisconnectedArgs> OnDisconnected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnDisconnectedArgs> val = this.m_OnDisconnected;
				AsyncEventHandler<OnDisconnectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnDisconnectedArgs> value2 = (AsyncEventHandler<OnDisconnectedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnDisconnected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnDisconnectedArgs> val = this.m_OnDisconnected;
				AsyncEventHandler<OnDisconnectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnDisconnectedArgs> value2 = (AsyncEventHandler<OnDisconnectedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnDisconnected, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnConnectionErrorArgs> OnConnectionError
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnConnectionErrorArgs> val = this.m_OnConnectionError;
				AsyncEventHandler<OnConnectionErrorArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectionErrorArgs> value2 = (AsyncEventHandler<OnConnectionErrorArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnectionError, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnConnectionErrorArgs> val = this.m_OnConnectionError;
				AsyncEventHandler<OnConnectionErrorArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnConnectionErrorArgs> value2 = (AsyncEventHandler<OnConnectionErrorArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnectionError, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnChatClearedArgs> OnChatCleared
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnChatClearedArgs> val = this.m_OnChatCleared;
				AsyncEventHandler<OnChatClearedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChatClearedArgs> value2 = (AsyncEventHandler<OnChatClearedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChatCleared, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnChatClearedArgs> val = this.m_OnChatCleared;
				AsyncEventHandler<OnChatClearedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnChatClearedArgs> value2 = (AsyncEventHandler<OnChatClearedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnChatCleared, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserTimedoutArgs> OnUserTimedout
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserTimedoutArgs> val = this.m_OnUserTimedout;
				AsyncEventHandler<OnUserTimedoutArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserTimedoutArgs> value2 = (AsyncEventHandler<OnUserTimedoutArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserTimedout, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserTimedoutArgs> val = this.m_OnUserTimedout;
				AsyncEventHandler<OnUserTimedoutArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserTimedoutArgs> value2 = (AsyncEventHandler<OnUserTimedoutArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserTimedout, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnLeftChannelArgs> OnLeftChannel
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnLeftChannelArgs> val = this.m_OnLeftChannel;
				AsyncEventHandler<OnLeftChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnLeftChannelArgs> value2 = (AsyncEventHandler<OnLeftChannelArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnLeftChannel, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnLeftChannelArgs> val = this.m_OnLeftChannel;
				AsyncEventHandler<OnLeftChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnLeftChannelArgs> value2 = (AsyncEventHandler<OnLeftChannelArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnLeftChannel, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserBannedArgs> OnUserBanned
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserBannedArgs> val = this.m_OnUserBanned;
				AsyncEventHandler<OnUserBannedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserBannedArgs> value2 = (AsyncEventHandler<OnUserBannedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserBanned, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserBannedArgs> val = this.m_OnUserBanned;
				AsyncEventHandler<OnUserBannedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserBannedArgs> value2 = (AsyncEventHandler<OnUserBannedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserBanned, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnSendReceiveDataArgs> OnSendReceiveData
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnSendReceiveDataArgs> val = this.m_OnSendReceiveData;
				AsyncEventHandler<OnSendReceiveDataArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnSendReceiveDataArgs> value2 = (AsyncEventHandler<OnSendReceiveDataArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSendReceiveData, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnSendReceiveDataArgs> val = this.m_OnSendReceiveData;
				AsyncEventHandler<OnSendReceiveDataArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnSendReceiveDataArgs> value2 = (AsyncEventHandler<OnSendReceiveDataArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSendReceiveData, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnRaidNotificationArgs> OnRaidNotification
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnRaidNotificationArgs> val = this.m_OnRaidNotification;
				AsyncEventHandler<OnRaidNotificationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnRaidNotificationArgs> value2 = (AsyncEventHandler<OnRaidNotificationArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRaidNotification, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnRaidNotificationArgs> val = this.m_OnRaidNotification;
				AsyncEventHandler<OnRaidNotificationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnRaidNotificationArgs> value2 = (AsyncEventHandler<OnRaidNotificationArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRaidNotification, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnGiftedSubscriptionArgs> OnGiftedSubscription
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnGiftedSubscriptionArgs> val = this.m_OnGiftedSubscription;
				AsyncEventHandler<OnGiftedSubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnGiftedSubscriptionArgs> value2 = (AsyncEventHandler<OnGiftedSubscriptionArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnGiftedSubscription, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnGiftedSubscriptionArgs> val = this.m_OnGiftedSubscription;
				AsyncEventHandler<OnGiftedSubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnGiftedSubscriptionArgs> value2 = (AsyncEventHandler<OnGiftedSubscriptionArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnGiftedSubscription, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnSelfRaidError
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSelfRaidError;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSelfRaidError, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSelfRaidError;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSelfRaidError, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnNoPermissionError
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnNoPermissionError;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnNoPermissionError, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnNoPermissionError;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnNoPermissionError, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnRaidedChannelIsMatureAudience
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRaidedChannelIsMatureAudience;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRaidedChannelIsMatureAudience, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRaidedChannelIsMatureAudience;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRaidedChannelIsMatureAudience, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> OnFailureToReceiveJoinConfirmation
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> val = this.m_OnFailureToReceiveJoinConfirmation;
				AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> value2 = (AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnFailureToReceiveJoinConfirmation, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> val = this.m_OnFailureToReceiveJoinConfirmation;
				AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs> value2 = (AsyncEventHandler<OnFailureToReceiveJoinConfirmationArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnFailureToReceiveJoinConfirmation, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUnaccountedForArgs> OnUnaccountedFor
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUnaccountedForArgs> val = this.m_OnUnaccountedFor;
				AsyncEventHandler<OnUnaccountedForArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUnaccountedForArgs> value2 = (AsyncEventHandler<OnUnaccountedForArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUnaccountedFor, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUnaccountedForArgs> val = this.m_OnUnaccountedFor;
				AsyncEventHandler<OnUnaccountedForArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUnaccountedForArgs> value2 = (AsyncEventHandler<OnUnaccountedForArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUnaccountedFor, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnMessageClearedArgs> OnMessageCleared
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnMessageClearedArgs> val = this.m_OnMessageCleared;
				AsyncEventHandler<OnMessageClearedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageClearedArgs> value2 = (AsyncEventHandler<OnMessageClearedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageCleared, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnMessageClearedArgs> val = this.m_OnMessageCleared;
				AsyncEventHandler<OnMessageClearedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageClearedArgs> value2 = (AsyncEventHandler<OnMessageClearedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageCleared, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnCommunitySubscriptionArgs> OnCommunitySubscription
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnCommunitySubscriptionArgs> val = this.m_OnCommunitySubscription;
				AsyncEventHandler<OnCommunitySubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnCommunitySubscriptionArgs> value2 = (AsyncEventHandler<OnCommunitySubscriptionArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnCommunitySubscription, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnCommunitySubscriptionArgs> val = this.m_OnCommunitySubscription;
				AsyncEventHandler<OnCommunitySubscriptionArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnCommunitySubscriptionArgs> value2 = (AsyncEventHandler<OnCommunitySubscriptionArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnCommunitySubscription, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnErrorEventArgs> OnError
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnErrorEventArgs> val = this.m_OnError;
				AsyncEventHandler<OnErrorEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnErrorEventArgs> value2 = (AsyncEventHandler<OnErrorEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnError, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnErrorEventArgs> val = this.m_OnError;
				AsyncEventHandler<OnErrorEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnErrorEventArgs> value2 = (AsyncEventHandler<OnErrorEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnError, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnAnnouncementArgs> OnAnnouncement
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnAnnouncementArgs> val = this.m_OnAnnouncement;
				AsyncEventHandler<OnAnnouncementArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnAnnouncementArgs> value2 = (AsyncEventHandler<OnAnnouncementArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnAnnouncement, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnAnnouncementArgs> val = this.m_OnAnnouncement;
				AsyncEventHandler<OnAnnouncementArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnAnnouncementArgs> value2 = (AsyncEventHandler<OnAnnouncementArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnAnnouncement, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnMessageThrottledArgs> OnMessageThrottled
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnMessageThrottledArgs> val = this.m_OnMessageThrottled;
				AsyncEventHandler<OnMessageThrottledArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageThrottledArgs> value2 = (AsyncEventHandler<OnMessageThrottledArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageThrottled, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnMessageThrottledArgs> val = this.m_OnMessageThrottled;
				AsyncEventHandler<OnMessageThrottledArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageThrottledArgs> value2 = (AsyncEventHandler<OnMessageThrottledArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageThrottled, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnRequiresVerifiedPhoneNumber
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRequiresVerifiedPhoneNumber;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRequiresVerifiedPhoneNumber, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnRequiresVerifiedPhoneNumber;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRequiresVerifiedPhoneNumber, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnFollowersOnly
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnFollowersOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnFollowersOnly, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnFollowersOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnFollowersOnly, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnSubsOnly
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSubsOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSubsOnly, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSubsOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSubsOnly, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnEmoteOnly
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnEmoteOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnEmoteOnly, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnEmoteOnly;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnEmoteOnly, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnSuspended
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSuspended;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSuspended, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSuspended;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSuspended, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnBanned
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnBanned;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBanned, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnBanned;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBanned, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnSlowMode
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSlowMode;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSlowMode, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnSlowMode;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnSlowMode, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<NoticeEventArgs> OnR9kMode
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnR9kMode;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnR9kMode, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<NoticeEventArgs> val = this.m_OnR9kMode;
				AsyncEventHandler<NoticeEventArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<NoticeEventArgs> value2 = (AsyncEventHandler<NoticeEventArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnR9kMode, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUserIntroArgs> OnUserIntro
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUserIntroArgs> val = this.m_OnUserIntro;
				AsyncEventHandler<OnUserIntroArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserIntroArgs> value2 = (AsyncEventHandler<OnUserIntroArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserIntro, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUserIntroArgs> val = this.m_OnUserIntro;
				AsyncEventHandler<OnUserIntroArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUserIntroArgs> value2 = (AsyncEventHandler<OnUserIntroArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUserIntro, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> OnAnonGiftPaidUpgrade
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> val = this.m_OnAnonGiftPaidUpgrade;
				AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> value2 = (AsyncEventHandler<OnAnonGiftPaidUpgradeArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnAnonGiftPaidUpgrade, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> val = this.m_OnAnonGiftPaidUpgrade;
				AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnAnonGiftPaidUpgradeArgs> value2 = (AsyncEventHandler<OnAnonGiftPaidUpgradeArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnAnonGiftPaidUpgrade, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnUnraidNotificationArgs> OnUnraidNotification
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnUnraidNotificationArgs> val = this.m_OnUnraidNotification;
				AsyncEventHandler<OnUnraidNotificationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUnraidNotificationArgs> value2 = (AsyncEventHandler<OnUnraidNotificationArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUnraidNotification, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnUnraidNotificationArgs> val = this.m_OnUnraidNotification;
				AsyncEventHandler<OnUnraidNotificationArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnUnraidNotificationArgs> value2 = (AsyncEventHandler<OnUnraidNotificationArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnUnraidNotification, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnRitualArgs> OnRitual
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnRitualArgs> val = this.m_OnRitual;
				AsyncEventHandler<OnRitualArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnRitualArgs> value2 = (AsyncEventHandler<OnRitualArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRitual, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnRitualArgs> val = this.m_OnRitual;
				AsyncEventHandler<OnRitualArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnRitualArgs> value2 = (AsyncEventHandler<OnRitualArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnRitual, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnBitsBadgeTierArgs> OnBitsBadgeTier
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnBitsBadgeTierArgs> val = this.m_OnBitsBadgeTier;
				AsyncEventHandler<OnBitsBadgeTierArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnBitsBadgeTierArgs> value2 = (AsyncEventHandler<OnBitsBadgeTierArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBitsBadgeTier, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnBitsBadgeTierArgs> val = this.m_OnBitsBadgeTier;
				AsyncEventHandler<OnBitsBadgeTierArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnBitsBadgeTierArgs> value2 = (AsyncEventHandler<OnBitsBadgeTierArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnBitsBadgeTier, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnCommunityPayForwardArgs> OnCommunityPayForward
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnCommunityPayForwardArgs> val = this.m_OnCommunityPayForward;
				AsyncEventHandler<OnCommunityPayForwardArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnCommunityPayForwardArgs> value2 = (AsyncEventHandler<OnCommunityPayForwardArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnCommunityPayForward, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnCommunityPayForwardArgs> val = this.m_OnCommunityPayForward;
				AsyncEventHandler<OnCommunityPayForwardArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnCommunityPayForwardArgs> value2 = (AsyncEventHandler<OnCommunityPayForwardArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnCommunityPayForward, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnStandardPayForwardArgs> OnStandardPayForward
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnStandardPayForwardArgs> val = this.m_OnStandardPayForward;
				AsyncEventHandler<OnStandardPayForwardArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnStandardPayForwardArgs> value2 = (AsyncEventHandler<OnStandardPayForwardArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnStandardPayForward, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnStandardPayForwardArgs> val = this.m_OnStandardPayForward;
				AsyncEventHandler<OnStandardPayForwardArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnStandardPayForwardArgs> value2 = (AsyncEventHandler<OnStandardPayForwardArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnStandardPayForward, value2, val2);
				}
				while (val != val2);
			}
		}

		public Client()
			: base((IClient)null, (ClientProtocol)1, (ISendOptions)null, (ILoggerFactory)null)
		{
			ThreadDispatcher.EnsureCreated(".ctor");
			((TwitchClient)this).OnConnected += delegate(object sender, OnConnectedEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnConnected?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnReconnected += delegate(object sender, OnConnectedEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnReconnected?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnJoinedChannel += delegate(object sender, OnJoinedChannelArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnJoinedChannel?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnIncorrectLogin += delegate(object sender, OnIncorrectLoginArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnIncorrectLogin?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnChannelStateChanged += delegate(object sender, OnChannelStateChangedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnChannelStateChanged?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnUserStateChanged += delegate(object sender, OnUserStateChangedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUserStateChanged?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnMessageReceived += delegate(object sender, OnMessageReceivedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnMessageReceived?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnWhisperReceived += delegate(object sender, OnWhisperReceivedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnWhisperReceived?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnMessageSent += delegate(object sender, OnMessageSentArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnMessageSent?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnChatCommandReceived += delegate(object sender, OnChatCommandReceivedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnChatCommandReceived?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnWhisperCommandReceived += delegate(object sender, OnWhisperCommandReceivedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnWhisperCommandReceived?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnUserJoined += delegate(object sender, OnUserJoinedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUserJoined?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnNewSubscriber += delegate(object sender, OnNewSubscriberArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnNewSubscriber?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnReSubscriber += delegate(object sender, OnReSubscriberArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnReSubscriber?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnPrimePaidSubscriber += delegate(object sender, OnPrimePaidSubscriberArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnPrimePaidSubscriber?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnContinuedGiftedSubscription += delegate(object sender, OnContinuedGiftedSubscriptionArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnContinuedGiftedSubscription?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnExistingUsersDetected += delegate(object sender, OnExistingUsersDetectedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnExistingUsersDetected?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnUserLeft += delegate(object sender, OnUserLeftArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUserLeft?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnDisconnected += delegate(object sender, OnDisconnectedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnDisconnected?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnConnectionError += delegate(object sender, OnConnectionErrorArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnConnectionError?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnChatCleared += delegate(object sender, OnChatClearedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnChatCleared?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnUserTimedout += delegate(object sender, OnUserTimedoutArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUserTimedout?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnLeftChannel += delegate(object sender, OnLeftChannelArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnLeftChannel?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnUserBanned += delegate(object sender, OnUserBannedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUserBanned?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnSendReceiveData += delegate(object sender, OnSendReceiveDataArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnSendReceiveData?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnRaidNotification += delegate(object sender, OnRaidNotificationArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnRaidNotification?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnGiftedSubscription += delegate(object sender, OnGiftedSubscriptionArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnGiftedSubscription?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnRaidedChannelIsMatureAudience += delegate(object sender, NoticeEventArgs arg)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnRaidedChannelIsMatureAudience?.Invoke(sender, arg);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnFailureToReceiveJoinConfirmation += delegate(object sender, OnFailureToReceiveJoinConfirmationArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnFailureToReceiveJoinConfirmation?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnUnaccountedFor += delegate(object sender, OnUnaccountedForArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUnaccountedFor?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnSelfRaidError += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnSelfRaidError?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnNoPermissionError += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnNoPermissionError?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnMessageCleared += delegate(object sender, OnMessageClearedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnMessageCleared?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnCommunitySubscription += delegate(object sender, OnCommunitySubscriptionArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnCommunitySubscription?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnError += delegate(object sender, OnErrorEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnError?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnAnnouncement += delegate(object sender, OnAnnouncementArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnAnnouncement?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnMessageThrottled += delegate(object sender, OnMessageThrottledArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnMessageThrottled?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnRequiresVerifiedPhoneNumber += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnRequiresVerifiedPhoneNumber?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnFollowersOnly += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnFollowersOnly?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnSubsOnly += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnSubsOnly?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnEmoteOnly += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnEmoteOnly?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnSuspended += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnSuspended?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnBanned += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnBanned?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnSlowMode += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnSlowMode?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnR9kMode += delegate(object sender, NoticeEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnR9kMode?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnUserIntro += delegate(object sender, OnUserIntroArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUserIntro?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnAnonGiftPaidUpgrade += delegate(object sender, OnAnonGiftPaidUpgradeArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnAnonGiftPaidUpgrade?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnUnraidNotification += delegate(object sender, OnUnraidNotificationArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUnraidNotification?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnRitual += delegate(object sender, OnRitualArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnRitual?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnBitsBadgeTier += delegate(object sender, OnBitsBadgeTierArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnBitsBadgeTier?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnCommunityPayForward += delegate(object sender, OnCommunityPayForwardArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnCommunityPayForward?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
			((TwitchClient)this).OnStandardPayForward += delegate(object sender, OnStandardPayForwardArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnStandardPayForward?.Invoke(sender, e);
				});
				return Task.CompletedTask;
			};
		}

		private void HandleNotInitialized()
		{
			ThreadDispatcher.Enqueue(delegate
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				throw new ClientNotInitializedException("The twitch client has not been initialized and cannot be used. Please call Initialize();");
			});
		}
	}
	public static class ColorExtension
	{
		public static Color ToUnity(this Color color)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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)
			return new Color((float)(int)color.R, (float)(int)color.G, (float)(int)color.B, (float)(int)color.A);
		}
	}
	public class PubSub : TwitchPubSub, ITwitchPubSub
	{
		public event EventHandler OnPubSubServiceConnected;

		public event EventHandler<OnPubSubServiceErrorArgs> OnPubSubServiceError;

		public event EventHandler OnPubSubServiceClosed;

		public event EventHandler<OnListenResponseArgs> OnListenResponse;

		public event EventHandler<OnTimeoutArgs> OnTimeout;

		public event EventHandler<OnBanArgs> OnBan;

		public event EventHandler<OnUnbanArgs> OnUnban;

		public event EventHandler<OnUntimeoutArgs> OnUntimeout;

		public event EventHandler<OnHostArgs> OnHost;

		public event EventHandler<OnSubscribersOnlyArgs> OnSubscribersOnly;

		public event EventHandler<OnSubscribersOnlyOffArgs> OnSubscribersOnlyOff;

		public event EventHandler<OnClearArgs> OnClear;

		public event EventHandler<OnEmoteOnlyArgs> OnEmoteOnly;

		public event EventHandler<OnEmoteOnlyOffArgs> OnEmoteOnlyOff;

		public event EventHandler<OnR9kBetaArgs> OnR9kBeta;

		public event EventHandler<OnR9kBetaOffArgs> OnR9kBetaOff;

		public event EventHandler<OnStreamUpArgs> OnStreamUp;

		public event EventHandler<OnStreamDownArgs> OnStreamDown;

		public event EventHandler<OnViewCountArgs> OnViewCount;

		public event EventHandler<OnWhisperArgs> OnWhisper;

		public event EventHandler<OnChannelSubscriptionArgs> OnChannelSubscription;

		public event EventHandler<OnChannelExtensionBroadcastArgs> OnChannelExtensionBroadcast;

		public event EventHandler<OnCustomRewardCreatedArgs> OnCustomRewardCreated;

		public event EventHandler<OnCustomRewardUpdatedArgs> OnCustomRewardUpdated;

		public event EventHandler<OnCustomRewardDeletedArgs> OnCustomRewardDeleted;

		public event EventHandler<OnRewardRedeemedArgs> OnRewardRedeemed;

		public event EventHandler<OnChannelPointsRewardRedeemedArgs> OnChannelPointsRewardRedeemed;

		public event EventHandler<OnBitsReceivedV2Args> OnBitsReceivedV2;

		public event EventHandler<OnLeaderboardEventArgs> OnLeaderboardSubs;

		public event EventHandler<OnLeaderboardEventArgs> OnLeaderboardBits;

		public event EventHandler<OnRaidUpdateArgs> OnRaidUpdate;

		public event EventHandler<OnRaidUpdateV2Args> OnRaidUpdateV2;

		public event EventHandler<OnRaidGoArgs> OnRaidGo;

		public event EventHandler<OnMessageDeletedArgs> OnMessageDeleted;

		public event EventHandler<OnLogArgs> OnLog;

		public event EventHandler<OnCommercialArgs> OnCommercial;

		public event EventHandler<OnPredictionArgs> OnPrediction;

		public event EventHandler<OnAutomodCaughtMessageArgs> OnAutomodCaughtMessage;

		public event EventHandler<OnAutomodCaughtUserMessage> OnAutomodCaughtUserMessage;

		public PubSub(ILogger<TwitchPubSub> logger = null)
			: base(logger)
		{
			ThreadDispatcher.EnsureCreated(".ctor");
			((TwitchPubSub)this).OnPubSubServiceConnected += delegate(object sender, EventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnPubSubServiceConnected?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnPubSubServiceError += delegate(object sender, OnPubSubServiceErrorArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnPubSubServiceError?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnPubSubServiceClosed += delegate(object sender, EventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnPubSubServiceClosed?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnListenResponse += delegate(object sender, OnListenResponseArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnListenResponse?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnTimeout += delegate(object sender, OnTimeoutArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnTimeout?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnBan += delegate(object sender, OnBanArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnBan?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnUnban += delegate(object sender, OnUnbanArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUnban?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnUntimeout += delegate(object sender, OnUntimeoutArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnUntimeout?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnHost += delegate(object sender, OnHostArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnHost?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnSubscribersOnly += delegate(object sender, OnSubscribersOnlyArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnSubscribersOnly?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnSubscribersOnlyOff += delegate(object sender, OnSubscribersOnlyOffArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnSubscribersOnlyOff?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnClear += delegate(object sender, OnClearArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnClear?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnEmoteOnly += delegate(object sender, OnEmoteOnlyArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnEmoteOnly?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnEmoteOnlyOff += delegate(object sender, OnEmoteOnlyOffArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnEmoteOnlyOff?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnR9kBeta += delegate(object sender, OnR9kBetaArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnR9kBeta?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnR9kBetaOff += delegate(object sender, OnR9kBetaOffArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnR9kBetaOff?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnStreamUp += delegate(object sender, OnStreamUpArgs arg)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnStreamUp(sender, arg);
				});
			};
			((TwitchPubSub)this).OnStreamDown += delegate(object sender, OnStreamDownArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnStreamDown?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnViewCount += delegate(object sender, OnViewCountArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnViewCount?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnWhisper += delegate(object sender, OnWhisperArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnWhisper?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnChannelSubscription += delegate(object sender, OnChannelSubscriptionArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnChannelSubscription?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnChannelExtensionBroadcast += delegate(object sender, OnChannelExtensionBroadcastArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnChannelExtensionBroadcast?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnCustomRewardCreated += delegate(object sender, OnCustomRewardCreatedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnCustomRewardCreated?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnCustomRewardUpdated += delegate(object sender, OnCustomRewardUpdatedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnCustomRewardUpdated?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnCustomRewardDeleted += delegate(object sender, OnCustomRewardDeletedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnCustomRewardDeleted?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnRewardRedeemed += delegate(object sender, OnRewardRedeemedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnRewardRedeemed?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnChannelPointsRewardRedeemed += delegate(object sender, OnChannelPointsRewardRedeemedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnChannelPointsRewardRedeemed?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnBitsReceivedV2 += delegate(object sender, OnBitsReceivedV2Args e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnBitsReceivedV2?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnLeaderboardSubs += delegate(object sender, OnLeaderboardEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnLeaderboardSubs?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnLeaderboardBits += delegate(object sender, OnLeaderboardEventArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnLeaderboardBits?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnRaidUpdate += delegate(object sender, OnRaidUpdateArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnRaidUpdate?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnRaidUpdateV2 += delegate(object sender, OnRaidUpdateV2Args e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnRaidUpdateV2?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnRaidGo += delegate(object sender, OnRaidGoArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnRaidGo?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnMessageDeleted += delegate(object sender, OnMessageDeletedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnMessageDeleted?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnLog += delegate(object sender, OnLogArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnLog?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnCommercial += delegate(object sender, OnCommercialArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnCommercial?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnPrediction += delegate(object sender, OnPredictionArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnPrediction?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnAutomodCaughtMessage += delegate(object sender, OnAutomodCaughtMessageArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnAutomodCaughtMessage?.Invoke(sender, e);
				});
			};
			((TwitchPubSub)this).OnAutomodCaughtUserMessage += delegate(object sender, OnAutomodCaughtUserMessage e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnAutomodCaughtUserMessage?.Invoke(sender, e);
				});
			};
		}
	}
	public class ThreadDispatcher : MonoBehaviour
	{
		private static ThreadDispatcher _instance;

		private static ConcurrentQueue<Action> _executionQueue = new ConcurrentQueue<Action>();

		public static void EnsureCreated([CallerMemberName] string callerMemberName = null)
		{
			if (Application.isPlaying && ((Object)(object)_instance == (Object)null || (Object)(object)((Component)_instance).gameObject == (Object)null))
			{
				_instance = CreateThreadDispatcherSingleton(callerMemberName);
			}
		}

		public static void Enqueue(Action action)
		{
			_executionQueue.Enqueue(action);
		}

		private void Update()
		{
			while (!_executionQueue.IsEmpty)
			{
				if (_executionQueue.TryDequeue(out var result))
				{
					result();
				}
			}
		}

		private static ThreadDispatcher CreateThreadDispatcherSingleton(string callerMemberName)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if (!UnityThread.CurrentIsMainThread)
			{
				throw new InvalidOperationException("The " + callerMemberName + " can only be created from the main thread. Did you accidentally delete the ThreadDispatcher in your scene?");
			}
			ThreadDispatcher threadDispatcher = new GameObject("ThreadDispatcher").AddComponent<ThreadDispatcher>();
			Object.DontDestroyOnLoad((Object)(object)threadDispatcher);
			return threadDispatcher;
		}
	}
	public class UnityFollowerService : FollowerService
	{
		public event EventHandler<OnServiceStartedArgs> OnServiceStarted;

		public event EventHandler<OnServiceStoppedArgs> OnServiceStopped;

		public event EventHandler<OnNewFollowersDetectedArgs> OnNewFollowersDetected;

		public UnityFollowerService(ITwitchAPI api, int checkIntervalSeconds = 60, int queryCount = 25)
			: base(api, checkIntervalSeconds, queryCount, 1000, false)
		{
			ThreadDispatcher.EnsureCreated(".ctor");
			((ApiService)this).OnServiceStarted += delegate(object sender, OnServiceStartedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnServiceStarted?.Invoke(sender, e);
				});
			};
			((ApiService)this).OnServiceStopped += delegate(object sender, OnServiceStoppedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnServiceStopped?.Invoke(sender, e);
				});
			};
			((FollowerService)this).OnNewFollowersDetected += delegate(object sender, OnNewFollowersDetectedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnNewFollowersDetected?.Invoke(sender, e);
				});
			};
		}
	}
	public class UnityLiveStreamMonitor : LiveStreamMonitorService
	{
		public event EventHandler<OnStreamOnlineArgs> OnStreamOnline;

		public event EventHandler<OnStreamOfflineArgs> OnStreamOffline;

		public event EventHandler<OnStreamUpdateArgs> OnStreamUpdate;

		public event EventHandler<OnServiceStartedArgs> OnServiceStarted;

		public event EventHandler<OnServiceStoppedArgs> OnServiceStopped;

		public event EventHandler<OnChannelsSetArgs> OnChannelsSet;

		public UnityLiveStreamMonitor(ITwitchAPI api, int checkIntervalSeconds = 60, int maxStreamRequestCountPerRequest = 100)
			: base(api, checkIntervalSeconds, maxStreamRequestCountPerRequest)
		{
			ThreadDispatcher.EnsureCreated(".ctor");
			((LiveStreamMonitorService)this).OnStreamOnline += delegate(object sender, OnStreamOnlineArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnStreamOnline?.Invoke(sender, e);
				});
			};
			((LiveStreamMonitorService)this).OnStreamOffline += delegate(object sender, OnStreamOfflineArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnStreamOffline?.Invoke(sender, e);
				});
			};
			((LiveStreamMonitorService)this).OnStreamUpdate += delegate(object sender, OnStreamUpdateArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnStreamUpdate?.Invoke(sender, e);
				});
			};
			((ApiService)this).OnServiceStarted += delegate(object sender, OnServiceStartedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnServiceStarted?.Invoke(sender, e);
				});
			};
			((ApiService)this).OnServiceStopped += delegate(object sender, OnServiceStoppedArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnServiceStopped?.Invoke(sender, e);
				});
			};
			((ApiService)this).OnChannelsSet += delegate(object sender, OnChannelsSetArgs e)
			{
				ThreadDispatcher.Enqueue(delegate
				{
					this.OnChannelsSet?.Invoke(sender, e);
				});
			};
		}
	}
	public class UnityThread : MonoBehaviour
	{
		private static Thread _mainThread;

		public static Thread Main => _mainThread;

		public static bool CurrentIsMainThread => _mainThread == null || _mainThread == Thread.CurrentThread;

		[RuntimeInitializeOnLoadMethod(/*Could not decode attribute arguments.*/)]
		private static void SetMainUnityThread()
		{
			_mainThread = Thread.CurrentThread;
		}
	}
}

Unity.Abstractions.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Unity.Exceptions;
using Unity.Injection;
using Unity.Lifetime;
using Unity.Policy;
using Unity.Resolution;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CLSCompliant(true)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("Unity.Container, PublicKey=002400000480000094000000060200000024000052534131000400000100010037b16015885a7ac3c63f3c10b23972ec0dfd6db643eaef45ea2297bdfdc53b1945017fc76fd038dc6e7bf9190024d5435fa49630fdfd143e3149a1506b895fbcce017df1d4f0eac6f05f6d257be45c7be9a8aa8d3d4164892dc75e7c379a22da0d986db393fbd09e4ba42398c80a305361553ef90eb3484d9cf12df90fc0e6e3")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Unity Open Source Project")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © Unity Container Project 2018")]
[assembly: AssemblyDescription("Unity Container Public Abstractions")]
[assembly: AssemblyFileVersion("5.11.1.0")]
[assembly: AssemblyInformationalVersion("5.11.1+7a870102bbc75751981b2c06ac08b7cd10eba5e4")]
[assembly: AssemblyProduct("Unity.Abstractions")]
[assembly: AssemblyTitle("Unity.Abstractions")]
[assembly: AssemblyVersion("5.11.1.0")]
namespace System.Reflection
{
	internal static class IntrospectionExtensions
	{
		public static MethodInfo GetGetMethod(this PropertyInfo info, bool _)
		{
			return info.GetMethod;
		}

		public static MethodInfo GetSetMethod(this PropertyInfo info, bool _)
		{
			return info.SetMethod;
		}
	}
}
namespace Unity
{
	public interface IContainerRegistration
	{
		Type RegisteredType { get; }

		string Name { get; }

		Type MappedToType { get; }

		LifetimeManager LifetimeManager { get; }
	}
	[CLSCompliant(true)]
	public interface IUnityContainer : IDisposable
	{
		IEnumerable<IContainerRegistration> Registrations { get; }

		IUnityContainer Parent { get; }

		IUnityContainer RegisterType(Type registeredType, Type mappedToType, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers);

		IUnityContainer RegisterInstance(Type type, string name, object instance, IInstanceLifetimeManager lifetimeManager);

		IUnityContainer RegisterFactory(Type type, string name, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager);

		bool IsRegistered(Type type, string name);

		object Resolve(Type type, string name, params ResolverOverride[] overrides);

		object BuildUp(Type type, object existing, string name, params ResolverOverride[] overrides);

		IUnityContainer CreateChildContainer();
	}
	[CLSCompliant(true)]
	public interface IUnityContainerAsync : IDisposable
	{
		IEnumerable<IContainerRegistration> Registrations { get; }

		IUnityContainerAsync Parent { get; }

		Task RegisterType(IEnumerable<Type> interfaces, Type type, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers);

		Task RegisterInstance(IEnumerable<Type> interfaces, string name, object instance, IInstanceLifetimeManager lifetimeManager);

		Task RegisterFactory(IEnumerable<Type> interfaces, string name, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager);

		bool IsRegistered(Type type, string name);

		ValueTask<object> ResolveAsync(Type type, string name, params ResolverOverride[] overrides);

		ValueTask<IEnumerable<object>> Resolve(Type type, Regex regex, params ResolverOverride[] overrides);

		IUnityContainerAsync CreateChildContainer();
	}
	public enum ResolutionOption
	{
		Required,
		Optional
	}
	public abstract class DependencyResolutionAttribute : Attribute
	{
		public string Name { get; }

		protected DependencyResolutionAttribute(string name)
		{
			Name = name;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
	public sealed class DependencyAttribute : DependencyResolutionAttribute
	{
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal static DependencyAttribute Instance = new DependencyAttribute();

		public DependencyAttribute()
			: base(null)
		{
		}

		public DependencyAttribute(string name)
			: base(name)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Constructor)]
	public sealed class InjectionConstructorAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public sealed class InjectionMethodAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
	public sealed class OptionalDependencyAttribute : DependencyResolutionAttribute
	{
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal static OptionalDependencyAttribute Instance = new OptionalDependencyAttribute();

		public OptionalDependencyAttribute()
			: base(null)
		{
		}

		public OptionalDependencyAttribute(string name)
			: base(name)
		{
		}
	}
	public class ResolutionFailedException : Exception
	{
		public string TypeRequested { get; private set; }

		public string NameRequested { get; private set; }

		public ResolutionFailedException(Type type, string name, string message, Exception innerException = null)
			: base(message, innerException)
		{
			TypeRequested = (type ?? throw new ArgumentNullException("type")).GetTypeInfo().Name;
			NameRequested = name;
		}
	}
	public static class UnityContainerExtensions
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType<T>(this IUnityContainer container, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), null, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType<T>(this IUnityContainer container, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), null, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType<T>(this IUnityContainer container, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), name, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType<T>(this IUnityContainer container, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), name, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType<TFrom, TTo>(this IUnityContainer container, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(typeof(TFrom), typeof(TTo), null, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType<TFrom, TTo>(this IUnityContainer container, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(typeof(TFrom), typeof(TTo), null, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType<TFrom, TTo>(this IUnityContainer container, string name, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(typeof(TFrom), typeof(TTo), name, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType<TFrom, TTo>(this IUnityContainer container, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(typeof(TFrom), typeof(TTo), name, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterSingleton<T>(this IUnityContainer container, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), null, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterSingleton<T>(this IUnityContainer container, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), name, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterSingleton<TFrom, TTo>(this IUnityContainer container, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(typeof(TFrom), typeof(TTo), null, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterSingleton<TFrom, TTo>(this IUnityContainer container, string name, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(typeof(TFrom), typeof(TTo), name, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType(this IUnityContainer container, Type t, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, null, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType(this IUnityContainer container, Type t, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, null, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType(this IUnityContainer container, Type t, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, name, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType(this IUnityContainer container, Type t, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, name, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType(this IUnityContainer container, Type from, Type to, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, null, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType(this IUnityContainer container, Type from, Type to, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, name, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterType(this IUnityContainer container, Type from, Type to, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, null, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterSingleton(this IUnityContainer container, Type t, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, null, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterSingleton(this IUnityContainer container, Type t, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, name, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterSingleton(this IUnityContainer container, Type from, Type to, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, null, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterSingleton(this IUnityContainer container, Type from, Type to, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, name, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterInstance<TInterface>(this IUnityContainer container, TInterface instance)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(typeof(TInterface), null, instance, new ContainerControlledLifetimeManager());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterInstance<TInterface>(this IUnityContainer container, TInterface instance, IInstanceLifetimeManager lifetimeManager)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(typeof(TInterface), null, instance, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterInstance<TInterface>(this IUnityContainer container, string name, TInterface instance)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(typeof(TInterface), name, instance, new ContainerControlledLifetimeManager());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterInstance<TInterface>(this IUnityContainer container, string name, TInterface instance, IInstanceLifetimeManager lifetimeManager)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(typeof(TInterface), name, instance, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterInstance(this IUnityContainer container, Type t, object instance)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(t, null, instance, new ContainerControlledLifetimeManager());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterInstance(this IUnityContainer container, Type t, object instance, IInstanceLifetimeManager lifetimeManager)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(t, null, instance, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterInstance(this IUnityContainer container, Type t, string name, object instance)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(t, name, instance, new ContainerControlledLifetimeManager());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterFactory<TInterface>(this IUnityContainer container, Func<IUnityContainer, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			if (factory == null)
			{
				throw new ArgumentNullException("factory");
			}
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(typeof(TInterface), null, (IUnityContainer c, Type t, string n) => factory(c), lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterFactory<TInterface>(this IUnityContainer container, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(typeof(TInterface), null, factory, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterFactory<TInterface>(this IUnityContainer container, string name, Func<IUnityContainer, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			if (factory == null)
			{
				throw new ArgumentNullException("factory");
			}
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(typeof(TInterface), name, (IUnityContainer c, Type t, string n) => factory(c), lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterFactory<TInterface>(this IUnityContainer container, string name, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(typeof(TInterface), name, factory, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterFactory(this IUnityContainer container, Type type, Func<IUnityContainer, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(type, null, (IUnityContainer c, Type t, string n) => factory(c), lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterFactory(this IUnityContainer container, Type type, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(type, null, factory, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterFactory(this IUnityContainer container, Type type, string name, Func<IUnityContainer, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(type, name, (IUnityContainer c, Type t, string n) => factory(c), lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainer RegisterFactory(this IUnityContainer container, Type type, string name, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(type, name, factory, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static T Resolve<T>(this IUnityContainer container, params ResolverOverride[] overrides)
		{
			return (T)(container ?? throw new ArgumentNullException("container")).Resolve(typeof(T), null, overrides);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static T Resolve<T>(this IUnityContainer container, string name, params ResolverOverride[] overrides)
		{
			return (T)(container ?? throw new ArgumentNullException("container")).Resolve(typeof(T), name, overrides);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static object Resolve(this IUnityContainer container, Type t, params ResolverOverride[] overrides)
		{
			return (container ?? throw new ArgumentNullException("container")).Resolve(t, null, overrides);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IEnumerable<object> ResolveAll(this IUnityContainer container, Type type, params ResolverOverride[] resolverOverrides)
		{
			object obj = (container ?? throw new ArgumentNullException("container")).Resolve((type ?? throw new ArgumentNullException("type")).MakeArrayType(), resolverOverrides);
			if (!(obj is IEnumerable<object> result))
			{
				return ((Array)obj).Cast<object>();
			}
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IEnumerable<T> ResolveAll<T>(this IUnityContainer container, params ResolverOverride[] resolverOverrides)
		{
			return (container ?? throw new ArgumentNullException("container")).ResolveAll(typeof(T), resolverOverrides).Cast<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static T BuildUp<T>(this IUnityContainer container, T existing, params ResolverOverride[] resolverOverrides)
		{
			if (existing == null)
			{
				throw new ArgumentNullException("existing");
			}
			return (T)(container ?? throw new ArgumentNullException("container")).BuildUp(typeof(T), existing, null, resolverOverrides);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static T BuildUp<T>(this IUnityContainer container, T existing, string name, params ResolverOverride[] resolverOverrides)
		{
			if (existing == null)
			{
				throw new ArgumentNullException("existing");
			}
			if (container == null)
			{
				throw new ArgumentNullException("container");
			}
			return (T)container.BuildUp(typeof(T), existing, name, resolverOverrides);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static object BuildUp(this IUnityContainer container, Type t, object existing, params ResolverOverride[] resolverOverrides)
		{
			return (container ?? throw new ArgumentNullException("container")).BuildUp(t, existing, null, resolverOverrides);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsRegistered(this IUnityContainer container, Type typeToCheck)
		{
			return (container ?? throw new ArgumentNullException("container")).IsRegistered(typeToCheck ?? throw new ArgumentNullException("typeToCheck"), null);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsRegistered<T>(this IUnityContainer container)
		{
			return (container ?? throw new ArgumentNullException("container")).IsRegistered(typeof(T), null);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsRegistered<T>(this IUnityContainer container, string nameToCheck)
		{
			return (container ?? throw new ArgumentNullException("container")).IsRegistered(typeof(T), nameToCheck);
		}
	}
	public static class UnityContainerAsyncExtensions
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType<T>(this IUnityContainerAsync container, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), null, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType<T>(this IUnityContainerAsync container, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), null, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType<T>(this IUnityContainerAsync container, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), name, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType<T>(this IUnityContainerAsync container, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), name, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType<TFrom, TTo>(this IUnityContainerAsync container, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(new Type[1] { typeof(TFrom) }, typeof(TTo), null, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType<TFrom, TTo>(this IUnityContainerAsync container, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(new Type[1] { typeof(TFrom) }, typeof(TTo), null, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType<TFrom, TTo>(this IUnityContainerAsync container, string name, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(new Type[1] { typeof(TFrom) }, typeof(TTo), name, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType<TFrom, TTo>(this IUnityContainerAsync container, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(new Type[1] { typeof(TFrom) }, typeof(TTo), name, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterSingleton<T>(this IUnityContainerAsync container, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), null, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterSingleton<T>(this IUnityContainerAsync container, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, typeof(T), name, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterSingleton<TFrom, TTo>(this IUnityContainerAsync container, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(new Type[1] { typeof(TFrom) }, typeof(TTo), null, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterSingleton<TFrom, TTo>(this IUnityContainerAsync container, string name, params InjectionMember[] injectionMembers) where TTo : TFrom
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(new Type[1] { typeof(TFrom) }, typeof(TTo), name, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType(this IUnityContainerAsync container, Type t, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, null, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType(this IUnityContainerAsync container, Type t, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, null, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType(this IUnityContainerAsync container, Type t, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, name, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType(this IUnityContainerAsync container, Type t, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, name, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType(this IUnityContainerAsync container, IEnumerable<Type> from, Type to, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, null, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType(this IUnityContainerAsync container, IEnumerable<Type> from, Type to, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, name, null, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterType(this IUnityContainerAsync container, IEnumerable<Type> from, Type to, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, null, lifetimeManager, injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterSingleton(this IUnityContainerAsync container, Type t, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, null, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterSingleton(this IUnityContainerAsync container, Type t, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(null, t, name, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterSingleton(this IUnityContainerAsync container, IEnumerable<Type> from, Type to, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, null, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterSingleton(this IUnityContainerAsync container, IEnumerable<Type> from, Type to, string name, params InjectionMember[] injectionMembers)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterType(from, to, name, new ContainerControlledLifetimeManager(), injectionMembers);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterInstance<TInterface>(this IUnityContainerAsync container, TInterface instance)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(new Type[1] { typeof(TInterface) }, null, instance, new ContainerControlledLifetimeManager());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterInstance<TInterface>(this IUnityContainerAsync container, TInterface instance, IInstanceLifetimeManager lifetimeManager)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(new Type[1] { typeof(TInterface) }, null, instance, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterInstance<TInterface>(this IUnityContainerAsync container, string name, TInterface instance)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(new Type[1] { typeof(TInterface) }, name, instance, new ContainerControlledLifetimeManager());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterInstance<TInterface>(this IUnityContainerAsync container, string name, TInterface instance, IInstanceLifetimeManager lifetimeManager)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(new Type[1] { typeof(TInterface) }, name, instance, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterInstance(this IUnityContainerAsync container, Type t, object instance)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(new Type[1] { t }, null, instance, new ContainerControlledLifetimeManager());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterInstance(this IUnityContainerAsync container, Type t, object instance, IInstanceLifetimeManager lifetimeManager)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(new Type[1] { t }, null, instance, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterInstance(this IUnityContainerAsync container, Type t, string name, object instance)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterInstance(new Type[1] { t }, name, instance, new ContainerControlledLifetimeManager());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterFactory<TInterface>(this IUnityContainerAsync container, Func<IUnityContainer, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			if (factory == null)
			{
				throw new ArgumentNullException("factory");
			}
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(new Type[1] { typeof(TInterface) }, null, (IUnityContainer c, Type t, string n) => factory(c), lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterFactory<TInterface>(this IUnityContainerAsync container, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(new Type[1] { typeof(TInterface) }, null, factory, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterFactory<TInterface>(this IUnityContainerAsync container, string name, Func<IUnityContainer, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			if (factory == null)
			{
				throw new ArgumentNullException("factory");
			}
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(new Type[1] { typeof(TInterface) }, name, (IUnityContainer c, Type t, string n) => factory(c), lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Task RegisterFactory<TInterface>(this IUnityContainerAsync container, string name, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(new Type[1] { typeof(TInterface) }, name, factory, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainerAsync RegisterFactory(this IUnityContainerAsync container, Type type, Func<IUnityContainerAsync, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(type, null, (IUnityContainerAsync c, Type t, string n) => factory(c), lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainerAsync RegisterFactory(this IUnityContainerAsync container, Type type, Func<IUnityContainerAsync, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(type, null, factory, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainerAsync RegisterFactory(this IUnityContainerAsync container, Type type, string name, Func<IUnityContainerAsync, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(type, name, (IUnityContainerAsync c, Type t, string n) => factory(c), lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IUnityContainerAsync RegisterFactory(this IUnityContainerAsync container, Type type, string name, Func<IUnityContainerAsync, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager = null)
		{
			return (container ?? throw new ArgumentNullException("container")).RegisterFactory(type, name, factory, lifetimeManager);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[SecuritySafeCritical]
		public static T ResolveAsync<T>(this IUnityContainerAsync container, params ResolverOverride[] overrides)
		{
			ValueTask<object> valueTask = (container ?? throw new ArgumentNullException("container")).ResolveAsync(typeof(T), null, overrides);
			if (!valueTask.IsCompleted)
			{
				return (T)valueTask.GetAwaiter().GetResult();
			}
			return (T)valueTask.Result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[SecuritySafeCritical]
		public static T ResolveAsync<T>(this IUnityContainerAsync container, string name, params ResolverOverride[] overrides)
		{
			ValueTask<object> valueTask = (container ?? throw new ArgumentNullException("container")).ResolveAsync(typeof(T), name, overrides);
			if (!valueTask.IsCompleted)
			{
				return (T)valueTask.GetAwaiter().GetResult();
			}
			return (T)valueTask.Result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[SecuritySafeCritical]
		public static ValueTask<object> ResolveAsync(this IUnityContainerAsync container, Type t, params ResolverOverride[] overrides)
		{
			return (container ?? throw new ArgumentNullException("container")).ResolveAsync(t, null, overrides);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsRegistered(this IUnityContainerAsync container, Type typeToCheck)
		{
			return (container ?? throw new ArgumentNullException("container")).IsRegistered(typeToCheck ?? throw new ArgumentNullException("typeToCheck"), null);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsRegistered<T>(this IUnityContainerAsync container)
		{
			return (container ?? throw new ArgumentNullException("container")).IsRegistered(typeof(T), null);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsRegistered<T>(this IUnityContainerAsync container, string nameToCheck)
		{
			return (container ?? throw new ArgumentNullException("container")).IsRegistered(typeof(T), nameToCheck);
		}
	}
	public static class Inject
	{
		public static ParameterBase Array(Type elementType, params object[] elementValues)
		{
			return new ResolvedArrayParameter(elementType, elementValues);
		}

		public static ParameterBase Array<TElement>(params object[] elementValues)
		{
			return new ResolvedArrayParameter(typeof(TElement), elementValues);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Parameter(object value)
		{
			return new InjectionParameter(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Parameter(Type type, object value)
		{
			return new InjectionParameter(type ?? throw new ArgumentNullException("type"), value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Parameter<TTarget>(object value)
		{
			return new InjectionParameter(typeof(TTarget), value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Field(string name, object value)
		{
			return new InjectionField(name ?? throw new ArgumentNullException("name"), value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Property(string name, object value)
		{
			return new InjectionProperty(name ?? throw new ArgumentNullException("name"), value);
		}
	}
	public static class Invoke
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Ctor()
		{
			return new InjectionConstructor();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Ctor(params object[] parameters)
		{
			return new InjectionConstructor(parameters);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Ctor(params Type[] parameters)
		{
			return new InjectionConstructor(parameters);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Ctor(ConstructorInfo info, params object[] parameters)
		{
			return new InjectionConstructor(info, parameters);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Constructor()
		{
			return new InjectionConstructor();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Constructor(params object[] parameters)
		{
			return new InjectionConstructor(parameters);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Constructor(params Type[] parameters)
		{
			return new InjectionConstructor(parameters);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Constructor(ConstructorInfo info, params object[] parameters)
		{
			return new InjectionConstructor(info, parameters);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Method(string name, params object[] parameters)
		{
			return new InjectionMethod(name, parameters);
		}
	}
	public static class Override
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Property(string name, object value)
		{
			return new PropertyOverride(name, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Field(string name, object value)
		{
			return new FieldOverride(name, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Parameter(object value)
		{
			return new ParameterOverride(value?.GetType() ?? throw new ArgumentNullException("value"), value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Parameter(string name, object value)
		{
			return new ParameterOverride(name, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Parameter(Type type, object value)
		{
			return new ParameterOverride(type, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Parameter(Type type, string name, object value)
		{
			return new ParameterOverride(type, name, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Parameter<TType>(object value)
		{
			return new ParameterOverride(typeof(TType), value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Parameter<TType>(string name, object value)
		{
			return Parameter(typeof(TType), name, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Dependency(object value)
		{
			return Dependency(value?.GetType() ?? throw new ArgumentNullException("value"), null, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Dependency(string name, object value)
		{
			return Dependency(value?.GetType() ?? throw new ArgumentNullException("value"), name, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Dependency(Type type, object value)
		{
			return new DependencyOverride(type, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Dependency(Type type, string name, object value)
		{
			return new DependencyOverride(type, name, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Dependency<TType>(object value)
		{
			return new DependencyOverride(typeof(TType), value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ResolverOverride Dependency<TType>(string name, object value)
		{
			return new DependencyOverride(typeof(TType), name, value);
		}
	}
	public static class Resolve
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Dependency<TTarget>()
		{
			return new ResolvedParameter(typeof(TTarget), null);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Dependency<TTarget>(string name)
		{
			return new ResolvedParameter(typeof(TTarget), name);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Parameter()
		{
			return new ResolvedParameter();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Parameter(string name)
		{
			return new ResolvedParameter(name);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Parameter(Type type)
		{
			return new ResolvedParameter(type);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Parameter<TTarget>()
		{
			return new ResolvedParameter(typeof(TTarget));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Parameter(Type type, string name)
		{
			return new ResolvedParameter(type, name);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Parameter<TTarget>(string name)
		{
			return new ResolvedParameter(typeof(TTarget), name);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static GenericParameter Generic(string genericParameterName)
		{
			return new GenericParameter(genericParameterName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static GenericParameter Generic(string genericParameterName, string registrationName)
		{
			return new GenericParameter(genericParameterName, registrationName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Optional()
		{
			return new OptionalParameter();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Optional(string name)
		{
			return new OptionalParameter(name);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Optional(Type type)
		{
			return new OptionalParameter(type);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Optional<TTarget>()
		{
			return new OptionalParameter(typeof(TTarget));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Optional(Type type, string name)
		{
			return new OptionalParameter(type, name);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ParameterBase Optional<TTarget>(string name)
		{
			return new OptionalParameter(typeof(TTarget), name);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Field(string name)
		{
			return new InjectionField(name);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember OptionalField(string name)
		{
			return new InjectionField(name, ResolutionOption.Optional);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember Property(string name)
		{
			return new InjectionProperty(name ?? throw new ArgumentNullException("name"));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static InjectionMember OptionalProperty(string name)
		{
			return new InjectionProperty(name ?? throw new ArgumentNullException("name"), ResolutionOption.Optional);
		}
	}
	public static class FactoryLifetime
	{
		public static IFactoryLifetimeManager Singleton => new SingletonLifetimeManager();

		public static IFactoryLifetimeManager PerContainer => new ContainerControlledLifetimeManager();

		public static IFactoryLifetimeManager Hierarchical => new HierarchicalLifetimeManager();

		public static ITypeLifetimeManager Scoped => new HierarchicalLifetimeManager();

		public static IFactoryLifetimeManager PerResolve => new PerResolveLifetimeManager();

		public static IFactoryLifetimeManager PerThread => new PerThreadLifetimeManager();

		public static IFactoryLifetimeManager Transient { get; } = new TransientLifetimeManager();


		public static IFactoryLifetimeManager PerContainerTransient => new ContainerControlledTransientManager();

		public static IFactoryLifetimeManager External => new ExternallyControlledLifetimeManager();
	}
	public static class InstanceLifetime
	{
		public static IInstanceLifetimeManager External => new ExternallyControlledLifetimeManager();

		public static IInstanceLifetimeManager Singleton => new SingletonLifetimeManager();

		public static IInstanceLifetimeManager PerContainer => new ContainerControlledLifetimeManager();
	}
	public static class TypeLifetime
	{
		public static ITypeLifetimeManager Singleton => new SingletonLifetimeManager();

		public static ITypeLifetimeManager ContainerControlled => new ContainerControlledLifetimeManager();

		public static ITypeLifetimeManager PerContainer => new ContainerControlledLifetimeManager();

		public static ITypeLifetimeManager Hierarchical => new HierarchicalLifetimeManager();

		public static ITypeLifetimeManager Scoped => new HierarchicalLifetimeManager();

		public static ITypeLifetimeManager PerResolve => new PerResolveLifetimeManager();

		public static ITypeLifetimeManager PerThread => new PerThreadLifetimeManager();

		public static ITypeLifetimeManager Transient => TransientLifetimeManager.Instance;

		public static ITypeLifetimeManager PerContainerTransient => new ContainerControlledTransientManager();

		public static ITypeLifetimeManager External => new ExternallyControlledLifetimeManager();
	}
	internal static class TypeReflectionExtensions
	{
		public static Type GetArrayParameterType(this Type typeToReflect, Type[] genericArguments)
		{
			int arrayRank = typeToReflect.GetArrayRank();
			Type elementType = typeToReflect.GetElementType();
			Type type = (elementType.IsArray ? elementType.GetArrayParameterType(genericArguments) : genericArguments[elementType.GenericParameterPosition]);
			if (1 != arrayRank)
			{
				return type.MakeArrayType(arrayRank);
			}
			return type.MakeArrayType();
		}

		public static IEnumerable<FieldInfo> GetDeclaredFields(this Type type)
		{
			TypeInfo info = type.GetTypeInfo();
			while (null != info)
			{
				foreach (FieldInfo declaredField in info.DeclaredFields)
				{
					yield return declaredField;
				}
				info = info.BaseType?.GetTypeInfo();
			}
		}

		public static IEnumerable<PropertyInfo> GetDeclaredProperties(this Type type)
		{
			TypeInfo info = type.GetTypeInfo();
			while (null != info)
			{
				foreach (PropertyInfo declaredProperty in info.DeclaredProperties)
				{
					yield return declaredProperty;
				}
				info = info.BaseType?.GetTypeInfo();
			}
		}

		public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type)
		{
			TypeInfo info = type.GetTypeInfo();
			while (null != info)
			{
				foreach (MethodInfo declaredMethod in info.DeclaredMethods)
				{
					yield return declaredMethod;
				}
				info = info.BaseType?.GetTypeInfo();
			}
		}
	}
}
namespace Unity.Policy
{
	public interface IPolicyList
	{
		object Get(Type type, Type policyInterface);

		object Get(Type type, string name, Type policyInterface);

		void Set(Type type, Type policyInterface, object policy);

		void Set(Type type, string name, Type policyInterface, object policy);

		void Clear(Type type, string name, Type policyInterface);
	}
	public interface IPolicySet
	{
		object Get(Type policyInterface);

		void Set(Type policyInterface, object policy);

		void Clear(Type policyInterface);
	}
	public static class PolicySetExtensions
	{
		public static T Get<T>(this IPolicySet policySet)
		{
			return (T)policySet.Get(typeof(T));
		}

		public static void Set<T>(this IPolicySet policySet, object policy)
		{
			policySet.Set(typeof(T), policy);
		}
	}
}
namespace Unity.Lifetime
{
	public interface IFactoryLifetimeManager
	{
		LifetimeManager CreateLifetimePolicy();
	}
	public interface IInstanceLifetimeManager
	{
		LifetimeManager CreateLifetimePolicy();
	}
	public interface ILifetimeContainer : IEnumerable<object>, IEnumerable, IDisposable
	{
		IUnityContainer Container { get; }

		int Count { get; }

		void Add(object item);

		bool Contains(object item);

		void Remove(object item);
	}
	public interface ITypeLifetimeManager
	{
		LifetimeManager CreateLifetimePolicy();
	}
	public abstract class LifetimeManager
	{
		public class InvalidValue
		{
			public override bool Equals(object obj)
			{
				return this == obj;
			}

			public override int GetHashCode()
			{
				return base.GetHashCode();
			}
		}

		public static readonly object NoValue = new InvalidValue();

		internal Delegate PipelineDelegate;

		public virtual bool InUse { get; set; }

		public virtual Func<ILifetimeContainer, object> TryGet { get; protected set; }

		public virtual Func<ILifetimeContainer, object> Get { get; protected set; }

		public virtual Action<object, ILifetimeContainer> Set { get; protected set; }

		public LifetimeManager()
		{
			Set = SetValue;
			Get = GetValue;
			TryGet = TryGetValue;
		}

		public virtual object TryGetValue(ILifetimeContainer container = null)
		{
			return GetValue(container);
		}

		public virtual object GetValue(ILifetimeContainer container = null)
		{
			return NoValue;
		}

		public virtual void SetValue(object newValue, ILifetimeContainer container = null)
		{
		}

		public virtual void RemoveValue(ILifetimeContainer container = null)
		{
		}

		public LifetimeManager CreateLifetimePolicy()
		{
			return OnCreateLifetimeManager();
		}

		protected abstract LifetimeManager OnCreateLifetimeManager();

		internal virtual object Pipeline<TContext>(ref TContext context) where TContext : IResolveContext
		{
			return ((ResolveDelegate<TContext>)PipelineDelegate)(ref context);
		}
	}
	public abstract class SynchronizedLifetimeManager : LifetimeManager, IDisposable
	{
		private readonly object _lock = new object();

		public static int ResolveTimeout = -1;

		public override object TryGetValue(ILifetimeContainer container = null)
		{
			if (Monitor.TryEnter(_lock))
			{
				object result = SynchronizedGetValue(container);
				Monitor.Exit(_lock);
				return result;
			}
			return LifetimeManager.NoValue;
		}

		public override object GetValue(ILifetimeContainer container = null)
		{
			if (Monitor.TryEnter(_lock, ResolveTimeout))
			{
				object obj = SynchronizedGetValue(container);
				if (LifetimeManager.NoValue != obj)
				{
					Monitor.Exit(_lock);
				}
				return obj;
			}
			throw new TimeoutException("Failed to enter a monitor");
		}

		protected abstract object SynchronizedGetValue(ILifetimeContainer container);

		public override void SetValue(object newValue, ILifetimeContainer container = null)
		{
			SynchronizedSetValue(newValue, container);
			TryExit();
		}

		protected abstract void SynchronizedSetValue(object newValue, ILifetimeContainer container);

		public void Recover()
		{
			TryExit();
		}

		protected virtual void TryExit()
		{
			if (!Monitor.IsEntered(_lock))
			{
				return;
			}
			try
			{
				Monitor.Exit(_lock);
			}
			catch (SynchronizationLockException)
			{
			}
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			TryExit();
		}
	}
	public class ContainerControlledLifetimeManager : SynchronizedLifetimeManager, IInstanceLifetimeManager, IFactoryLifetimeManager, ITypeLifetimeManager
	{
		protected object Value = LifetimeManager.NoValue;

		public object Scope { get; internal set; }

		public ContainerControlledLifetimeManager()
		{
			Set = base.SetValue;
			Get = base.GetValue;
			TryGet = base.TryGetValue;
		}

		public override object GetValue(ILifetimeContainer container = null)
		{
			return Get(container);
		}

		public override void SetValue(object newValue, ILifetimeContainer container = null)
		{
			Set(newValue, container);
			Set = delegate
			{
				throw new InvalidOperationException("ContainerControlledLifetimeManager can only be set once");
			};
			Get = SynchronizedGetValue;
			TryGet = SynchronizedGetValue;
		}

		protected override object SynchronizedGetValue(ILifetimeContainer container = null)
		{
			return Value;
		}

		protected override void SynchronizedSetValue(object newValue, ILifetimeContainer container = null)
		{
			Value = newValue;
		}

		public override void RemoveValue(ILifetimeContainer container = null)
		{
			Dispose();
		}

		protected override LifetimeManager OnCreateLifetimeManager()
		{
			return new ContainerControlledLifetimeManager
			{
				Scope = Scope
			};
		}

		protected override void Dispose(bool disposing)
		{
			try
			{
				if (LifetimeManager.NoValue != Value)
				{
					if (Value is IDisposable disposable)
					{
						disposable.Dispose();
					}
					Value = LifetimeManager.NoValue;
				}
			}
			finally
			{
				base.Dispose(disposing);
			}
		}

		public override string ToString()
		{
			return "Lifetime:PerContainer";
		}
	}
	public class ContainerControlledTransientManager : LifetimeManager, IFactoryLifetimeManager, ITypeLifetimeManager
	{
		public override bool InUse
		{
			get
			{
				return false;
			}
			set
			{
			}
		}

		public override void SetValue(object newValue, ILifetimeContainer container = null)
		{
			if (newValue is IDisposable item)
			{
				container?.Add(item);
			}
		}

		protected override LifetimeManager OnCreateLifetimeManager()
		{
			return this;
		}

		public override string ToString()
		{
			return "Lifetime:PerContainerTransient";
		}
	}
	public class ExternallyControlledLifetimeManager : LifetimeManager, IInstanceLifetimeManager, ITypeLifetimeManager, IFactoryLifetimeManager
	{
		private WeakReference _value;

		public override object GetValue(ILifetimeContainer container = null)
		{
			if (_value == null)
			{
				return LifetimeManager.NoValue;
			}
			object target = _value.Target;
			if (_value.IsAlive)
			{
				return target;
			}
			_value = null;
			return LifetimeManager.NoValue;
		}

		public override void SetValue(object newValue, ILifetimeContainer container = null)
		{
			_value = new WeakReference(newValue);
		}

		protected override LifetimeManager OnCreateLifetimeManager()
		{
			return new ExternallyControlledLifetimeManager();
		}

		public override string ToString()
		{
			return "Lifetime:External";
		}
	}
	public class HierarchicalLifetimeManager : SynchronizedLifetimeManager, IFactoryLifetimeManager, ITypeLifetimeManager
	{
		private class DisposableAction : IDisposable
		{
			private readonly Action _action;

			public DisposableAction(Action action)
			{
				_action = action ?? throw new ArgumentNullException("action");
			}

			public void Dispose()
			{
				_action();
			}
		}

		private readonly IDictionary<ILifetimeContainer, object> _values = new ConcurrentDictionary<ILifetimeContainer, object>();

		protected override object SynchronizedGetValue(ILifetimeContainer container = null)
		{
			if (!_values.TryGetValue(container ?? throw new ArgumentNullException("container"), out var value))
			{
				return LifetimeManager.NoValue;
			}
			return value;
		}

		protected override void SynchronizedSetValue(object newValue, ILifetimeContainer container = null)
		{
			_values[container ?? throw new ArgumentNullException("container")] = newValue;
			container.Add(new DisposableAction(delegate
			{
				RemoveValue(container);
			}));
		}

		public override void RemoveValue(ILifetimeContainer container = null)
		{
			if (container == null)
			{
				throw new ArgumentNullException("container");
			}
			if (_values.TryGetValue(container, out var value))
			{
				_values.Remove(container);
				if (value is IDisposable disposable)
				{
					disposable.Dispose();
				}
			}
		}

		protected override LifetimeManager OnCreateLifetimeManager()
		{
			return new HierarchicalLifetimeManager();
		}

		public override string ToString()
		{
			return "Lifetime:Hierarchical";
		}

		protected override void Dispose(bool disposing)
		{
			try
			{
				if (_values.Count != 0)
				{
					IDisposable[] array = _values.Values.OfType<IDisposable>().ToArray();
					for (int i = 0; i < array.Length; i++)
					{
						array[i].Dispose();
					}
					_values.Clear();
				}
			}
			finally
			{
				base.Dispose(disposing);
			}
		}
	}
	public class PerResolveLifetimeManager : LifetimeManager, IInstanceLifetimeManager, IFactoryLifetimeManager, ITypeLifetimeManager
	{
		protected object value = LifetimeManager.NoValue;

		public override object GetValue(ILifetimeContainer container = null)
		{
			return value;
		}

		protected override LifetimeManager OnCreateLifetimeManager()
		{
			return new PerResolveLifetimeManager();
		}

		public override string ToString()
		{
			return "Lifetime:PerResolve";
		}
	}
	public class PerThreadLifetimeManager : LifetimeManager, IFactoryLifetimeManager, ITypeLifetimeManager
	{
		[ThreadStatic]
		private static Dictionary<Guid, object> _values;

		private readonly Guid _key = Guid.NewGuid();

		public override object GetValue(ILifetimeContainer container = null)
		{
			if (_values == null)
			{
				return LifetimeManager.NoValue;
			}
			if (!_values.TryGetValue(_key, out var value))
			{
				return LifetimeManager.NoValue;
			}
			return value;
		}

		public override void SetValue(object newValue, ILifetimeContainer container = null)
		{
			if (_values == null)
			{
				_values = new Dictionary<Guid, object>();
			}
			_values[_key] = newValue;
		}

		protected override LifetimeManager OnCreateLifetimeManager()
		{
			return new PerThreadLifetimeManager();
		}

		public override string ToString()
		{
			return "Lifetime:PerThread";
		}
	}
	public class SingletonLifetimeManager : ContainerControlledLifetimeManager
	{
		public override string ToString()
		{
			return "Lifetime:Singleton";
		}
	}
	public class TransientLifetimeManager : LifetimeManager, IFactoryLifetimeManager, ITypeLifetimeManager
	{
		public static readonly TransientLifetimeManager Instance = new TransientLifetimeManager();

		public override bool InUse
		{
			get
			{
				return false;
			}
			set
			{
			}
		}

		protected override LifetimeManager OnCreateLifetimeManager()
		{
			return new TransientLifetimeManager();
		}

		public override string ToString()
		{
			return "Lifetime:Transient";
		}
	}
}
namespace Unity.Exceptions
{
	internal class CircularDependencyException : Exception
	{
		public CircularDependencyException(Type type, string name)
			: base($"Circular reference: Type: {type}, Name: {name}")
		{
		}
	}
}
namespace Unity.Resolution
{
	public abstract class ResolverOverride
	{
		protected Type Target;

		protected readonly Type Type;

		protected readonly string Name;

		protected ResolverOverride(string name)
		{
			Name = name;
		}

		protected ResolverOverride(Type target, Type type, string name)
		{
			Target = target;
			Type = type;
			Name = name;
		}

		public ResolverOverride OnType<T>()
		{
			Target = typeof(T);
			return this;
		}

		public ResolverOverride OnType(Type targetType)
		{
			Target = targetType;
			return this;
		}

		public virtual ResolveDelegate<TContext> GetResolver<TContext>(Type type) where TContext : IResolveContext
		{
			if (!(this is IResolve resolve))
			{
				throw new InvalidCastException("Derived type does not implement IResolve policy");
			}
			return resolve.Resolve;
		}

		public override int GetHashCode()
		{
			return ((Target?.GetHashCode() ?? 0) + (Name?.GetHashCode() ?? 0)) ^ GetType().GetHashCode();
		}

		public override bool Equals(object obj)
		{
			return this == obj as ResolverOverride;
		}

		public static bool operator ==(ResolverOverride left, ResolverOverride right)
		{
			return left?.GetHashCode() == right?.GetHashCode();
		}

		public static bool operator !=(ResolverOverride left, ResolverOverride right)
		{
			return !(left == right);
		}
	}
	public class ParameterOverrides : IEnumerable
	{
		private IList<Tuple<string, object>> _values = new List<Tuple<string, object>>();

		public void Add(string key, object value)
		{
			_values.Add(new Tuple<string, object>(key, value));
		}

		public ResolverOverride[] OnType<T>()
		{
			return _values.Select((Tuple<string, object> p) => new ParameterOverride(p.Item1, p.Item2).OnType<T>()).ToArray();
		}

		public ResolverOverride[] OnType(Type targetType)
		{
			return new ResolverOverride[0];
		}

		public IEnumerator GetEnumerator()
		{
			foreach (Tuple<string, object> value in _values)
			{
				yield return new ParameterOverride(value.Item1, value.Item2);
			}
		}
	}
	public class DependencyOverride : ResolverOverride, IEquatable<NamedType>, IResolve
	{
		protected readonly object Value;

		public DependencyOverride(Type typeToConstruct, object dependencyValue)
			: base(null, typeToConstruct, null)
		{
			Value = dependencyValue;
		}

		public DependencyOverride(string name, object dependencyValue)
			: base(null, null, name)
		{
			Value = dependencyValue;
		}

		public DependencyOverride(Type type, string name, object value)
			: base(null, type, name)
		{
			Value = value;
		}

		public DependencyOverride(Type target, Type type, string name, object value)
			: base(target, type, name)
		{
			Value = value;
		}

		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		public override bool Equals(object other)
		{
			if (other != null && other is DependencyOverride dependencyOverride)
			{
				DependencyOverride dependencyOverride2 = dependencyOverride;
				if (dependencyOverride2.Type == Type)
				{
					return dependencyOverride2.Name == Name;
				}
				return false;
			}
			return false;
		}

		public bool Equals(NamedType other)
		{
			if (other.Type == Type)
			{
				return other.Name == Name;
			}
			return false;
		}

		public object Resolve<TContext>(ref TContext context) where TContext : IResolveContext
		{
			if (Value is IResolve resolve)
			{
				return resolve.Resolve(ref context);
			}
			if (Value is IResolverFactory<Type> resolverFactory)
			{
				return resolverFactory.GetResolver<TContext>(Type)(ref context);
			}
			return Value;
		}
	}
	public class DependencyOverride<T> : DependencyOverride
	{
		public DependencyOverride(object dependencyValue)
			: base(null, typeof(T), null, dependencyValue)
		{
		}
	}
	public class FieldOverride : ResolverOverride, IEquatable<FieldInfo>, IResolve
	{
		protected readonly object Value;

		public FieldOverride(string fieldName, object fieldValue)
			: base(fieldName)
		{
			Value = fieldValue;
		}

		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		public override bool Equals(object other)
		{
			if (other != null)
			{
				if (other is FieldInfo fieldInfo)
				{
					FieldInfo other2 = fieldInfo;
					return Equals(other2);
				}
				if (other is FieldOverride fieldOverride)
				{
					FieldOverride fieldOverride2 = fieldOverride;
					if ((null == Target || fieldOverride2.Target == Target) && (null == Type || fieldOverride2.Type == Type))
					{
						if (Name != null)
						{
							return fieldOverride2.Name == Name;
						}
						return true;
					}
					return false;
				}
			}
			return base.Equals(other);
		}

		public bool Equals(FieldInfo other)
		{
			if (null != other && (null == Target || other.DeclaringType == Target) && (null == Type || other.FieldType == Type))
			{
				if (Name != null)
				{
					return other.Name == Name;
				}
				return true;
			}
			return false;
		}

		public object Resolve<TContext>(ref TContext context) where TContext : IResolveContext
		{
			if (Value is IResolve resolve)
			{
				return resolve.Resolve(ref context);
			}
			if (Value is IResolverFactory<Type> resolverFactory)
			{
				return resolverFactory.GetResolver<TContext>(Type)(ref context);
			}
			return Value;
		}
	}
	public class ParameterOverride : ResolverOverride, IEquatable<ParameterInfo>, IResolve
	{
		protected readonly object Value;

		public ParameterOverride(string parameterName, object parameterValue)
			: base(null, null, parameterName)
		{
			Value = parameterValue;
		}

		public ParameterOverride(Type parameterType, object parameterValue)
			: base(null, parameterType, null)
		{
			Value = parameterValue;
		}

		public ParameterOverride(Type parameterType, string parameterName, object parameterValue)
			: base(null, parameterType, parameterName)
		{
			Value = parameterValue;
		}

		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		public override bool Equals(object other)
		{
			if (other != null)
			{
				if (other is ParameterInfo parameterInfo)
				{
					ParameterInfo other2 = parameterInfo;
					return Equals(other2);
				}
				if (other is ParameterOverride parameterOverride)
				{
					ParameterOverride parameterOverride2 = parameterOverride;
					if ((null == Target || parameterOverride2.Target == Target) && (null == Type || parameterOverride2.Type == Type))
					{
						if (Name != null)
						{
							return parameterOverride2.Name == Name;
						}
						return true;
					}
					return false;
				}
			}
			return base.Equals(other);
		}

		public bool Equals(ParameterInfo other)
		{
			if (other != null && (null == Target || other.Member.DeclaringType == Target) && (null == Type || other.ParameterType == Type))
			{
				if (Name != null)
				{
					return other.Name == Name;
				}
				return true;
			}
			return false;
		}

		public object Resolve<TContext>(ref TContext context) where TContext : IResolveContext
		{
			if (Value is IResolve resolve)
			{
				return resolve.Resolve(ref context);
			}
			if (Value is IResolverFactory<Type> resolverFactory)
			{
				return resolverFactory.GetResolver<TContext>(Type)(ref context);
			}
			return Value;
		}
	}
	public class PropertyOverride : ResolverOverride, IEquatable<PropertyInfo>, IResolve
	{
		protected readonly object Value;

		public PropertyOverride(string propertyName, object propertyValue)
			: base(propertyName)
		{
			Value = propertyValue;
		}

		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		public override bool Equals(object other)
		{
			if (other != null)
			{
				if (other is PropertyInfo propertyInfo)
				{
					PropertyInfo other2 = propertyInfo;
					return Equals(other2);
				}
				if (other is PropertyOverride propertyOverride)
				{
					PropertyOverride propertyOverride2 = propertyOverride;
					if ((null == Target || propertyOverride2.Target == Target) && (null == Type || propertyOverride2.Type == Type))
					{
						if (Name != null)
						{
							return propertyOverride2.Name == Name;
						}
						return true;
					}
					return false;
				}
			}
			return base.Equals(other);
		}

		public bool Equals(PropertyInfo other)
		{
			if (null != other && (null == Target || other.DeclaringType == Target) && (null == Type || other.PropertyType == Type))
			{
				if (Name != null)
				{
					return other.Name == Name;
				}
				return true;
			}
			return false;
		}

		public object Resolve<TContext>(ref TContext context) where TContext : IResolveContext
		{
			if (Value is IResolve resolve)
			{
				return resolve.Resolve(ref context);
			}
			if (Value is IResolverFactory<Type> resolverFactory)
			{
				return resolverFactory.GetResolver<TContext>(Type)(ref context);
			}
			return Value;
		}
	}
	public delegate object ResolveDelegate<TContext>(ref TContext context) where TContext : IResolveContext;
	public interface IResolve
	{
		object Resolve<TContext>(ref TContext context) where TContext : IResolveContext;
	}
	public interface IResolveContext : IPolicyList
	{
		IUnityContainer Container { get; }

		Type Type { get; }

		string Name { get; }

		object Resolve(Type type, string name);
	}
	public class IResolveContextExpression<TContext> where TContext : IResolveContext
	{
		public static readonly MethodInfo ResolveMethod;

		public static readonly ParameterExpression Context;

		public static readonly MemberExpression Type;

		public static readonly MemberExpression Name;

		public static readonly MemberExpression Container;

		static IResolveContextExpression()
		{
			ResolveMethod = typeof(IResolveContext).GetTypeInfo().GetDeclaredMethods("Resolve").First();
			TypeInfo typeInfo = typeof(TContext).GetTypeInfo();
			Context = Expression.Parameter(typeof(ResolveDelegate<TContext>).GetTypeInfo().GetDeclaredMethod("Invoke").GetParameters()[0].ParameterType, "context");
			Type = Expression.MakeMemberAccess(Context, typeInfo.GetDeclaredProperty("Type"));
			Name = Expression.MakeMemberAccess(Context, typeInfo.GetDeclaredProperty("Name"));
			Container = Expression.MakeMemberAccess(Context, typeInfo.GetDeclaredProperty("Container"));
		}
	}
	public delegate ResolveDelegate<TContext> ResolverFactory<TContext>(Type type) where TContext : IResolveContext;
	public interface IResolverFactory<in TMemberInfo>
	{
		ResolveDelegate<TContext> GetResolver<TContext>(TMemberInfo info) where TContext : IResolveContext;
	}
	public struct NamedType
	{
		public Type Type;

		public string Name;

		public override int GetHashCode()
		{
			return GetHashCode(Type, Name);
		}

		public static int GetHashCode(Type type, string name)
		{
			return ((type?.GetHashCode() ?? 0) + 37) ^ ((name?.GetHashCode() ?? 0) + 17);
		}

		public static int GetHashCode(int typeHash, int nameHash)
		{
			return (typeHash + 37) ^ (nameHash + 17);
		}

		public override bool Equals(object obj)
		{
			if (obj is NamedType namedType && Type == namedType.Type && Name == namedType.Name)
			{
				return true;
			}
			return false;
		}

		public static bool operator ==(NamedType obj1, NamedType obj2)
		{
			if (obj1.Type == obj2.Type)
			{
				return obj1.Name == obj2.Name;
			}
			return false;
		}

		public static bool operator !=(NamedType obj1, NamedType obj2)
		{
			if (!(obj1.Type != obj2.Type))
			{
				return obj1.Name != obj2.Name;
			}
			return true;
		}

		public override string ToString()
		{
			return "Type: " + Type?.Name + ",  Name: " + Name;
		}
	}
}
namespace Unity.Injection
{
	public abstract class GenericBase : ParameterValue, IResolverFactory<Type>, IResolverFactory<ParameterInfo>
	{
		private readonly string _name;

		private readonly bool _isArray;

		private readonly string _genericParameterName;

		public virtual string ParameterTypeName => _genericParameterName;

		protected GenericBase(string genericParameterName)
			: this(genericParameterName, null)
		{
		}

		protected GenericBase(string genericParameterName, string resolutionName)
		{
			if (genericParameterName == null)
			{
				throw new ArgumentNullException("genericParameterName");
			}
			if (genericParameterName.EndsWith("[]", StringComparison.Ordinal) || genericParameterName.EndsWith("()", StringComparison.Ordinal))
			{
				_genericParameterName = genericParameterName.Replace("[]", string.Empty).Replace("()", string.Empty);
				_isArray = true;
			}
			else
			{
				_genericParameterName = genericParameterName;
				_isArray = false;
			}
			_name = resolutionName;
		}

		public override bool Equals(Type type)
		{
			Type type2 = type ?? throw new ArgumentNullException("type");
			if (!_isArray)
			{
				if (type2.GetTypeInfo().IsGenericParameter)
				{
					return type2.GetTypeInfo().Name == _genericParameterName;
				}
				return false;
			}
			if (type2.IsArray && type2.GetElementType().GetTypeInfo().IsGenericParameter)
			{
				return type2.GetElementType().GetTypeInfo().Name == _genericParameterName;
			}
			return false;
		}

		public virtual ResolveDelegate<TContext> GetResolver<TContext>(Type type) where TContext : IResolveContext
		{
			return GetResolver<TContext>(type, _name);
		}

		public virtual ResolveDelegate<TContext> GetResolver<TContext>(ParameterInfo info) where TContext : IResolveContext
		{
			Type parameterType = info.ParameterType;
			return GetResolver<TContext>(parameterType, _name);
		}

		protected virtual ResolveDelegate<TContext> GetResolver<TContext>(Type type, string name) where TContext : IResolveContext
		{
			return delegate(ref TContext context)
			{
				return context.Resolve(type, name);
			};
		}
	}
	public static class InjectionMatching
	{
		public static bool MatchMemberInfo(this object[] data, MethodBase info)
		{
			ParameterInfo[] parameters = info.GetParameters();
			if (((data != null) ? data.Length : 0) != parameters.Length)
			{
				return false;
			}
			for (int i = 0; i < ((data != null) ? data.Length : 0); i++)
			{
				if (!((data != null) ? data[i] : null).Matches(parameters[i].ParameterType))
				{
					return false;
				}
			}
			return true;
		}

		public static bool Matches(this object data, Type match)
		{
			if (data != null)
			{
				if (data is IEquatable<Type> equatable)
				{
					return equatable.Equals(match);
				}
				if (data is Type type)
				{
					return type.MatchesType(match);
				}
			}
			return data.MatchesObject(match);
		}

		public static bool MatchesType(this Type type, Type match)
		{
			if (null == type)
			{
				return true;
			}
			if (match.IsAssignableFrom(type))
			{
				return true;
			}
			if ((type.IsArray || typeof(Array) == type) && (match.IsArray || match == typeof(Array)))
			{
				return true;
			}
			if (type.IsGenericType && type.IsGenericTypeDefinition && match.IsGenericType && type.GetGenericTypeDefinition() == match.GetGenericTypeDefinition())
			{
				return true;
			}
			return false;
		}

		public static bool MatchesObject(this object parameter, Type match)
		{
			Type type = ((parameter is Type) ? typeof(Type) : parameter?.GetType());
			if (null == type)
			{
				return true;
			}
			if (match.IsAssignableFrom(type))
			{
				return true;
			}
			if ((type.IsArray || typeof(Array) == type) && (match.IsArray || match == typeof(Array)))
			{
				return true;
			}
			if (type.IsGenericType && type.IsGenericTypeDefinition && match.IsGenericType && type.GetGenericTypeDefinition() == match.GetGenericTypeDefinition())
			{
				return true;
			}
			return false;
		}

		public static string Signature(this object[] data)
		{
			return string.Join(", ", data?.Select((object d) => d.ToString()) ?? Enumerable.Empty<string>());
		}
	}
	public abstract class InjectionMember
	{
		public virtual bool BuildRequired => false;

		public virtual void AddPolicies<TContext, TPolicySet>(Type registeredType, Type mappedToType, string name, ref TPolicySet policies) where TContext : IResolveContext where TPolicySet : IPolicySet
		{
		}
	}
	public abstract class InjectionMember<TMemberInfo, TData> : InjectionMember, IEquatable<TMemberInfo> where TMemberInfo : MemberInfo
	{
		protected const string NoMatchFound = "No member matching data has been found.";

		protected TMemberInfo Selection { get; set; }

		public string Name { get; }

		public virtual TData Data { get; }

		public bool IsInitialized => (MemberInfo?)null != (MemberInfo?)Selection;

		public override bool BuildRequired => true;

		protected InjectionMember(string name, TData data)
		{
			Name = name;
			Data = data;
		}

		protected InjectionMember(TMemberInfo info, TData data)
		{
			Selection = info;
			Name = info.Name;
			Data = data;
		}

		public abstract TMemberInfo MemberInfo(Type type);

		public abstract IEnumerable<TMemberInfo> DeclaredMembers(Type type);

		public virtual bool Equals(TMemberInfo other)
		{
			return Selection?.Equals(other) ?? false;
		}

		public override bool Equals(object obj)
		{
			if (obj != null)
			{
				if (obj is TMemberInfo val)
				{
					TMemberInfo other = val;
					return Equals(other);
				}
				if (obj is IEquatable<TMemberInfo> equatable)
				{
					return equatable.Equals(Selection);
				}
			}
			return false;
		}

		public override int GetHashCode()
		{
			return Selection?.GetHashCode() ?? 0;
		}

		public override void AddPolicies<TContext, TPolicySet>(Type registeredType, Type mappedToType, string name, ref TPolicySet policies)
		{
			Func<Type, InjectionMember, TMemberInfo> func = policies.Get<Func<Type, InjectionMember, TMemberInfo>>() ?? new Func<Type, InjectionMember, TMemberInfo>(SelectMember);
			Selection = func(mappedToType, this);
		}

		protected virtual TMemberInfo SelectMember(Type type, InjectionMember member)
		{
			throw new NotImplementedException();
		}
	}
	public abstract class MemberInfoBase<TMemberInfo> : InjectionMember<TMemberInfo, object> where TMemberInfo : MemberInfo
	{
		protected abstract Type MemberType { get; }

		protected MemberInfoBase(string name, object data)
			: base(name, data)
		{
		}

		public override TMemberInfo MemberInfo(Type type)
		{
			if (base.Selection.DeclaringType != null && !base.Selection.DeclaringType.IsGenericType && !base.Selection.DeclaringType.ContainsGenericParameters)
			{
				return base.Selection;
			}
			return DeclaredMember(type, base.Selection.Name);
		}

		protected override TMemberInfo SelectMember(Type type, InjectionMember _)
		{
			foreach (TMemberInfo item in DeclaredMembers(type))
			{
				if (!(item.Name != base.Name))
				{
					return item;
				}
			}
			throw new ArgumentException("No member matching data has been found.");
		}

		protected abstract TMemberInfo DeclaredMember(Type type, string name);
	}
	public abstract class MethodBase<TMemberInfo> : InjectionMember<TMemberInfo, object[]> where TMemberInfo : MethodBase
	{
		protected MethodBase(string name, params object[] arguments)
			: base(name, arguments)
		{
		}

		protected MethodBase(TMemberInfo info, params object[] arguments)
			: base(info, arguments)
		{
		}

		public override TMemberInfo MemberInfo(Type type)
		{
			bool num = (from p in base.Selection.GetParameters()
				select p.ParameterType.GetTypeInfo()).Any((TypeInfo i) => i.IsGenericType && i.ContainsGenericParameters);
			TypeInfo typeInfo = base.Selection.DeclaringType.GetTypeInfo();
			if (!num && (!typeInfo.IsGenericType || !typeInfo.ContainsGenericParameters))
			{
				return base.Selection;
			}
			foreach (TMemberInfo item in DeclaredMembers(type))
			{
				if (item.MetadataToken == base.Selection.MetadataToken)
				{
					return item;
				}
			}
			throw new InvalidOperationException($"Error selecting member on type {type}");
		}
	}
	public abstract class ParameterBase : ParameterValue
	{
		private readonly Type _type;

		public virtual Type ParameterType => _type;

		protected ParameterBase(Type parameterType = null)
		{
			_type = parameterType;
		}

		public override bool Equals(Type t)
		{
			if (null == _type)
			{
				return true;
			}
			TypeInfo typeInfo = (t ?? throw new ArgumentNullException("t")).GetTypeInfo();
			TypeInfo typeInfo2 = _type.GetTypeInfo();
			if (typeInfo.IsGenericType && typeInfo.ContainsGenericParameters && typeInfo2.IsGenericType && typeInfo2.ContainsGenericParameters)
			{
				return t.GetGenericTypeDefinition() == _type.GetGenericTypeDefinition();
			}
			return typeInfo.IsAssignableFrom(typeInfo2);
		}
	}
	public abstract class ParameterValue : IEquatable<Type>
	{
		public abstract bool Equals(Type type);
	}
	public class InjectionConstructor : MethodBase<ConstructorInfo>
	{
		public InjectionConstructor(params object[] arguments)
			: base((string)null, arguments)
		{
		}

		public InjectionConstructor(ConstructorInfo info, params object[] arguments)
			: base((string)null, arguments)
		{
			base.Selection = info;
		}

		protected override ConstructorInfo SelectMember(Type type, InjectionMember _)
		{
			foreach (ConstructorInfo item in DeclaredMembers(type))
			{
				if (Data.MatchMemberInfo(item))
				{
					return item;
				}
			}
			throw new ArgumentException("No member matching data has been found.");
		}

		public override IEnumerable<ConstructorInfo> DeclaredMembers(Type type)
		{
			return type.GetTypeInfo().DeclaredConstructors.Where((ConstructorInfo ctor) => !ctor.IsFamily && !ctor.IsPrivate && !ctor.IsStatic);
		}

		public override string ToString()
		{
			return "Invoke.Constructor(" + Data.Signature() + ")";
		}
	}
	[Obsolete("InjectionFactory has been deprecated and will be removed in next release. Please use IUnityContainer.RegisterFactory(...) method instead.", false)]
	public class InjectionFactory : InjectionMember
	{
		internal sealed class InternalPerResolveLifetimeManager : PerResolveLifetimeManager
		{
			public InternalPerResolveLifetimeManager(object obj)
			{
				value = obj;
				InUse = true;
			}
		}

		private readonly Func<IUnityContainer, Type, string, object> _factoryFunc;

		public InjectionFactory(Func<IUnityContainer, object> factoryFunc)
		{
			if (factoryFunc == null)
			{
				throw new ArgumentNullException("factoryFunc");
			}
			_factoryFunc = (IUnityContainer c, Type t, string s) => factoryFunc(c);
		}

		public InjectionFactory(Func<IUnityContainer, Type, string, object> factoryFunc)
		{
			_factoryFunc = factoryFunc ?? throw new ArgumentNullException("factoryFunc");
		}

		public override void AddPolicies<TContext, TPolicySet>(Type registeredType, Type mappedToType, string name, ref TPolicySet policies)
		{
			if (null != mappedToType && mappedToType != registeredType)
			{
				throw new InvalidOperationException("Registration where both MappedToType and InjectionFactory are set is not supported");
			}
			if (policies.Get(typeof(LifetimeManager)) is PerResolveLifetimeManager)
			{
				policies.Set(typeof(ResolveDelegate<TContext>), CreatePerResolveLegacyPolicy());
			}
			else
			{
				policies.Set(typeof(ResolveDelegate<TContext>), CreateLegacyPolicy());
			}
			ResolveDelegate<TContext> CreateLegacyPolicy()
			{
				return delegate(ref TContext c)
				{
					return _factoryFunc(c.Container, c.Type, c.Name);
				};
			}
			ResolveDelegate<TContext> CreatePerResolveLegacyPolicy()
			{
				return delegate(ref TContext context)
				{
					object obj = _factoryFunc(context.Container, context.Type, context.Name);
					context.Set(policy: new InternalPerResolveLifetimeManager(obj), type: context.Type, name: context.Name, policyInterface: typeof(LifetimeManager));
					return obj;
				};
			}
		}
	}
	public class InjectionField : MemberInfoBase<FieldInfo>
	{
		protected override Type MemberType => base.Selection.FieldType;

		public InjectionField(string name, ResolutionOption option = ResolutionOption.Required)
			: base(name, (object)((ResolutionOption.Optional == option) ? ((DependencyResolutionAttribute)OptionalDependencyAttribute.Instance) : ((DependencyResolutionAttribute)DependencyAttribute.Instance)))
		{
		}

		public InjectionField(string name, object value)
			: base(name, value)
		{
		}

		protected override FieldInfo DeclaredMember(Type type, string name)
		{
			return type.GetField(base.Selection.Name);
		}

		public override IEnumerable<FieldInfo> DeclaredMembers(Type type)
		{
			foreach (FieldInfo declaredField in type.GetDeclaredFields())
			{
				if (!declaredField.IsFamily && !declaredField.IsPrivate && !declaredField.IsInitOnly && !declaredField.IsStatic)
				{
					yield return declaredField;
				}
			}
		}

		public override string ToString()
		{
			if (!(Data is DependencyResolutionAttribute))
			{
				return $"Inject.Field('{base.Name}', {Data})";
			}
			return "Resolve.Field('" + base.Name + "')";
		}
	}
	public class InjectionMethod : MethodBase<MethodInfo>
	{
		public InjectionMethod(string name, params object[] arguments)
			: base(name, arguments)
		{
		}

		protected override MethodInfo SelectMember(Type type, InjectionMember _)
		{
			object[] data = Data;
			bool flag = data == null || data.Length == 0;
			foreach (MethodInfo item in DeclaredMembers(type))
			{
				if (base.Name != null)
				{
					if (base.Name != item.Name)
					{
						continue;
					}
					if (flag)
					{
						return item;
					}
				}
				if (Data.MatchMemberInfo(item))
				{
					return item;
				}
			}
			throw new ArgumentException("No member matching data has been found.");
		}

		public override IEnumerable<MethodInfo> DeclaredMembers(Type type)
		{
			foreach (MethodInfo declaredMethod in type.GetDeclaredMethods())
			{
				if (!declaredMethod.IsFamily && !declaredMethod.IsPrivate && !declaredMethod.IsStatic && declaredMethod.Name == base.Name)
				{
					yield return declaredMethod;
				}
			}
		}

		public override string ToString()
		{
			return "Invoke.Method('" + base.Name + "', " + Data.Signature() + ")";
		}
	}
	public class InjectionProperty : MemberInfoBase<PropertyInfo>
	{
		protected override Type MemberType => base.Selection.PropertyType;

		public InjectionProperty(string name, ResolutionOption option = ResolutionOption.Required)
			: base(name, (object)((ResolutionOption.Optional == option) ? ((DependencyResolutionAttribute)OptionalDependencyAttribute.Instance) : ((DependencyResolutionAttribute)DependencyAttribute.Instance)))
		{
		}

		public InjectionProperty(string name, object value)
			: base(name, value)
		{
		}

		protected override PropertyInfo DeclaredMember(Type type, string name)
		{
			return DeclaredMembers(type).FirstOrDefault((PropertyInfo p) => p.Name == base.Selection.Name);
		}

		public override IEnumerable<PropertyInfo> DeclaredMembers(Type type)
		{
			foreach (PropertyInfo declaredProperty in type.GetDeclaredProperties())
			{
				if (declaredProperty.CanWrite && declaredProperty.GetIndexParameters().Length == 0)
				{
					MethodInfo setMethod = declaredProperty.GetSetMethod(nonPublic: true);
					if (!setMethod.IsPrivate && !setMethod.IsFamily)
					{
						yield return declaredProperty;
					}
				}
			}
		}

		public override string ToString()
		{
			if (!(Data is DependencyResolutionAttribute))
			{
				return $"Inject.Property('{base.Name}', {Data})";
			}
			return "Resolve.Property('" + base.Name + "')";
		}
	}
	public class GenericParameter : GenericBase
	{
		public GenericParameter(string genericParameterName)
			: base(genericParameterName)
		{
		}

		public GenericParameter(string genericParameterName, string name)
			: base(genericParameterName, name)
		{
		}
	}
	public class GenericResolvedArrayParameter : GenericBase
	{
		private delegate object Resolver<TContext>(ref TContext context, object[] values) where TContext : IResolveContext;

		private readonly object[] _values;

		private static readonly MethodInfo ResolverMethod = typeof(GenericResolvedArrayParameter).GetTypeInfo().GetDeclaredMethod("DoResolve");

		public override string ParameterTypeName => base.ParameterTypeName + "[]";

		public GenericResolvedArrayParameter(string genericParameterName, params object[] elementValues)
			: base(genericParameterName)
		{
			_values = elementValues;
		}

		public override bool Equals(Type type)
		{
			Type type2 = type ?? throw new ArgumentNullException("type");
			if (!type2.IsArray || type2.GetArrayRank() != 1)
			{
				return false;
			}
			Type elementType = type2.GetElementType();
			if (elementType.GetTypeInfo().IsGenericParameter)
			{
				return elementType.GetTypeInfo().Name == base.ParameterTypeName;
			}
			return false;
		}

		protected override ResolveDelegate<TContext> GetResolver<TContext>(Type type, string name)
		{
			Type elementType = type.GetElementType();
			Resolver<TContext> resolverMethod = (Resolver<TContext>)ResolverMethod.MakeGenericMethod(typeof(TContext), elementType).CreateDelegate(typeof(Resolver<TContext>));
			object[] values = _values.Select(delegate(object value)
			{
				if (value != null)
				{
					if (value is IResolverFactory<Type> resolverFactory)
					{
						return resolverFactory.GetResolver<TContext>(elementType);
					}
					if (value is Type && typeof(Type) != elementType)
					{
						return (ResolveDelegate<TContext>)delegate(ref TContext context)
						{
							return context.Resolve(elementType, null);
						};
					}
				}
				return value;
			}).ToArray();
			return delegate(ref TContext context)
			{
				return resolverMethod(ref context, values);
			};
		}

		private static object DoResolve<TContext, TElement>(ref TContext context, object[] values) where TContext : IResolveContext
		{
			TElement[] array = new TElement[values.Length];
			for (int i = 0; i < values.Length; i++)
			{
				array[i] = (TElement)ResolveValue(ref context, values[i]);
			}
			return array;
			static object ResolveValue(ref TContext c, object value)
			{
				if (value != null)
				{
					if (value is ResolveDelegate<TContext> resolveDelegate)
					{
						return resolveDelegate(ref c);
					}
					if (value is IResolve resolve)
					{
						return resolve.Resolve(ref c);
					}
				}
				return value;
			}
		}
	}
	public class InjectionParameter : ParameterBase, IResolve
	{
		private readonly object _value;

		public InjectionParameter(object value)
			: base((value ?? throw new ArgumentNullException("value")).GetType())
		{
			_value = value;
		}

		public InjectionParameter(Type parameterType, object parameterValue)
			: base(parameterType)
		{
			_value = parameterValue;
		}

		public object Resolve<TContext>(ref TContext context) where TContext : IResolveContext
		{
			return _value;
		}
	}
	public class InjectionParameter<TParameter> : InjectionParameter
	{
		public InjectionParameter(TParameter value)
			: base(typeof(TParameter), value)
		{
		}
	}
	public class OptionalGenericParameter : GenericBase
	{
		public OptionalGenericParameter(string genericParameterName)
			: base(genericParameterName)
		{
		}

		public OptionalGenericParameter(string genericParameterName, string name)
			: base(genericParameterName, name)
		{
		}

		protected override ResolveDelegate<TContext> GetResolver<TContext>(Type type, string name)
		{
			return delegate(ref TContext context)
			{
				try
				{
					return context.Resolve(type, name);
				}
				catch (Exception ex) when (!(ex is CircularDependencyException))
				{
					return null;
				}
			};
		}
	}
	public class OptionalParameter : ParameterBase, IResolverFactory<Type>, IResolverFactory<ParameterInfo>
	{
		private readonly string _name;

		public OptionalParameter()
		{
		}

		public OptionalParameter(Type type)
			: base(type)
		{
		}

		public OptionalParameter(string name)
		{
			_name = name;
		}

		public OptionalParameter(Type type, string name)
			: base(type)
		{
			_name = name;
		}

		public ResolveDelegate<TContext> GetResolver<TContext>(Type type) where TContext : IResolveContext
		{
			return delegate(ref TContext c)
			{
				try
				{
					return c.Resolve(type, _name);
				}
				catch (Exception ex) when (!(ex is CircularDependencyException))
				{
					return null;
				}
			};
		}

		public ResolveDelegate<TContext> GetResolver<TContext>(ParameterInfo info) where TContext : IResolveContext
		{
			object value = (info.HasDefaultValue ? info.DefaultValue : null);
			if (null == ParameterType || (ParameterType.IsGenericType && ParameterType.ContainsGenericParameters) || (ParameterType.IsArray && ParameterType.GetElementType().IsGenericParameter) || ParameterType.IsGenericParameter)
			{
				Type type = info.ParameterType;
				return delegate(ref TContext c)
				{
					try
					{
						return c.Resolve(type, _name);
					}
					catch (Exception ex2) when (!(ex2 is CircularDependencyException))
					{
						return value;
					}
				};
			}
			return delegate(ref TContext c)
			{
				try
				{
					return c.Resolve(ParameterType, _name);
				}
				catch (Exception ex) when (!(ex is CircularDependencyException))
				{
					return value;
				}
			};
		}
	}
	public class OptionalParameter<T> : OptionalParameter
	{
		public OptionalParameter()
			: base(typeof(T))
		{
		}

		public OptionalParameter(string name)
			: base(typeof(T), name)
		{
		}
	}
	public class ResolvedArrayParameter : ParameterBase, IResolverFactory<Type>, IResolverFactory<ParameterInfo>
	{
		private delegate object Resolver<TContext>(ref TContext context, object[] values) where TContext : IResolveContext;

		private readonly object[] _values;

		private readonly Type _elementType;

		private static readonly MethodInfo ResolverMethod = typeof(GenericResolvedArrayParameter).GetTypeInfo().GetDeclaredMethod("DoResolve");

		public ResolvedArrayParameter(Type elementType, params object[] elementValues)
			: this(elementType.MakeArrayType(), elementType, elementValues)
		{
		}

		protected ResolvedArrayParameter(Type arrayParameterType, Type elementType, params object[] elementValues)
			: base(arrayParameterType)
		{
			_elementType = elementType ?? throw new ArgumentNullException("elementType");
			_values = elementValues;
			foreach (object obj in elementValues)
			{
				if ((!(obj is IEquatable<Type> equatable) || !equatable.Equals(elementType)) && (!(obj is Type type) || !(type == _elementType)) && !_elementType.IsAssignableFrom(obj?.GetType()))
				{
					throw new InvalidOperationException($"The type {obj?.GetType()} cannot be assigned to variables of type {elementType}.");
				}
			}
		}

		public ResolveDelegate<TContext> GetResolver<TContext>(Type type) where TContext : IResolveContext
		{
			Type elementType = ((!_elementType.IsArray) ? _elementType : _elementType.GetArrayParameterType(type.GetTypeInfo().GenericTypeArguments));
			Resolver<TContext> resolverMethod = (Resolver<TContext>)ResolverMethod.MakeGenericMethod(typeof(TContext), elementType).CreateDelegate(typeof(Resolver<TContext>));
			object[] values = _values.Select(delegate(object value)
			{
				if (value != null)
				{
					if (value is IResolverFactory<Type> resolverFactory)
					{
						return resolverFactory.GetResolver<TContext>(type);
					}
					if (value is Type && typeof(Type) != elementType)
					{
						return (ResolveDelegate<TContext>)delegate(ref TContext context)
						{
							return context.Resolve(elementType, null);
						};
					}
				}
				return value;
			}).ToArray();
			return delegate(ref TContext context)
			{
				return resolverMethod(ref context, values);
			};
		}

		public ResolveDelegate<TContext> GetResolver<TContext>(ParameterInfo info) where TContext : IResolveContext
		{
			Type elementType = (info.ParameterType.IsArray ? info.ParameterType.GetElementType() : _elementType);
			Resolver<TContext> resolverMethod = (Resolver<TContext>)ResolverMethod.MakeGenericMethod(typeof(TContext), elementType).CreateDelegate(typeof(Resolver<TContext>));
			object[] values = _values.Select(delegate(object value)
			{
				if (value != null)
				{
					if (value is IResolverFactory<Type> resolverFactory)
					{
						return resolverFactory.GetResolver<TContext>(elementType);
					}
					if (value is Type && typeof(Type) != elementType)
					{
						return (ResolveDelegate<TContext>)delegate(ref TContext context)
						{
							return context.Resolve(elementType, null);
						};
					}
				}
				return value;
			}).ToArray();
			return delegate(ref TContext context)
			{
				return resolverMethod(ref context, values);
			};
		}

		private static object DoResolve<TContext, TElement>(ref TContext context, object[] values) where TContext : IResolveContext
		{
			TElement[] array = new TElement[values.Length];
			for (int i = 0; i < values.Length; i++)
			{
				array[i] = (TElement)ResolveValue(ref context, values[i]);
			}
			return array;
			static object ResolveValue(ref TContext c, object value)
			{
				if (value != null)
				{
					if (value is ResolveDelegate<TContext> resolveDelegate)
					{
						return resolveDelegate(ref c);
					}
					if (value is IResolve resolve)
					{
						return resolve.Resolve(ref c);
					}
				}
				return value;
			}
		}
	}
	public class ResolvedArrayParameter<TElement> : ResolvedArrayParameter
	{
		public ResolvedArrayParameter(params object[] elementValues)
			: base(typeof(TElement[]), typeof(TElement), elementValues)
		{
		}
	}
	public class ResolvedParameter : ParameterBase, IResolverFactory<Type>, IResolverFactory<ParameterInfo>
	{
		private readonly string _name;

		public ResolvedParameter()
		{
		}

		public ResolvedParameter(Type parameterType)
			: base(parameterType)
		{
		}

		public ResolvedParameter(string name)
		{
			_name = name;
		}

		public ResolvedParameter(Type parameterType, string name)
			: base(parameterType)
		{
			_name = name;
		}

		public ResolveDelegate<TContext> GetResolver<TContext>(Type type) where TContext : IResolveContext
		{
			if (null == ParameterType || (ParameterType.IsGenericType && ParameterType.ContainsGenericParameters) || (ParameterType.IsArray && ParameterType.GetElementType().IsGenericParameter) || ParameterType.IsGenericParameter)
			{
				return delegate(ref TContext c)
				{
					return c.Resolve(type, _name);
				};
			}
			return delegate(ref TContext c)
			{
				return c.Resolve(ParameterType, _name);
			};
		}

		public ResolveDelegate<TContext> GetResolver<TContext>(ParameterInfo info) where TContext : IResolveContext
		{
			if (null == ParameterType || (ParameterType.IsGenericType && ParameterType.ContainsGenericParameters) || (ParameterType.IsArray && Par

Unity.Container.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Unity.Builder;
using Unity.Events;
using Unity.Exceptions;
using Unity.Extension;
using Unity.Factories;
using Unity.Injection;
using Unity.Lifetime;
using Unity.Policy;
using Unity.Processors;
using Unity.Registration;
using Unity.Resolution;
using Unity.Storage;
using Unity.Strategies;
using Unity.Utility;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CLSCompliant(true)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Unity Open Source Project")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © Unity Container Project 2018")]
[assembly: AssemblyDescription("Unity Core Engine")]
[assembly: AssemblyFileVersion("5.11.1.0")]
[assembly: AssemblyInformationalVersion("5.11.1+626e5550a8f5be33f170ccf48561e06d76ae2e1c")]
[assembly: AssemblyProduct("Unity.Container")]
[assembly: AssemblyTitle("Unity.Container")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.11.1.0")]
[module: UnverifiableCode]
namespace Unity
{
	public class DefaultLifetime : UnityContainerExtension
	{
		public ITypeLifetimeManager TypeDefaultLifetime
		{
			get
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Expected O, but got Unknown
				return (ITypeLifetimeManager)((UnityContainer)(object)base.Container).TypeLifetimeManager;
			}
			set
			{
				//IL_000c: 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_0025: Expected O, but got Unknown
				UnityContainer obj = (UnityContainer)(object)base.Container;
				LifetimeManager val = (LifetimeManager)value;
				if ((int)val == 0)
				{
					throw new ArgumentNullException("Type Lifetime Manager can not be null");
				}
				obj.TypeLifetimeManager = val;
			}
		}

		public IInstanceLifetimeManager InstanceDefaultLifetime
		{
			get
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Expected O, but got Unknown
				return (IInstanceLifetimeManager)((UnityContainer)(object)base.Container).InstanceLifetimeManager;
			}
			set
			{
				//IL_000c: 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_0025: Expected O, but got Unknown
				UnityContainer obj = (UnityContainer)(object)base.Container;
				LifetimeManager val = (LifetimeManager)value;
				if ((int)val == 0)
				{
					throw new ArgumentNullException("Instance Lifetime Manager can not be null");
				}
				obj.InstanceLifetimeManager = val;
			}
		}

		public IFactoryLifetimeManager FactoryDefaultLifetime
		{
			get
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Expected O, but got Unknown
				return (IFactoryLifetimeManager)((UnityContainer)(object)base.Container).FactoryLifetimeManager;
			}
			set
			{
				//IL_000c: 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_0025: Expected O, but got Unknown
				UnityContainer obj = (UnityContainer)(object)base.Container;
				LifetimeManager val = (LifetimeManager)value;
				if ((int)val == 0)
				{
					throw new ArgumentNullException("Factory Lifetime Manager can not be null");
				}
				obj.FactoryLifetimeManager = val;
			}
		}

		protected override void Initialize()
		{
		}
	}
	public class Diagnostic : UnityContainerExtension
	{
		protected override void Initialize()
		{
			((UnityContainer)(object)base.Container).SetDefaultPolicies = UnityContainer.SetDiagnosticPolicies;
			((UnityContainer)(object)base.Container).SetDefaultPolicies((UnityContainer)(object)base.Container);
		}
	}
	public static class DiagnosticExtensions
	{
		[Conditional("DEBUG")]
		public static void EnableDebugDiagnostic(this UnityContainer container)
		{
			if (container == null)
			{
				throw new ArgumentNullException("container");
			}
			container.AddExtension(new Diagnostic());
		}

		public static UnityContainer EnableDiagnostic(this UnityContainer container)
		{
			if (container == null)
			{
				throw new ArgumentNullException("container");
			}
			container.AddExtension(new Diagnostic());
			return container;
		}
	}
	public static class ExtensionExtensions
	{
		public static IUnityContainer AddExtension(this IUnityContainer container, IUnityContainerExtensionConfigurator extension)
		{
			return (((UnityContainer)(object)container) ?? throw new ArgumentNullException("container")).AddExtension(extension);
		}

		public static object Configure(this IUnityContainer container, Type configurationInterface)
		{
			return (((UnityContainer)(object)container) ?? throw new ArgumentNullException("container")).Configure(configurationInterface);
		}

		public static IUnityContainer AddNewExtension<TExtension>(this IUnityContainer container) where TExtension : UnityContainerExtension
		{
			TExtension extension = UnityContainerExtensions.Resolve<TExtension>(container ?? throw new ArgumentNullException("container"), Array.Empty<ResolverOverride>());
			return container.AddExtension(extension);
		}

		public static TConfigurator Configure<TConfigurator>(this IUnityContainer container) where TConfigurator : IUnityContainerExtensionConfigurator
		{
			return (TConfigurator)(container ?? throw new ArgumentNullException("container")).Configure(typeof(TConfigurator));
		}
	}
	public class ForceActivation : UnityContainerExtension
	{
		protected override void Initialize()
		{
			UnityContainer unityContainer = (UnityContainer)(object)base.Container;
			unityContainer._buildStrategy = unityContainer.ResolvingFactory;
			unityContainer.Defaults.Set(typeof(ResolveDelegateFactory), (object)unityContainer._buildStrategy);
		}
	}
	public class ForceCompillation : UnityContainerExtension
	{
		protected override void Initialize()
		{
			UnityContainer unityContainer = (UnityContainer)(object)base.Container;
			unityContainer._buildStrategy = unityContainer.CompilingFactory;
			unityContainer.Defaults.Set(typeof(ResolveDelegateFactory), (object)unityContainer._buildStrategy);
		}
	}
	[DebuggerDisplay("{DebugName()}")]
	[DebuggerTypeProxy(typeof(UnityContainerDebugProxy))]
	[CLSCompliant(true)]
	[SecuritySafeCritical]
	public class UnityContainer : IUnityContainer, IDisposable
	{
		private class ContainerContext : ExtensionContext, IPolicyList
		{
			private readonly object syncRoot = new object();

			private readonly UnityContainer _container;

			public override IUnityContainer Container => (IUnityContainer)(object)_container;

			public override IStagedStrategyChain<BuilderStrategy, UnityBuildStage> Strategies => _container._strategies;

			public override IStagedStrategyChain<MemberProcessor, BuilderStage> BuildPlanStrategies => _container._processors;

			public override IPolicyList Policies { get; }

			public override ILifetimeContainer Lifetime => (ILifetimeContainer)(object)_container.LifetimeContainer;

			public override event EventHandler<RegisterEventArgs> Registering
			{
				add
				{
					_container.Registering += value;
				}
				remove
				{
					_container.Registering -= value;
				}
			}

			public override event EventHandler<RegisterInstanceEventArgs> RegisteringInstance
			{
				add
				{
					_container.RegisteringInstance += value;
				}
				remove
				{
					_container.RegisteringInstance -= value;
				}
			}

			public override event EventHandler<ChildContainerCreatedEventArgs> ChildContainerCreated
			{
				add
				{
					_container.ChildContainerCreated += value;
				}
				remove
				{
					_container.ChildContainerCreated -= value;
				}
			}

			public ContainerContext(UnityContainer container)
			{
				_container = container ?? throw new ArgumentNullException("container");
				Policies = (IPolicyList)(object)this;
			}

			public virtual void ClearAll()
			{
			}

			public virtual object Get(Type type, Type policyInterface)
			{
				return _container.GetPolicy(type, "ALL", policyInterface);
			}

			public virtual object Get(Type type, string name, Type policyInterface)
			{
				return _container.GetPolicy(type, name, policyInterface);
			}

			public virtual void Set(Type type, Type policyInterface, object policy)
			{
				_container.SetPolicy(type, "ALL", policyInterface, policy);
			}

			public virtual void Set(Type type, string name, Type policyInterface, object policy)
			{
				_container.SetPolicy(type, name, policyInterface, policy);
			}

			public virtual void Clear(Type type, string name, Type policyInterface)
			{
			}
		}

		internal class UnityContainerDebugProxy
		{
			private readonly IUnityContainer _container;

			public string Id { get; }

			public IEnumerable<IContainerRegistration> Registrations => _container.Registrations;

			public UnityContainerDebugProxy(IUnityContainer container)
			{
				_container = container;
				Id = ((object)container).GetHashCode().ToString();
			}
		}

		internal delegate object GetPolicyDelegate(Type type, string name, Type policyInterface);

		internal delegate void SetPolicyDelegate(Type type, string name, Type policyInterface, object policy);

		internal delegate void ClearPolicyDelegate(Type type, string name, Type policyInterface);

		private class RegistrationContext : IPolicyList
		{
			private readonly InternalRegistration _registration;

			private readonly UnityContainer _container;

			private readonly Type _type;

			private readonly string _name;

			internal RegistrationContext(UnityContainer container, Type type, string name, InternalRegistration registration)
			{
				_registration = registration;
				_container = container;
				_type = type;
				_name = name;
			}

			public object Get(Type type, Type policyInterface)
			{
				if (_type != type)
				{
					return _container.GetPolicy(type, "ALL", policyInterface);
				}
				return _registration.Get(policyInterface);
			}

			public object Get(Type type, string name, Type policyInterface)
			{
				if (_type != type || _name != name)
				{
					return _container.GetPolicy(type, name, policyInterface);
				}
				return _registration.Get(policyInterface);
			}

			public void Set(Type type, Type policyInterface, object policy)
			{
				if (_type != type)
				{
					_container.SetPolicy(type, "ALL", policyInterface, policy);
				}
				else
				{
					_registration.Set(policyInterface, policy);
				}
			}

			public void Set(Type type, string name, Type policyInterface, object policy)
			{
				if (_type != type || _name != name)
				{
					_container.SetPolicy(type, name, policyInterface, policy);
				}
				else
				{
					_registration.Set(policyInterface, policy);
				}
			}

			public void Clear(Type type, string name, Type policyInterface)
			{
				if (_type != type || _name != name)
				{
					_container.ClearPolicy(type, name, policyInterface);
				}
				else
				{
					_registration.Clear(policyInterface);
				}
			}
		}

		[DebuggerDisplay("RegisteredType={RegisteredType?.Name},    Name={Name},    MappedTo={RegisteredType == MappedToType ? string.Empty : MappedToType?.Name ?? string.Empty},    {LifetimeManager?.GetType()?.Name}")]
		private struct ContainerRegistrationStruct : IContainerRegistration
		{
			public Type RegisteredType { get; internal set; }

			public string Name { get; internal set; }

			public Type MappedToType { get; internal set; }

			public LifetimeManager LifetimeManager { get; internal set; }
		}

		internal ResolveDelegateFactory _buildStrategy = OptimizingFactory;

		private static Func<Exception, string> CreateMessage = (Exception ex) => "Resolution failed with error: " + ex.Message + "\n\nFor more detailed information run Unity in debug mode: new UnityContainer(ModeFlags.Diagnostic)";

		private readonly UnityContainer _root;

		private readonly UnityContainer _parent;

		internal readonly LifetimeContainer LifetimeContainer;

		private List<IUnityContainerExtensionConfigurator> _extensions;

		private LifetimeManager _typeLifetimeManager;

		private LifetimeManager _factoryLifetimeManager;

		private LifetimeManager _instanceLifetimeManager;

		private readonly ContainerContext _context;

		private StagedStrategyChain<BuilderStrategy, UnityBuildStage> _strategies;

		private StagedStrategyChain<MemberProcessor, BuilderStage> _processors;

		private BuilderStrategy[] _strategiesChain;

		private MemberProcessor[] _processorsChain;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal Func<Type, string, IPolicySet> GetRegistration;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal Func<Type, string, InternalRegistration, IPolicySet> Register;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal GetPolicyDelegate GetPolicy;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal SetPolicyDelegate SetPolicy;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal ClearPolicyDelegate ClearPolicy;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private Func<Type, string, IPolicySet> _get;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal Func<Type, string, bool> _isExplicitlyRegistered;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private Func<Type, string, Type, IPolicySet> _getGenericRegistration;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal Func<Type, bool> IsTypeExplicitlyRegistered;

		private static readonly ContainerLifetimeManager _containerManager = new ContainerLifetimeManager();

		internal Action<UnityContainer> SetDefaultPolicies = delegate(UnityContainer container)
		{
			container.Defaults = (IPolicySet)(object)new InternalRegistration(typeof(BuilderContext.ExecutePlanDelegate), container.ContextExecutePlan);
			FieldProcessor fieldProcessor = new FieldProcessor(container.Defaults);
			MethodProcessor methodProcessor = new MethodProcessor(container.Defaults, container);
			PropertyProcessor propertyProcessor = new PropertyProcessor(container.Defaults);
			ConstructorProcessor constructorProcessor = new ConstructorProcessor(container.Defaults, container);
			container._processors = new StagedStrategyChain<MemberProcessor, BuilderStage>
			{
				{
					constructorProcessor,
					BuilderStage.Creation
				},
				{
					fieldProcessor,
					BuilderStage.Fields
				},
				{
					propertyProcessor,
					BuilderStage.Properties
				},
				{
					methodProcessor,
					BuilderStage.Methods
				}
			};
			container._processors.Invalidated += delegate
			{
				container._processorsChain = container._processors.ToArray();
			};
			container._processorsChain = container._processors.ToArray();
			container.Defaults.Set(typeof(ResolveDelegateFactory), (object)new ResolveDelegateFactory(OptimizingFactory));
			container.Defaults.Set(typeof(ISelect<ConstructorInfo>), (object)constructorProcessor);
			container.Defaults.Set(typeof(ISelect<FieldInfo>), (object)fieldProcessor);
			container.Defaults.Set(typeof(ISelect<PropertyInfo>), (object)propertyProcessor);
			container.Defaults.Set(typeof(ISelect<MethodInfo>), (object)methodProcessor);
			if (container._registrations != null)
			{
				container.Set(null, null, container.Defaults);
			}
		};

		private const string LifetimeManagerInUse = "The lifetime manager is already registered. WithLifetime managers cannot be reused, please create a new one.";

		private Action<Type, Type> TypeValidator;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private const int ContainerInitialCapacity = 37;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private const int ListToHashCutPoint = 8;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public const string All = "ALL";

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal const int HashMask = int.MaxValue;

		internal IPolicySet Defaults;

		private readonly object _syncRoot = new object();

		private LinkedNode<Type, object> _validators;

		private Registrations _registrations;

		internal LifetimeManager TypeLifetimeManager
		{
			get
			{
				return _typeLifetimeManager ?? _parent.TypeLifetimeManager;
			}
			set
			{
				_typeLifetimeManager = value;
			}
		}

		internal LifetimeManager FactoryLifetimeManager
		{
			get
			{
				return _factoryLifetimeManager ?? _parent.FactoryLifetimeManager;
			}
			set
			{
				_factoryLifetimeManager = value;
			}
		}

		internal LifetimeManager InstanceLifetimeManager
		{
			get
			{
				return _instanceLifetimeManager ?? _parent.InstanceLifetimeManager;
			}
			set
			{
				_instanceLifetimeManager = value;
			}
		}

		IUnityContainer IUnityContainer.Parent => (IUnityContainer)(object)_parent;

		public IEnumerable<IContainerRegistration> Registrations
		{
			get
			{
				QuickSet<Type> set = new QuickSet<Type>();
				set.Add(NamedType.GetHashCode(typeof(IUnityContainer), (string)null), typeof(IUnityContainer));
				yield return (IContainerRegistration)(object)new ContainerRegistrationStruct
				{
					RegisteredType = typeof(IUnityContainer),
					MappedToType = typeof(UnityContainer),
					LifetimeManager = (LifetimeManager)(object)_containerManager
				};
				for (UnityContainer container = this; container != null; container = container._parent)
				{
					if (container._registrations != null)
					{
						Registrations registrations = container._registrations;
						for (int i = 0; i < registrations.Count; i++)
						{
							IRegistry<string, IPolicySet> value = registrations.Entries[i].Value;
							Type type = registrations.Entries[i].Key;
							IRegistry<string, IPolicySet> registry = value;
							if (registry == null)
							{
								yield break;
							}
							if (!(registry is LinkedRegistry linkedRegistry))
							{
								if (!(registry is HashRegistry hashRegistry))
								{
									yield break;
								}
								HashRegistry hashRegistry2 = hashRegistry;
								int count = hashRegistry2.Count;
								HashRegistry.Entry[] nodes = hashRegistry2.Entries;
								for (int j = 0; j < count; j++)
								{
									string key = nodes[j].Key;
									if (nodes[j].Value is ContainerRegistration containerRegistration && set.Add(NamedType.GetHashCode(type, key), type))
									{
										yield return (IContainerRegistration)(object)new ContainerRegistrationStruct
										{
											RegisteredType = type,
											Name = key,
											LifetimeManager = containerRegistration.LifetimeManager,
											MappedToType = containerRegistration.Type
										};
									}
								}
								continue;
							}
							LinkedRegistry linkedRegistry2 = linkedRegistry;
							for (LinkedNode<string, IPolicySet> node = linkedRegistry2; node != null; node = node.Next)
							{
								if (node.Value is ContainerRegistration containerRegistration2 && set.Add(NamedType.GetHashCode(type, node.Key), type))
								{
									yield return (IContainerRegistration)(object)new ContainerRegistrationStruct
									{
										RegisteredType = type,
										Name = node.Key,
										LifetimeManager = containerRegistration2.LifetimeManager,
										MappedToType = containerRegistration2.Type
									};
								}
							}
						}
					}
				}
			}
		}

		private ResolveDelegate<BuilderContext> ExecutePlan { get; set; } = delegate(ref BuilderContext context)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			int num2 = -1;
			BuilderStrategy[] buildChain = ((InternalRegistration)(object)context.Registration).BuildChain;
			try
			{
				while (!context.BuildComplete && ++num2 < buildChain.Length)
				{
					buildChain[num2].PreBuildUp(ref context);
				}
				while (--num2 >= 0)
				{
					buildChain[num2].PostBuildUp(ref context);
				}
			}
			catch (Exception ex)
			{
				SynchronizedLifetimeManager requiresRecovery = context.RequiresRecovery;
				if (requiresRecovery != null)
				{
					requiresRecovery.Recover();
				}
				if (!(ex.InnerException is InvalidRegistrationException) && !(ex is InvalidRegistrationException) && !(ex is ObjectDisposedException) && !(ex is MemberAccessException) && !(ex is MakeGenericTypeFailedException))
				{
					throw;
				}
				throw new ResolutionFailedException(context.RegistrationType, context.Name, CreateMessage(ex), ex);
			}
			return context.Existing;
		};


		internal BuilderContext.ExecutePlanDelegate ContextExecutePlan { get; set; } = delegate(BuilderStrategy[] chain, ref BuilderContext context)
		{
			int num = -1;
			try
			{
				while (!context.BuildComplete && ++num < chain.Length)
				{
					chain[num].PreBuildUp(ref context);
				}
				while (--num >= 0)
				{
					chain[num].PostBuildUp(ref context);
				}
			}
			catch when (context.RequiresRecovery != null)
			{
				context.RequiresRecovery.Recover();
				throw;
			}
			return context.Existing;
		};


		internal BuilderContext.ResolvePlanDelegate ContextResolvePlan { get; set; } = delegate(ref BuilderContext context, ResolveDelegate<BuilderContext> resolver)
		{
			return resolver.Invoke(ref context);
		};


		private event EventHandler<RegisterEventArgs> Registering;

		private event EventHandler<RegisterInstanceEventArgs> RegisteringInstance;

		private event EventHandler<ChildContainerCreatedEventArgs> ChildContainerCreated;

		private static string CreateDiagnosticMessage(Exception ex)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine(ex.Message);
			stringBuilder.AppendLine("_____________________________________________________");
			stringBuilder.AppendLine("Exception occurred while:");
			foreach (DictionaryEntry datum in ex.Data)
			{
				stringBuilder.AppendLine(DataToString(datum.Value));
			}
			return stringBuilder.ToString();
		}

		private static string DataToString(object value)
		{
			if (value != null)
			{
				if (value is ParameterInfo parameterInfo)
				{
					ParameterInfo parameterInfo2 = parameterInfo;
					return "    for parameter:  " + parameterInfo2.Name;
				}
				if (value is ConstructorInfo constructorInfo)
				{
					ConstructorInfo constructorInfo2 = constructorInfo;
					string text = string.Join(", ", from p in constructorInfo2.GetParameters()
						select p.ParameterType.Name + " " + p.Name);
					return "   on constructor:  " + constructorInfo2.DeclaringType.Name + "(" + text + ")";
				}
				if (value is MethodInfo methodInfo)
				{
					MethodInfo methodInfo2 = methodInfo;
					string text2 = string.Join(", ", from p in methodInfo2.GetParameters()
						select p.ParameterType.Name + " " + p.Name);
					return "        on method:  " + methodInfo2.Name + "(" + text2 + ")";
				}
				if (value is PropertyInfo propertyInfo)
				{
					PropertyInfo propertyInfo2 = propertyInfo;
					return "    for property:   " + propertyInfo2.Name;
				}
				if (value is FieldInfo fieldInfo)
				{
					FieldInfo fieldInfo2 = fieldInfo;
					return "       for field:   " + fieldInfo2.Name;
				}
				if (value is Type type)
				{
					Type type2 = type;
					return "\n• while resolving:  " + type2.Name;
				}
				if (value is Tuple<Type, string> tuple)
				{
					Tuple<Type, string> tuple2 = tuple;
					return "\n• while resolving:  " + tuple2.Item1.Name + " registered with name: " + tuple2.Item2;
				}
				if (value is Tuple<Type, Type> tuple3)
				{
					Tuple<Type, Type> tuple4 = tuple3;
					return "        mapped to:  " + tuple4.Item1?.Name;
				}
			}
			return value.ToString();
		}

		private string DebugName()
		{
			int num = (_registrations?.Keys ?? Enumerable.Empty<Type>()).SelectMany((Type t) => _registrations[t].Values).OfType<ContainerRegistration>().Count();
			if (_parent == null)
			{
				return $"Container[{num}]";
			}
			return _parent.DebugName() + $".Child[{num}]";
		}

		private UnityContainer(UnityContainer parent)
		{
			LifetimeContainer = new LifetimeContainer((IUnityContainer)(object)this);
			_context = new ContainerContext(this);
			_parent = parent ?? throw new ArgumentNullException("parent");
			_parent.LifetimeContainer.Add(this);
			_root = _parent._root;
			SetDefaultPolicies = parent.SetDefaultPolicies;
			_get = _parent._get;
			_getGenericRegistration = _parent._getGenericRegistration;
			_isExplicitlyRegistered = _parent._isExplicitlyRegistered;
			IsTypeExplicitlyRegistered = _parent.IsTypeExplicitlyRegistered;
			GetRegistration = _parent.GetRegistration;
			Register = CreateAndSetOrUpdate;
			GetPolicy = parent.GetPolicy;
			SetPolicy = CreateAndSetPolicy;
			ClearPolicy = delegate
			{
			};
			_strategies = _parent._strategies;
			_strategiesChain = _parent._strategiesChain;
			_strategies.Invalidated += OnStrategiesChanged;
			SetDefaultPolicies(this);
		}

		internal static void SetDiagnosticPolicies(UnityContainer container)
		{
			container.ContextExecutePlan = ContextValidatingExecutePlan;
			container.ContextResolvePlan = ContextValidatingResolvePlan;
			container.ExecutePlan = container.ExecuteValidatingPlan;
			container.Defaults = (IPolicySet)(object)new InternalRegistration(typeof(BuilderContext.ExecutePlanDelegate), container.ContextExecutePlan);
			if (container._registrations != null)
			{
				container.Set(null, null, container.Defaults);
			}
			FieldDiagnostic fieldDiagnostic = new FieldDiagnostic(container.Defaults);
			MethodDiagnostic methodDiagnostic = new MethodDiagnostic(container.Defaults, container);
			PropertyDiagnostic propertyDiagnostic = new PropertyDiagnostic(container.Defaults);
			ConstructorDiagnostic constructorDiagnostic = new ConstructorDiagnostic(container.Defaults, container);
			container._processors = new StagedStrategyChain<MemberProcessor, BuilderStage>
			{
				{
					constructorDiagnostic,
					BuilderStage.Creation
				},
				{
					fieldDiagnostic,
					BuilderStage.Fields
				},
				{
					propertyDiagnostic,
					BuilderStage.Properties
				},
				{
					methodDiagnostic,
					BuilderStage.Methods
				}
			};
			container._processors.Invalidated += delegate
			{
				container._processorsChain = container._processors.ToArray();
			};
			container._processorsChain = container._processors.ToArray();
			container.Defaults.Set(typeof(ResolveDelegateFactory), (object)container._buildStrategy);
			container.Defaults.Set(typeof(ISelect<ConstructorInfo>), (object)constructorDiagnostic);
			container.Defaults.Set(typeof(ISelect<FieldInfo>), (object)fieldDiagnostic);
			container.Defaults.Set(typeof(ISelect<PropertyInfo>), (object)propertyDiagnostic);
			container.Defaults.Set(typeof(ISelect<MethodInfo>), (object)methodDiagnostic);
			InternalRegistration internalRegistration = new InternalRegistration();
			internalRegistration.Set(typeof(Func<Type, InjectionMember, ConstructorInfo>), Validating.ConstructorSelector);
			internalRegistration.Set(typeof(Func<Type, InjectionMember, MethodInfo>), Validating.MethodSelector);
			internalRegistration.Set(typeof(Func<Type, InjectionMember, FieldInfo>), Validating.FieldSelector);
			internalRegistration.Set(typeof(Func<Type, InjectionMember, PropertyInfo>), Validating.PropertySelector);
			container._validators = internalRegistration;
			container.TypeValidator = delegate(Type typeFrom, Type typeTo)
			{
				if (null != typeFrom && typeFrom != null && !typeFrom.IsGenericType && null != typeTo && !typeTo.IsGenericType && !typeFrom.IsAssignableFrom(typeTo))
				{
					throw new ArgumentException($"The type {typeTo} cannot be assigned to variables of type {typeFrom}.");
				}
				if (null != typeFrom && null != typeTo && typeFrom.IsGenericType && typeTo.IsArray && typeFrom.GetGenericTypeDefinition() == typeof(IEnumerable<>))
				{
					throw new ArgumentException("Type mapping of IEnumerable<T> to array T[] is not supported.");
				}
				if (null == typeFrom && typeTo.IsInterface)
				{
					throw new ArgumentException($"The type {typeTo} is an interface and can not be constructed.");
				}
			};
			if (container._registrations != null)
			{
				container.Set(null, null, container.Defaults);
			}
		}

		private void CreateAndSetPolicy(Type type, string name, Type policyInterface, object policy)
		{
			lock (GetRegistration)
			{
				if (_registrations == null)
				{
					SetupChildContainerBehaviors();
				}
			}
			Set(type, name, policyInterface, policy);
		}

		private IPolicySet CreateAndSetOrUpdate(Type type, string name, InternalRegistration registration)
		{
			lock (GetRegistration)
			{
				if (_registrations == null)
				{
					SetupChildContainerBehaviors();
				}
			}
			return AddOrUpdate(type, name, registration);
		}

		private void SetupChildContainerBehaviors()
		{
			lock (_syncRoot)
			{
				if (_registrations == null)
				{
					_registrations = new Registrations(37);
					Set(null, null, Defaults);
					Register = AddOrUpdate;
					GetPolicy = Get;
					SetPolicy = Set;
					ClearPolicy = Clear;
					GetRegistration = GetDynamicRegistration;
					_get = (Type type, string name) => Get(type, name) ?? _parent._get(type, name);
					_getGenericRegistration = GetOrAddGeneric;
					IsTypeExplicitlyRegistered = IsTypeTypeExplicitlyRegisteredLocally;
					_isExplicitlyRegistered = IsExplicitlyRegisteredLocally;
				}
			}
		}

		private void OnStrategiesChanged(object sender, EventArgs e)
		{
			_strategiesChain = _strategies.ToArray();
			if (_parent != null && _registrations == null)
			{
				SetupChildContainerBehaviors();
			}
		}

		private BuilderStrategy[] GetBuilders(Type type, InternalRegistration registration)
		{
			return (from strategy in _strategiesChain.ToArray()
				where strategy.RequiredToBuildType((IUnityContainer)(object)this, type, registration, (InjectionMember[])null)
				select strategy).ToArray();
		}

		internal Type GetFinalType(Type argType)
		{
			Type type = argType;
			while (null != type)
			{
				TypeInfo typeInfo = type.GetTypeInfo();
				Type type2;
				if (typeInfo.IsGenericType)
				{
					if (IsTypeExplicitlyRegistered(type))
					{
						return type;
					}
					Type genericTypeDefinition = typeInfo.GetGenericTypeDefinition();
					if (IsTypeExplicitlyRegistered(genericTypeDefinition))
					{
						return genericTypeDefinition;
					}
					type2 = typeInfo.GenericTypeArguments[0];
					if (IsTypeExplicitlyRegistered(type2))
					{
						return type2;
					}
				}
				else
				{
					if (!type.IsArray)
					{
						return type;
					}
					type2 = type.GetElementType();
					if (IsTypeExplicitlyRegistered(type2))
					{
						return type2;
					}
				}
				type = type2;
			}
			return argType;
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposing)
			{
				return;
			}
			List<Exception> list = null;
			try
			{
				GetPolicy = delegate
				{
					throw new ObjectDisposedException(DebugName() ?? "");
				};
				_strategies.Invalidated -= OnStrategiesChanged;
				_parent?.LifetimeContainer.Remove(this);
				LifetimeContainer.Dispose();
			}
			catch (Exception item)
			{
				list = new List<Exception> { item };
			}
			if (_extensions != null)
			{
				foreach (IDisposable item3 in _extensions.OfType<IDisposable>().ToList())
				{
					try
					{
						item3.Dispose();
					}
					catch (Exception item2)
					{
						if (list == null)
						{
							list = new List<Exception>();
						}
						list.Add(item2);
					}
				}
				_extensions = null;
			}
			lock (GetRegistration)
			{
				_registrations = new Registrations(1);
			}
			if (list != null && list.Count == 1)
			{
				throw list[0];
			}
			if (list == null || list.Count <= 1)
			{
				return;
			}
			throw new AggregateException(list);
		}

		IUnityContainer IUnityContainer.RegisterType(Type typeFrom, Type typeTo, string name, ITypeLifetimeManager lifetimeManager, InjectionMember[] injectionMembers)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			Type registeredType = typeFrom ?? typeTo;
			if (null == registeredType)
			{
				throw new ArgumentNullException("typeTo");
			}
			TypeValidator?.Invoke(typeFrom, typeTo);
			try
			{
				LifetimeManager val = (LifetimeManager)((lifetimeManager == null) ? ((object)TypeLifetimeManager.CreateLifetimePolicy()) : ((object)(LifetimeManager)lifetimeManager));
				if (val.InUse)
				{
					throw new InvalidOperationException("The lifetime manager is already registered. WithLifetime managers cannot be reused, please create a new one.");
				}
				UnityContainer unityContainer = ((val is SingletonLifetimeManager) ? _root : this);
				ContainerRegistration registration = new ContainerRegistration(_validators, typeTo, val, injectionMembers);
				ContainerControlledLifetimeManager val2;
				if ((val2 = (ContainerControlledLifetimeManager)(object)((val is ContainerControlledLifetimeManager) ? val : null)) != null)
				{
					val2.Scope = unityContainer;
				}
				if (unityContainer.Register(registeredType, name, registration) is ContainerRegistration containerRegistration && containerRegistration.LifetimeManager is IDisposable disposable)
				{
					unityContainer.LifetimeContainer.Remove(disposable);
					disposable.Dispose();
				}
				if (val is IDisposable item)
				{
					unityContainer.LifetimeContainer.Add(item);
				}
				if (injectionMembers != null && injectionMembers.Length != 0)
				{
					InjectionMember[] array = injectionMembers;
					for (int i = 0; i < array.Length; i++)
					{
						array[i].AddPolicies<BuilderContext, ContainerRegistration>(registeredType, typeTo, name, ref registration);
					}
				}
				registration.BuildChain = (from strategy in _strategiesChain.ToArray()
					where strategy.RequiredToBuildType((IUnityContainer)(object)this, registeredType, registration, injectionMembers)
					select strategy).ToArray();
				unityContainer.Registering?.Invoke(this, new RegisterEventArgs(registeredType, typeTo, name, val));
			}
			catch (Exception ex)
			{
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine(ex.Message);
				stringBuilder.AppendLine();
				List<string> list = new List<string>();
				string text = ((!(null == typeFrom)) ? (typeFrom?.Name + "," + typeTo?.Name) : typeTo?.Name);
				if (name != null)
				{
					list.Add(" '" + name + "'");
				}
				if (lifetimeManager != null && !(lifetimeManager is TransientLifetimeManager))
				{
					list.Add(((object)lifetimeManager).ToString());
				}
				if (injectionMembers != null && injectionMembers.Length != 0)
				{
					list.Add(string.Join(" ,", injectionMembers.Select((InjectionMember m) => ((object)m).ToString())));
				}
				stringBuilder.AppendLine("  Error in:  RegisterType<" + text + ">(" + string.Join(", ", list) + ")");
				throw new InvalidOperationException(stringBuilder.ToString(), ex);
			}
			return (IUnityContainer)(object)this;
		}

		IUnityContainer IUnityContainer.RegisterInstance(Type type, string name, object instance, IInstanceLifetimeManager lifetimeManager)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			Type type2 = instance?.GetType();
			Type type3 = type ?? type2;
			LifetimeManager val = (LifetimeManager)((lifetimeManager == null) ? ((object)InstanceLifetimeManager.CreateLifetimePolicy()) : ((object)(LifetimeManager)lifetimeManager));
			try
			{
				if (null == type3)
				{
					throw new InvalidOperationException("At least one of Type arguments 'type' or 'instance' must be not 'null'");
				}
				if (val.InUse)
				{
					throw new InvalidOperationException("The lifetime manager is already registered. WithLifetime managers cannot be reused, please create a new one.");
				}
				val.SetValue(instance, (ILifetimeContainer)(object)LifetimeContainer);
				UnityContainer unityContainer = ((val is SingletonLifetimeManager) ? _root : this);
				ContainerRegistration registration = new ContainerRegistration(null, type2, val);
				ContainerControlledLifetimeManager val2;
				if ((val2 = (ContainerControlledLifetimeManager)(object)((val is ContainerControlledLifetimeManager) ? val : null)) != null)
				{
					val2.Scope = unityContainer;
				}
				if (unityContainer.Register(type3, name, registration) is ContainerRegistration containerRegistration && containerRegistration.LifetimeManager is IDisposable disposable)
				{
					unityContainer.LifetimeContainer.Remove(disposable);
					disposable.Dispose();
				}
				if (val is IDisposable item)
				{
					unityContainer.LifetimeContainer.Add(item);
				}
				registration.BuildChain = (from strategy in _strategiesChain.ToArray()
					where strategy.RequiredToResolveInstance((IUnityContainer)(object)this, registration)
					select strategy).ToArray();
				unityContainer.RegisteringInstance?.Invoke(this, new RegisterInstanceEventArgs(type3, instance, name, val));
			}
			catch (Exception innerException)
			{
				List<string> list = new List<string>();
				if (name != null)
				{
					list.Add(" '" + name + "'");
				}
				if (lifetimeManager != null && !(lifetimeManager is TransientLifetimeManager))
				{
					list.Add(((object)lifetimeManager).ToString());
				}
				throw new InvalidOperationException("Error in  RegisterInstance<" + type3?.Name + ">(" + string.Join(", ", list) + ")", innerException);
			}
			return (IUnityContainer)(object)this;
		}

		public IUnityContainer RegisterFactory(Type type, string name, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			LifetimeManager val = (LifetimeManager)((lifetimeManager == null) ? ((object)FactoryLifetimeManager.CreateLifetimePolicy()) : ((object)(LifetimeManager)lifetimeManager));
			if (null == type)
			{
				throw new ArgumentNullException("type");
			}
			if (factory == null)
			{
				throw new ArgumentNullException("factory");
			}
			if (val.InUse)
			{
				throw new InvalidOperationException("The lifetime manager is already registered. WithLifetime managers cannot be reused, please create a new one.");
			}
			UnityContainer unityContainer = ((val is SingletonLifetimeManager) ? _root : this);
			InjectionFactory val2 = new InjectionFactory(factory);
			InjectionMember[] injectionMembers = (InjectionMember[])(object)new InjectionMember[1] { (InjectionMember)val2 };
			ContainerRegistration registration = new ContainerRegistration(_validators, type, val, injectionMembers);
			ContainerControlledLifetimeManager val3;
			if ((val3 = (ContainerControlledLifetimeManager)(object)((val is ContainerControlledLifetimeManager) ? val : null)) != null)
			{
				val3.Scope = unityContainer;
			}
			if (unityContainer.Register(type, name, registration) is ContainerRegistration containerRegistration && containerRegistration.LifetimeManager is IDisposable disposable)
			{
				unityContainer.LifetimeContainer.Remove(disposable);
				disposable.Dispose();
			}
			if (val is IDisposable item)
			{
				unityContainer.LifetimeContainer.Add(item);
			}
			((InjectionMember)val2).AddPolicies<BuilderContext, ContainerRegistration>(type, type, name, ref registration);
			registration.BuildChain = (from strategy in _strategiesChain.ToArray()
				where strategy.RequiredToBuildType((IUnityContainer)(object)this, type, registration, injectionMembers)
				select strategy).ToArray();
			unityContainer.Registering?.Invoke(this, new RegisterEventArgs(type, type, name, val));
			return (IUnityContainer)(object)this;
		}

		bool IUnityContainer.IsRegistered(Type type, string name)
		{
			if ((object)"ALL" != name)
			{
				return _isExplicitlyRegistered(type, name);
			}
			return IsTypeExplicitlyRegistered(type);
		}

		object IUnityContainer.Resolve(Type type, string name, params ResolverOverride[] overrides)
		{
			if (null == type)
			{
				throw new ArgumentNullException("type");
			}
			InternalRegistration internalRegistration = (InternalRegistration)(object)GetRegistration(type, name);
			object obj = internalRegistration.Get(typeof(LifetimeManager));
			ContainerControlledLifetimeManager val;
			UnityContainer unityContainer = (((val = (ContainerControlledLifetimeManager)((obj is ContainerControlledLifetimeManager) ? obj : null)) != null) ? ((UnityContainer)val.Scope) : this);
			BuilderContext builderContext = default(BuilderContext);
			builderContext.List = (IPolicyList)(object)new PolicyList();
			builderContext.Lifetime = (ILifetimeContainer)(object)unityContainer.LifetimeContainer;
			builderContext.Overrides = ((overrides != null && overrides.Length == 0) ? null : overrides);
			builderContext.Registration = (IPolicySet)(object)internalRegistration;
			builderContext.RegistrationType = type;
			builderContext.Name = name;
			builderContext.ExecutePlan = ContextExecutePlan;
			builderContext.ResolvePlan = ContextResolvePlan;
			builderContext.Type = ((internalRegistration is ContainerRegistration containerRegistration) ? containerRegistration.Type : type);
			BuilderContext builderContext2 = builderContext;
			return unityContainer.ExecutePlan.Invoke(ref builderContext2);
		}

		object IUnityContainer.BuildUp(Type type, object existing, string name, params ResolverOverride[] overrides)
		{
			if (null == type)
			{
				throw new ArgumentNullException("type");
			}
			if (existing != null && TypeValidator != null)
			{
				TypeValidator(type, existing.GetType());
			}
			InternalRegistration internalRegistration = (InternalRegistration)(object)GetRegistration(type, name);
			object obj = internalRegistration.Get(typeof(LifetimeManager));
			ContainerControlledLifetimeManager val;
			UnityContainer unityContainer = (((val = (ContainerControlledLifetimeManager)((obj is ContainerControlledLifetimeManager) ? obj : null)) != null) ? ((UnityContainer)val.Scope) : this);
			BuilderContext builderContext = default(BuilderContext);
			builderContext.List = (IPolicyList)(object)new PolicyList();
			builderContext.Lifetime = (ILifetimeContainer)(object)unityContainer.LifetimeContainer;
			builderContext.Existing = existing;
			builderContext.Overrides = ((overrides != null && overrides.Length == 0) ? null : overrides);
			builderContext.Registration = (IPolicySet)(object)internalRegistration;
			builderContext.RegistrationType = type;
			builderContext.Name = name;
			builderContext.ExecutePlan = ContextExecutePlan;
			builderContext.ResolvePlan = ContextResolvePlan;
			builderContext.Type = ((internalRegistration is ContainerRegistration containerRegistration) ? containerRegistration.Type : type);
			BuilderContext builderContext2 = builderContext;
			return ExecutePlan.Invoke(ref builderContext2);
		}

		IUnityContainer IUnityContainer.CreateChildContainer()
		{
			UnityContainer unityContainer = new UnityContainer(this);
			this.ChildContainerCreated?.Invoke(this, new ChildContainerCreatedEventArgs(unityContainer._context));
			return (IUnityContainer)(object)unityContainer;
		}

		public UnityContainer()
		{
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Expected O, but got Unknown
			_root = this;
			LifetimeContainer = new LifetimeContainer((IUnityContainer)(object)this);
			_typeLifetimeManager = (LifetimeManager)(object)TransientLifetimeManager.Instance;
			_factoryLifetimeManager = (LifetimeManager)(object)TransientLifetimeManager.Instance;
			_instanceLifetimeManager = (LifetimeManager)new ContainerControlledLifetimeManager();
			_registrations = new Registrations(37);
			_context = new ContainerContext(this);
			_get = Get;
			_getGenericRegistration = GetOrAddGeneric;
			_isExplicitlyRegistered = IsExplicitlyRegisteredLocally;
			IsTypeExplicitlyRegistered = IsTypeTypeExplicitlyRegisteredLocally;
			GetRegistration = GetOrAdd;
			Register = AddOrUpdate;
			GetPolicy = Get;
			SetPolicy = Set;
			ClearPolicy = Clear;
			_strategies = new StagedStrategyChain<BuilderStrategy, UnityBuildStage>
			{
				{
					new ArrayResolveStrategy(typeof(UnityContainer).GetTypeInfo().GetDeclaredMethod("ResolveArray"), typeof(UnityContainer).GetTypeInfo().GetDeclaredMethod("ResolveGenericArray")),
					UnityBuildStage.Enumerable
				},
				{
					new BuildKeyMappingStrategy(),
					UnityBuildStage.TypeMapping
				},
				{
					new LifetimeStrategy(),
					UnityBuildStage.Lifetime
				},
				{
					new BuildPlanStrategy(),
					UnityBuildStage.Creation
				}
			};
			_strategies.Invalidated += OnStrategiesChanged;
			_strategiesChain = _strategies.ToArray();
			SetDefaultPolicies(this);
			Set(typeof(Func<>), "ALL", typeof(LifetimeManager), (object)new PerResolveLifetimeManager());
			Set(typeof(Func<>), "ALL", typeof(ResolveDelegateFactory), new ResolveDelegateFactory(DeferredFuncResolverFactory.DeferredResolveDelegateFactory));
			Set(typeof(Lazy<>), "ALL", typeof(ResolveDelegateFactory), new ResolveDelegateFactory(GenericLazyResolverFactory.GetResolver));
			Set(typeof(IEnumerable<>), "ALL", typeof(ResolveDelegateFactory), EnumerableResolver.Factory);
			((IUnityContainer)this).RegisterInstance(typeof(IUnityContainer), (string)null, (object)this, (IInstanceLifetimeManager)(object)_containerManager);
		}

		public IUnityContainer AddExtension(IUnityContainerExtensionConfigurator extension)
		{
			lock (LifetimeContainer)
			{
				if (_extensions == null)
				{
					_extensions = new List<IUnityContainerExtensionConfigurator>();
				}
				_extensions.Add(extension ?? throw new ArgumentNullException("extension"));
			}
			(extension as UnityContainerExtension)?.InitializeExtension(_context);
			return (IUnityContainer)(object)this;
		}

		public object Configure(Type configurationInterface)
		{
			return _extensions?.FirstOrDefault((IUnityContainerExtensionConfigurator ex) => configurationInterface.IsAssignableFrom(ex.GetType()));
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		private bool IsExplicitlyRegisteredLocally(Type type, string name)
		{
			int num = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num2 = num % _registrations.Buckets.Length;
			for (int num3 = _registrations.Buckets[num2]; num3 >= 0; num3 = _registrations.Entries[num3].Next)
			{
				ref Registrations.Entry reference = ref _registrations.Entries[num3];
				if (reference.HashCode == num && !(reference.Key != type))
				{
					if (!(reference.Value?[name] is ContainerRegistration))
					{
						UnityContainer parent = _parent;
						if (parent == null)
						{
							return false;
						}
						return ((IUnityContainer)parent).IsRegistered(type, name);
					}
					return true;
				}
			}
			UnityContainer parent2 = _parent;
			if (parent2 == null)
			{
				return false;
			}
			return ((IUnityContainer)parent2).IsRegistered(type, name);
		}

		private bool IsTypeTypeExplicitlyRegisteredLocally(Type type)
		{
			int num = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num2 = num % _registrations.Buckets.Length;
			for (int num3 = _registrations.Buckets[num2]; num3 >= 0; num3 = _registrations.Entries[num3].Next)
			{
				ref Registrations.Entry reference = ref _registrations.Entries[num3];
				if (reference.HashCode == num && !(reference.Key != type))
				{
					if (!reference.Value.Values.Any((IPolicySet v) => v is ContainerRegistration))
					{
						return _parent?.IsTypeExplicitlyRegistered(type) ?? false;
					}
					return true;
				}
			}
			return _parent?.IsTypeExplicitlyRegistered(type) ?? false;
		}

		internal bool RegistrationExists(Type type, string name)
		{
			IPolicySet val = null;
			IPolicySet val2 = null;
			int num = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			for (UnityContainer unityContainer = this; unityContainer != null; unityContainer = unityContainer._parent)
			{
				if (unityContainer._registrations != null)
				{
					int num2 = num % unityContainer._registrations.Buckets.Length;
					for (int num3 = unityContainer._registrations.Buckets[num2]; num3 >= 0; num3 = unityContainer._registrations.Entries[num3].Next)
					{
						ref Registrations.Entry reference = ref unityContainer._registrations.Entries[num3];
						if (reference.HashCode == num && !(reference.Key != type))
						{
							IRegistry<string, IPolicySet> value = reference.Value;
							if (value[name] != null)
							{
								return true;
							}
							if (val == null)
							{
								val = value["ALL"];
							}
							if (name != null && val2 == null)
							{
								val2 = value[null];
							}
						}
					}
				}
			}
			if (val != null)
			{
				return true;
			}
			if (val2 != null)
			{
				return true;
			}
			if ((object)type != null && !type.IsGenericType)
			{
				return false;
			}
			type = type?.GetGenericTypeDefinition();
			num = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			for (UnityContainer unityContainer2 = this; unityContainer2 != null; unityContainer2 = unityContainer2._parent)
			{
				if (unityContainer2._registrations != null)
				{
					int num4 = num % unityContainer2._registrations.Buckets.Length;
					for (int num5 = unityContainer2._registrations.Buckets[num4]; num5 >= 0; num5 = unityContainer2._registrations.Entries[num5].Next)
					{
						ref Registrations.Entry reference2 = ref unityContainer2._registrations.Entries[num5];
						if (reference2.HashCode == num && !(reference2.Key != type))
						{
							IRegistry<string, IPolicySet> value2 = reference2.Value;
							if (value2[name] != null)
							{
								return true;
							}
							if (val == null)
							{
								val = value2["ALL"];
							}
							if (name != null && val2 == null)
							{
								val2 = value2[null];
							}
						}
					}
				}
			}
			if (val != null)
			{
				return true;
			}
			return val2 != null;
		}

		private static RegistrationSet GetRegistrations(UnityContainer container)
		{
			RegistrationSet registrationSet = ((container._parent != null) ? GetRegistrations(container._parent) : new RegistrationSet());
			if (container._registrations == null)
			{
				return registrationSet;
			}
			int length = container._registrations.Count;
			Registrations.Entry[] entries = container._registrations.Entries;
			for (int i = ((container._parent == null) ? GetStartIndex() : 0); i < length; i++)
			{
				ref Registrations.Entry reference = ref entries[i];
				IRegistry<string, IPolicySet> value = reference.Value;
				if (value != null)
				{
					if (value is LinkedRegistry linkedRegistry)
					{
						for (LinkedNode<string, IPolicySet> linkedNode = linkedRegistry; linkedNode != null; linkedNode = linkedNode.Next)
						{
							if (linkedNode.Value is ContainerRegistration registration)
							{
								registrationSet.Add(reference.Key, linkedNode.Key, registration);
							}
						}
						continue;
					}
					if (value is HashRegistry hashRegistry)
					{
						int count = hashRegistry.Count;
						HashRegistry.Entry[] entries2 = hashRegistry.Entries;
						for (int j = 0; j < count; j++)
						{
							ref HashRegistry.Entry reference2 = ref entries2[j];
							if (reference2.Value is ContainerRegistration registration2)
							{
								registrationSet.Add(reference.Key, reference2.Key, registration2);
							}
						}
						continue;
					}
				}
				throw new InvalidOperationException("Unknown type of registry");
			}
			return registrationSet;
			int GetStartIndex()
			{
				int num = -1;
				while (++num < length)
				{
					if (!(typeof(IUnityContainer) != container._registrations.Entries[num].Key))
					{
						return num;
					}
				}
				return 0;
			}
		}

		private static RegistrationSet GetRegistrations(UnityContainer container, params Type[] types)
		{
			RegistrationSet registrationSet = ((container._parent != null) ? GetRegistrations(container._parent, types) : new RegistrationSet());
			if (container._registrations == null)
			{
				return registrationSet;
			}
			foreach (Type type in types)
			{
				IRegistry<string, IPolicySet> registry = container.Get(type);
				if (registry?.Values == null)
				{
					continue;
				}
				IRegistry<string, IPolicySet> registry2 = registry;
				if (registry2 != null)
				{
					if (registry2 is LinkedRegistry linkedRegistry)
					{
						for (LinkedNode<string, IPolicySet> linkedNode = linkedRegistry; linkedNode != null; linkedNode = linkedNode.Next)
						{
							if (linkedNode.Value is ContainerRegistration registration)
							{
								registrationSet.Add(type, linkedNode.Key, registration);
							}
						}
						continue;
					}
					if (registry2 is HashRegistry hashRegistry)
					{
						int count = hashRegistry.Count;
						HashRegistry.Entry[] entries = hashRegistry.Entries;
						for (int j = 0; j < count; j++)
						{
							ref HashRegistry.Entry reference = ref entries[j];
							if (reference.Value is ContainerRegistration registration2)
							{
								registrationSet.Add(type, reference.Key, registration2);
							}
						}
						continue;
					}
				}
				throw new InvalidOperationException("Unknown type of registry");
			}
			return registrationSet;
		}

		private static RegistrationSet GetNamedRegistrations(UnityContainer container, params Type[] types)
		{
			RegistrationSet registrationSet = ((container._parent != null) ? GetNamedRegistrations(container._parent, types) : new RegistrationSet());
			if (container._registrations == null)
			{
				return registrationSet;
			}
			foreach (Type type in types)
			{
				IRegistry<string, IPolicySet> registry = container.Get(type);
				if (registry?.Values == null)
				{
					continue;
				}
				IRegistry<string, IPolicySet> registry2 = registry;
				if (registry2 != null)
				{
					if (registry2 is LinkedRegistry linkedRegistry)
					{
						for (LinkedNode<string, IPolicySet> linkedNode = linkedRegistry; linkedNode != null; linkedNode = linkedNode.Next)
						{
							if (linkedNode.Value is ContainerRegistration registration && !string.IsNullOrEmpty(linkedNode.Key))
							{
								registrationSet.Add(type, linkedNode.Key, registration);
							}
						}
						continue;
					}
					if (registry2 is HashRegistry hashRegistry)
					{
						int count = hashRegistry.Count;
						HashRegistry.Entry[] entries = hashRegistry.Entries;
						for (int j = 0; j < count; j++)
						{
							ref HashRegistry.Entry reference = ref entries[j];
							if (reference.Value is ContainerRegistration registration2 && !string.IsNullOrEmpty(reference.Key))
							{
								registrationSet.Add(type, reference.Key, registration2);
							}
						}
						continue;
					}
				}
				throw new InvalidOperationException("Unknown type of registry");
			}
			return registrationSet;
		}

		private IRegistry<string, IPolicySet> Get(Type type)
		{
			int num = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num2 = num % _registrations.Buckets.Length;
			for (int num3 = _registrations.Buckets[num2]; num3 >= 0; num3 = _registrations.Entries[num3].Next)
			{
				ref Registrations.Entry reference = ref _registrations.Entries[num3];
				if (reference.HashCode == num && !(reference.Key != type))
				{
					return reference.Value;
				}
			}
			return null;
		}

		private IPolicySet AddOrUpdate(Type type, string name, InternalRegistration registration)
		{
			int num = 0;
			int num2 = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num3 = num2 % _registrations.Buckets.Length;
			lock (_syncRoot)
			{
				int num4 = _registrations.Buckets[num3];
				while (num4 >= 0)
				{
					ref Registrations.Entry reference = ref _registrations.Entries[num4];
					if (reference.HashCode != num2 || reference.Key != type)
					{
						num++;
						num4 = _registrations.Entries[num4].Next;
						continue;
					}
					IRegistry<string, IPolicySet> registry = reference.Value;
					if (registry.RequireToGrow)
					{
						registry = ((registry is HashRegistry dictionary) ? new HashRegistry(dictionary) : new HashRegistry(16, (LinkedRegistry)registry));
						_registrations.Entries[num4].Value = registry;
					}
					return registry.SetOrReplace(name, (IPolicySet)(object)registration);
				}
				if (_registrations.RequireToGrow || 8 < num)
				{
					_registrations = new Registrations(_registrations);
					num3 = num2 % _registrations.Buckets.Length;
				}
				ref Registrations.Entry reference2 = ref _registrations.Entries[_registrations.Count];
				reference2.HashCode = num2;
				reference2.Next = _registrations.Buckets[num3];
				reference2.Key = type;
				reference2.Value = new LinkedRegistry(name, (IPolicySet)(object)registration);
				_registrations.Buckets[num3] = _registrations.Count++;
				return null;
			}
		}

		private IPolicySet GetOrAdd(Type type, string name)
		{
			int num = 0;
			int num2 = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num3 = num2 % _registrations.Buckets.Length;
			for (int num4 = _registrations.Buckets[num3]; num4 >= 0; num4 = _registrations.Entries[num4].Next)
			{
				ref Registrations.Entry reference = ref _registrations.Entries[num4];
				if (reference.HashCode == num2 && !(reference.Key != type))
				{
					IPolicySet val = reference.Value?[name];
					if (val != null)
					{
						return val;
					}
				}
			}
			lock (_syncRoot)
			{
				int num5 = _registrations.Buckets[num3];
				while (num5 >= 0)
				{
					ref Registrations.Entry reference2 = ref _registrations.Entries[num5];
					if (reference2.HashCode != num2 || reference2.Key != type)
					{
						num++;
						num5 = _registrations.Entries[num5].Next;
						continue;
					}
					IRegistry<string, IPolicySet> registry = reference2.Value;
					if (registry.RequireToGrow)
					{
						registry = ((registry is HashRegistry dictionary) ? new HashRegistry(dictionary) : new HashRegistry(16, (LinkedRegistry)registry));
						_registrations.Entries[num5].Value = registry;
					}
					return registry.GetOrAdd(name, () => CreateRegistration(type, name));
				}
				if (_registrations.RequireToGrow || 8 < num)
				{
					_registrations = new Registrations(_registrations);
					num3 = num2 % _registrations.Buckets.Length;
				}
				IPolicySet val2 = CreateRegistration(type, name);
				ref Registrations.Entry reference3 = ref _registrations.Entries[_registrations.Count];
				reference3.HashCode = num2;
				reference3.Next = _registrations.Buckets[num3];
				reference3.Key = type;
				reference3.Value = new LinkedRegistry(name, val2);
				_registrations.Buckets[num3] = _registrations.Count++;
				return val2;
			}
		}

		private IPolicySet GetOrAddGeneric(Type type, string name, Type definition)
		{
			int num = 0;
			bool flag = false;
			int num2;
			int num3;
			if (_parent != null)
			{
				num2 = (definition?.GetHashCode() ?? 0) & 0x7FFFFFFF;
				num3 = num2 % _registrations.Buckets.Length;
				for (int num4 = _registrations.Buckets[num3]; num4 >= 0; num4 = _registrations.Entries[num4].Next)
				{
					ref Registrations.Entry reference = ref _registrations.Entries[num4];
					if (reference.HashCode == num2 && !(reference.Key != definition) && reference.Value?[name] != null)
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					return _parent._getGenericRegistration(type, name, definition);
				}
			}
			num2 = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			num3 = num2 % _registrations.Buckets.Length;
			lock (_syncRoot)
			{
				int num5 = _registrations.Buckets[num3];
				while (num5 >= 0)
				{
					ref Registrations.Entry reference2 = ref _registrations.Entries[num5];
					if (reference2.HashCode != num2 || reference2.Key != type)
					{
						num++;
						num5 = _registrations.Entries[num5].Next;
						continue;
					}
					IRegistry<string, IPolicySet> registry = reference2.Value;
					if (registry.RequireToGrow)
					{
						registry = ((registry is HashRegistry dictionary) ? new HashRegistry(dictionary) : new HashRegistry(16, (LinkedRegistry)registry));
						_registrations.Entries[num5].Value = registry;
					}
					return registry.GetOrAdd(name, () => CreateRegistration(type, name));
				}
				if (_registrations.RequireToGrow || 8 < num)
				{
					_registrations = new Registrations(_registrations);
					num3 = num2 % _registrations.Buckets.Length;
				}
				IPolicySet val = CreateRegistration(type, name);
				ref Registrations.Entry reference3 = ref _registrations.Entries[_registrations.Count];
				reference3.HashCode = num2;
				reference3.Next = _registrations.Buckets[num3];
				reference3.Key = type;
				reference3.Value = new LinkedRegistry(name, val);
				_registrations.Buckets[num3] = _registrations.Count++;
				return val;
			}
		}

		private IPolicySet Get(Type type, string name)
		{
			int num = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num2 = num % _registrations.Buckets.Length;
			for (int num3 = _registrations.Buckets[num2]; num3 >= 0; num3 = _registrations.Entries[num3].Next)
			{
				ref Registrations.Entry reference = ref _registrations.Entries[num3];
				if (reference.HashCode == num && !(reference.Key != type))
				{
					return reference.Value?[name];
				}
			}
			return null;
		}

		private void Set(Type type, string name, IPolicySet value)
		{
			int num = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num2 = num % _registrations.Buckets.Length;
			int num3 = 0;
			lock (_syncRoot)
			{
				int num4 = _registrations.Buckets[num2];
				while (num4 >= 0)
				{
					ref Registrations.Entry reference = ref _registrations.Entries[num4];
					if (reference.HashCode != num || reference.Key != type)
					{
						num3++;
						num4 = _registrations.Entries[num4].Next;
						continue;
					}
					IRegistry<string, IPolicySet> registry = reference.Value;
					if (registry.RequireToGrow)
					{
						registry = ((registry is HashRegistry dictionary) ? new HashRegistry(dictionary) : new HashRegistry(16, (LinkedRegistry)registry));
						_registrations.Entries[num4].Value = registry;
					}
					registry[name] = value;
					return;
				}
				if (_registrations.RequireToGrow || 8 < num3)
				{
					_registrations = new Registrations(_registrations);
					num2 = num % _registrations.Buckets.Length;
				}
				ref Registrations.Entry reference2 = ref _registrations.Entries[_registrations.Count];
				reference2.HashCode = num;
				reference2.Next = _registrations.Buckets[num2];
				reference2.Key = type;
				reference2.Value = new LinkedRegistry(name, value);
				_registrations.Buckets[num2] = _registrations.Count++;
			}
		}

		private object Get(Type type, string name, Type policyInterface)
		{
			object obj = null;
			int num = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num2 = num % _registrations.Buckets.Length;
			for (int num3 = _registrations.Buckets[num2]; num3 >= 0; num3 = _registrations.Entries[num3].Next)
			{
				ref Registrations.Entry reference = ref _registrations.Entries[num3];
				if (reference.HashCode == num && !(reference.Key != type))
				{
					IRegistry<string, IPolicySet> value = reference.Value;
					object obj2;
					if (value == null)
					{
						obj2 = null;
					}
					else
					{
						IPolicySet obj3 = value[name];
						obj2 = ((obj3 != null) ? obj3.Get(policyInterface) : null);
					}
					obj = obj2;
					break;
				}
			}
			object obj4 = obj;
			if (obj4 == null)
			{
				UnityContainer parent = _parent;
				if (parent == null)
				{
					return null;
				}
				obj4 = parent.GetPolicy(type, name, policyInterface);
			}
			return obj4;
		}

		private void Set(Type type, string name, Type policyInterface, object policy)
		{
			int num = 0;
			int num2 = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num3 = num2 % _registrations.Buckets.Length;
			lock (_syncRoot)
			{
				int num4 = _registrations.Buckets[num3];
				while (num4 >= 0)
				{
					ref Registrations.Entry reference = ref _registrations.Entries[num4];
					if (reference.HashCode != num2 || reference.Key != type)
					{
						num++;
						num4 = _registrations.Entries[num4].Next;
						continue;
					}
					IRegistry<string, IPolicySet> registry = reference.Value;
					IPolicySet val = registry[name];
					if (val != null)
					{
						val.Set(policyInterface, policy);
						return;
					}
					if (registry.RequireToGrow)
					{
						registry = ((registry is HashRegistry dictionary) ? new HashRegistry(dictionary) : new HashRegistry(16, (LinkedRegistry)registry));
						_registrations.Entries[num4].Value = registry;
					}
					registry.GetOrAdd(name, () => CreateRegistration(type, policyInterface, policy));
					return;
				}
				if (_registrations.RequireToGrow || 8 < num)
				{
					_registrations = new Registrations(_registrations);
					num3 = num2 % _registrations.Buckets.Length;
				}
				IPolicySet value = CreateRegistration(type, policyInterface, policy);
				ref Registrations.Entry reference2 = ref _registrations.Entries[_registrations.Count];
				reference2.HashCode = num2;
				reference2.Next = _registrations.Buckets[num3];
				reference2.Key = type;
				reference2.Value = new LinkedRegistry(name, value);
				_registrations.Buckets[num3] = _registrations.Count++;
			}
		}

		private void Clear(Type type, string name, Type policyInterface)
		{
			int num = (type?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num2 = num % _registrations.Buckets.Length;
			for (int num3 = _registrations.Buckets[num2]; num3 >= 0; num3 = _registrations.Entries[num3].Next)
			{
				ref Registrations.Entry reference = ref _registrations.Entries[num3];
				if (reference.HashCode == num && !(reference.Key != type))
				{
					IRegistry<string, IPolicySet> value = reference.Value;
					if (value != null)
					{
						IPolicySet obj = value[name];
						if (obj != null)
						{
							obj.Clear(policyInterface);
						}
					}
					break;
				}
			}
		}

		private IPolicySet GetDynamicRegistration(Type type, string name)
		{
			IPolicySet val = _get(type, name);
			if (val != null)
			{
				return val;
			}
			TypeInfo typeInfo = type.GetTypeInfo();
			if (typeInfo.IsGenericType)
			{
				return GetOrAddGeneric(type, name, typeInfo.GetGenericTypeDefinition());
			}
			return _root.GetOrAdd(type, name);
		}

		private IPolicySet CreateRegistration(Type type, string name)
		{
			InternalRegistration internalRegistration = new InternalRegistration(type, name);
			if (type.GetTypeInfo().IsGenericType)
			{
				InternalRegistration internalRegistration2 = (InternalRegistration)(object)_get(type.GetGenericTypeDefinition(), name);
				if (internalRegistration2 != null)
				{
					internalRegistration.InjectionMembers = internalRegistration2.InjectionMembers;
					internalRegistration.Map = internalRegistration2.Map;
				}
			}
			internalRegistration.BuildChain = GetBuilders(type, internalRegistration);
			return (IPolicySet)(object)internalRegistration;
		}

		private IPolicySet CreateRegistration(Type type, Type policyInterface, object policy)
		{
			InternalRegistration internalRegistration = new InternalRegistration(policyInterface, policy);
			internalRegistration.BuildChain = GetBuilders(type, internalRegistration);
			return (IPolicySet)(object)internalRegistration;
		}

		internal IEnumerable<TElement> ResolveEnumerable<TElement>(Func<Type, string, InternalRegistration, object> resolve, string name)
		{
			RegistrationSet set = GetRegistrations(this, typeof(TElement));
			for (int i = 0; i < set.Count; i++)
			{
				TElement val;
				try
				{
					if (set[i].RegisteredType.IsGenericTypeDefinition)
					{
						InternalRegistration arg = (InternalRegistration)(object)GetRegistration(typeof(TElement), set[i].Name);
						val = (TElement)resolve(typeof(TElement), set[i].Name, arg);
					}
					else
					{
						val = (TElement)resolve(typeof(TElement), set[i].Name, set[i].Registration);
					}
				}
				catch (MakeGenericTypeFailedException)
				{
					continue;
				}
				catch (ArgumentException ex2) when (ex2.InnerException is TypeLoadException)
				{
					continue;
				}
				yield return val;
			}
			if (set.Count == 0)
			{
				TElement val;
				try
				{
					IPolicySet val2 = GetRegistration(typeof(TElement), name);
					val = (TElement)resolve(typeof(TElement), name, (InternalRegistration)(object)val2);
				}
				catch
				{
					yield break;
				}
				yield return val;
			}
		}

		internal IEnumerable<TElement> ResolveEnumerable<TElement>(Func<Type, string, InternalRegistration, object> resolve, Type generic, string name)
		{
			RegistrationSet set = GetRegistrations(this, typeof(TElement), generic);
			for (int i = 0; i < set.Count; i++)
			{
				TElement val;
				try
				{
					if (set[i].Registration is ContainerRegistration && set[i].RegisteredType.IsGenericTypeDefinition)
					{
						InternalRegistration arg = (InternalRegistration)(object)GetRegistration(typeof(TElement), set[i].Name);
						val = (TElement)resolve(typeof(TElement), set[i].Name, arg);
					}
					else
					{
						val = (TElement)resolve(typeof(TElement), set[i].Name, set[i].Registration);
					}
				}
				catch (MakeGenericTypeFailedException)
				{
					continue;
				}
				catch (ArgumentException ex2) when (ex2.InnerException is TypeLoadException)
				{
					continue;
				}
				yield return val;
			}
			if (set.Count == 0)
			{
				TElement val;
				try
				{
					IPolicySet val2 = GetRegistration(typeof(TElement), name);
					val = (TElement)resolve(typeof(TElement), name, (InternalRegistration)(object)val2);
				}
				catch
				{
					yield break;
				}
				yield return val;
			}
		}

		internal static object ResolveArray<TElement>(ref BuilderContext context)
		{
			Type typeFromHandle = typeof(TElement);
			Type type = (typeFromHandle.IsGenericType ? typeFromHandle.GetGenericTypeDefinition() : typeFromHandle);
			RegistrationSet registrations = ((type == typeFromHandle) ? GetNamedRegistrations((UnityContainer)(object)context.Container, typeFromHandle) : GetNamedRegistrations((UnityContainer)(object)context.Container, typeFromHandle, type));
			return ResolveRegistrations<TElement>(ref context, registrations).ToArray();
		}

		private static IList<TElement> ResolveRegistrations<TElement>(ref BuilderContext context, RegistrationSet registrations)
		{
			Type typeFromHandle = typeof(TElement);
			List<TElement> list = new List<TElement>();
			for (int i = 0; i < registrations.Count; i++)
			{
				ref RegistrationSet.Entry reference = ref registrations[i];
				try
				{
					if (reference.RegisteredType.IsGenericTypeDefinition)
					{
						list.Add((TElement)context.Resolve(typeFromHandle, reference.Name));
					}
					else
					{
						list.Add((TElement)context.Resolve(typeFromHandle, reference.Name, reference.Registration));
					}
				}
				catch (ArgumentException ex) when (ex.InnerException is TypeLoadException)
				{
				}
			}
			return list;
		}

		internal static object ResolveGenericArray<TElement>(ref BuilderContext context, Type type)
		{
			Type type2 = (type.IsGenericType ? type.GetGenericTypeDefinition() : type);
			RegistrationSet registrations = ((type2 == type) ? GetNamedRegistrations((UnityContainer)(object)context.Container, type) : GetNamedRegistrations((UnityContainer)(object)context.Container, type, type2));
			return ResolveGenericRegistrations<TElement>(ref context, registrations).ToArray();
		}

		private static IList<TElement> ResolveGenericRegistrations<TElement>(ref BuilderContext context, RegistrationSet registrations)
		{
			List<TElement> list = new List<TElement>();
			for (int i = 0; i < registrations.Count; i++)
			{
				ref RegistrationSet.Entry reference = ref registrations[i];
				try
				{
					list.Add((TElement)context.Resolve(typeof(TElement), reference.Name));
				}
				catch (MakeGenericTypeFailedException)
				{
				}
				catch (InvalidOperationException ex2) when (ex2.InnerException is InvalidRegistrationException)
				{
				}
			}
			return list;
		}

		private static ResolveDelegate<BuilderContext> OptimizingFactory(ref BuilderContext context)
		{
			int counter = 3;
			Type type = context.Type;
			IPolicySet registration = context.Registration;
			ResolveDelegate<BuilderContext> seed = null;
			MemberProcessor[] chain = ((UnityContainer)(object)context.Container)._processorsChain;
			MemberProcessor[] array = chain;
			foreach (MemberProcessor memberProcessor in array)
			{
				seed = memberProcessor.GetResolver(type, registration, seed);
			}
			return delegate(ref BuilderContext c)
			{
				if (Interlocked.Decrement(ref counter) == 0)
				{
					Task.Factory.StartNew(delegate
					{
						List<Expression> list = new List<Expression>();
						MemberProcessor[] array2 = chain;
						for (int j = 0; j < array2.Length; j++)
						{
							foreach (Expression expression2 in array2[j].GetExpressions(type, registration))
							{
								list.Add(expression2);
							}
						}
						list.Add(BuilderContextExpression.Existing);
						Expression<ResolveDelegate<BuilderContext>> expression = Expression.Lambda<ResolveDelegate<BuilderContext>>(Expression.Block(list), new ParameterExpression[1] { IResolveContextExpression<BuilderContext>.Context });
						registration.Set(typeof(ResolveDelegate<BuilderContext>), (object)expression.Compile());
					});
				}
				return seed?.Invoke(ref c);
			};
		}

		internal ResolveDelegate<BuilderContext> CompilingFactory(ref BuilderContext context)
		{
			List<Expression> list = new List<Expression>();
			Type type = context.Type;
			IPolicySet registration = context.Registration;
			MemberProcessor[] processorsChain = _processorsChain;
			for (int i = 0; i < processorsChain.Length; i++)
			{
				foreach (Expression expression in processorsChain[i].GetExpressions(type, registration))
				{
					list.Add(expression);
				}
			}
			list.Add(BuilderContextExpression.Existing);
			return Expression.Lambda<ResolveDelegate<BuilderContext>>(Expression.Block(list), new ParameterExpression[1] { IResolveContextExpression<BuilderContext>.Context }).Compile();
		}

		internal ResolveDelegate<BuilderContext> ResolvingFactory(ref BuilderContext context)
		{
			ResolveDelegate<BuilderContext> val = null;
			Type type = context.Type;
			IPolicySet registration = context.Registration;
			MemberProcessor[] processorsChain = _processorsChain;
			for (int i = 0; i < processorsChain.Length; i++)
			{
				val = processorsChain[i].GetResolver(type, registration, val);
			}
			return val;
		}

		private object ExecuteValidatingPlan(ref BuilderContext context)
		{
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			int num = -1;
			BuilderStrategy[] buildChain = ((InternalRegistration)(object)context.Registration).BuildChain;
			try
			{
				while (!context.BuildComplete && ++num < buildChain.Length)
				{
					buildChain[num].PreBuildUp(ref context);
				}
				while (--num >= 0)
				{
					buildChain[num].PostBuildUp(ref context);
				}
			}
			catch (Exception ex)
			{
				SynchronizedLifetimeManager requiresRecovery = context.RequiresRecovery;
				if (requiresRecovery != null)
				{
					requiresRecovery.Recover();
				}
				ex.Data.Add(Guid.NewGuid(), (context.Name != null) ? ((context.RegistrationType == context.Type) ? ((object?)new Tuple<Type, string>(context.Type, context.Name)) : ((object?)new Tuple<Type, Type, string>(context.RegistrationType, context.Type, context.Name))) : ((context.RegistrationType == context.Type) ? ((object)context.Type) : ((object)new Tuple<Type, Type>(context.RegistrationType, context.Type))));
				string text = CreateDiagnosticMessage(ex);
				throw new ResolutionFailedException(context.RegistrationType, context.Name, text, ex);
			}
			return context.Existing;
		}

		internal static object ContextValidatingExecutePlan(BuilderStrategy[] chain, ref BuilderContext context)
		{
			int num = -1;
			object obj = GetPerResolveValue(context.Parent, context.RegistrationType, context.Name);
			if (obj != null)
			{
				return obj;
			}
			try
			{
				while (!context.BuildComplete && ++num < chain.Length)
				{
					chain[num].PreBuildUp(ref context);
				}
				while (--num >= 0)
				{
					chain[num].PostBuildUp(ref context);
				}
			}
			catch (Exception ex)
			{
				SynchronizedLifetimeManager requiresRecovery = context.RequiresRecovery;
				if (requiresRecovery != null)
				{
					requiresRecovery.Recover();
				}
				ex.Data.Add(Guid.NewGuid(), (context.Name != null) ? ((context.RegistrationType == context.Type) ? ((object?)new Tuple<Type, string>(context.Type, context.Name)) : ((object?)new Tuple<Type, Type, string>(context.RegistrationType, context.Type, context.Name))) : ((context.RegistrationType == context.Type) ? ((object)context.Type) : ((object)new Tuple<Type, Type>(context.RegistrationType, context.Type))));
				throw;
			}
			return context.Existing;
			unsafe static object GetPerResolveValue(IntPtr parent, Type registrationType, string name)
			{
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ab: Expected O, but got Unknown
				if (IntPtr.Zero == parent)
				{
					return null;
				}
				BuilderContext builderContext = Unsafe.AsRef<BuilderContext>(parent.ToPointer());
				if (registrationType != builderContext.RegistrationType || name != builderContext.Name)
				{
					return GetPerResolveValue(builderContext.Parent, registrationType, name);
				}
				LifetimeManager val = (LifetimeManager)builderContext.Get(typeof(LifetimeManager));
				object obj2 = (((int)val != 0) ? val.GetValue((ILifetimeContainer)null) : null);
				if (LifetimeManager.NoValue != obj2)
				{
					return obj2;
				}
				throw new InvalidOperationException($"Circular reference for Type: {builderContext.Type}, Name: {builderContext.Name}", (Exception?)new CircularDependencyException(builderContext.Type, builderContext.Name));
			}
		}

		internal unsafe static object ContextValidatingResolvePlan(ref BuilderContext thisContext, ResolveDelegate<BuilderContext> resolver)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (resolver == null)
			{
				throw new ArgumentNullException("resolver");
			}
			IntPtr parent = thisContext.Parent;
			while (IntPtr.Zero != parent)
			{
				BuilderContext builderContext = Unsafe.AsRef<BuilderContext>(parent.ToPointer());
				if (thisContext.RegistrationType == builderContext.RegistrationType && thisContext.Name == builderContext.Name)
				{
					throw new CircularDependencyException(thisContext.Type, thisContext.Name);
				}
				parent = builderContext.Parent;
			}
			BuilderContext builderContext2 = default(BuilderContext);
			builderContext2.Lifetime = thisContext.Lifetime;
			builderContext2.Registration = thisContext.Registration;
			builderContext2.RegistrationType = thisContext.Type;
			builderContext2.Name = thisContext.Name;
			builderContext2.Type = thisContext.Type;
			builderContext2.ExecutePlan = thisContext.ExecutePlan;
			builderContext2.ResolvePlan = thisContext.ResolvePlan;
			builderContext2.List = thisContext.List;
			builderContext2.Overrides = thisContext.Overrides;
			builderContext2.DeclaringType = thisContext.Type;
			builderContext2.Parent = new IntPtr(Unsafe.AsPointer(ref thisContext));
			BuilderContext builderContext3 = builderContext2;
			return resolver.Invoke(ref builderContext3);
		}
	}
	internal static class Error
	{
		public const string MissingDependency = "Could not resolve dependency for build key {0}.";

		public const string NoOperationExceptionReason = "while resolving";

		public const string NotAGenericType = "The type {0} is not a generic type, and you are attempting to inject a generic parameter named '{1}'.";

		public const string ResolutionFailed = "Resolution of the dependency failed, type = '{0}', name = '{1}'.\nException occurred while: {2}.\nException is: {3} - {4}\n-----------------------------------------------\nAt the time of the exception, the container was: ";

		public const string SelectedConstructorHasRefParameters = "The constructor {1} selected for type {0} has ref or out parameters. Such parameters are not supported for constructor injection.";

		public const string SelectedConstructorHasRefItself = "The constructor {1} selected for type {0} has reference to itself. Such references create infinite loop during resolving.";

		public const string TypesAreNotAssignable = "The type {1} cannot be assigned to variables of type {0}.";

		public const string UnknownType = "<unknown>";
	}
}
namespace Unity.Utility
{
	internal static class HashHelpers
	{
		public static readonly int[] Primes = new int[73]
		{
			1, 3, 7, 11, 17, 23, 29, 37, 47, 59,
			71, 89, 107, 131, 163, 197, 239, 293, 353, 431,
			521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801,
			3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519,
			21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631,
			130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827,
			807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287,
			4999559, 5999471, 7199369
		};

		internal const int HashPrime = 101;

		public const int MaxPrimeArrayLength = 2146435069;

		public static bool IsPrime(int candidate)
		{
			if (((uint)candidate & (true ? 1u : 0u)) != 0)
			{
				int num = (int)Math.Sqrt(candidate);
				for (int i = 3; i <= num; i += 2)
				{
					if (candidate % i == 0)
					{
						return false;
					}
				}
				return true;
			}
			return candidate == 2;
		}

		public static int GetPrime(int min)
		{
			if (min < 0)
			{
				throw new ArgumentException("Capacity Overflow");
			}
			for (int i = 0; i < Primes.Length; i++)
			{
				int num = Primes[i];
				if (num >= min)
				{
					return num;
				}
			}
			for (int j = min | 1; j < int.MaxValue; j += 2)
			{
				if (IsPrime(j) && (j - 1) % 101 != 0)
				{
					return j;
				}
			}
			return min;
		}

		public static int GetMinPrime()
		{
			return Primes[0];
		}

		public static int ExpandPrime(int oldSize)
		{
			int num = 2 * oldSize;
			if ((uint)num > 2146435069u && 2146435069 > oldSize)
			{
				return 2146435069;
			}
			return GetPrime(num);
		}
	}
}
namespace Unity.Strategies
{
	public class ArrayResolveStrategy : BuilderStrategy
	{
		private delegate object ResolveArrayDelegate(ref BuilderContext context, Type type);

		private readonly MethodInfo _resolveMethod;

		private readonly MethodInfo _resolveGenericMethod;

		public ArrayResolveStrategy(MethodInfo method, MethodInfo generic)
		{
			_resolveMethod = method;
			_resolveGenericMethod = generic;
		}

		public override bool RequiredToBuildType(IUnityContainer container, Type type, InternalRegistration registration, params InjectionMember[] injectionMembers)
		{
			if (registration is ContainerRegistration containerRegistration && (type != containerRegistration.Type || (injectionMembers != null && injectionMembers.Any((InjectionMember i) => i is InjectionFactory))))
			{
				return false;
			}
			if (null != type && type.IsArray)
			{
				return type.GetArrayRank() == 1;
			}
			return false;
		}

		public override void PreBuildUp(ref BuilderContext context)
		{
			ResolveDelegate<BuilderContext> val = PolicySetExtensions.Get<ResolveDelegate<BuilderContext>>(context.Registration);
			if (val == null)
			{
				Type elementType = context.RegistrationType.GetElementType();
				Type type = ((UnityContainer)(object)context.Container).GetFinalType(elementType);
				if (type != elementType)
				{
					ResolveArrayDelegate method = (ResolveArrayDelegate)_resolveGenericMethod.MakeGenericMethod(elementType).CreateDelegate(typeof(ResolveArrayDelegate));
					val = delegate(ref BuilderContext c)
					{
						return method(ref c, type);
					};
				}
				else
				{
					val = (ResolveDelegate<BuilderContext>)(object)_resolveMethod.MakeGenericMethod(elementType).CreateDelegate(typeof(ResolveDelegate<BuilderContext>));
				}
				context.Registration.Set(typeof(ResolveDelegate<BuilderContext>), (object)val);
			}
			context.Existing = val.Invoke(ref context);
			context.BuildComplete = true;
		}
	}
	public abstract class BuilderStrategy
	{
		public virtual void PreBuildUp(ref BuilderContext context)
		{
		}

		public virtual void PostBuildUp(ref BuilderContext context)
		{
		}

		public virtual bool RequiredToBuildType(IUnityContainer container, Type type, InternalRegistration registration, params InjectionMember[] injectionMembers)
		{
			return true;
		}

		public virtual bool RequiredToResolveInstance(IUnityContainer container, InternalRegistration registration)
		{
			return false;
		}

		public static TPolicyInterface GetPolicy<TPolicyInterface>(ref BuilderContext context)
		{
			return (TPolicyInterface)(context.Get(context.RegistrationType, context.Name, typeof(TPolicyInterface)) ?? (context.RegistrationType.IsGenericType ? (context.Get(context.RegistrationType.GetGenericTypeDefinition(), context.Name, typeof(TPolicyInterface)) ?? context.Get(null, null, typeof(TPolicyInterface))) : context.Get(null, null, typeof(TPolicyInterface))));
		}
	}
	public class BuildKeyMappingStrategy : BuilderStrategy
	{
		public override bool RequiredToBuildType(IUnityContainer container, Type type, InternalRegistration registration, params InjectionMember[] injectionMembers)
		{
			ContainerRegistration containerRegistration;
			if ((containerRegistration = registration as ContainerRegistration) == null)
			{
				return registration.Map != null;
			}
			if (null == containerRegistration.Type || type == containerRegistration.Type)
			{
				return false;
			}
			if (type.IsGenericTypeDefinition && containerRegistration.Type.IsGenericTypeDefinition && containerRegistration.Map == null)
			{
				containerRegistration.Map = delegate(Type t)
				{
					if (t.IsGenericTypeDefinition)
					{
						return containerRegistration.Type;
					}
					if (t.GenericTypeArguments.Length != containerRegistration.Type.GetTypeInfo().GenericTypeParameters.Length)
					{
						throw new ArgumentException("Invalid number of generic arguments in types: {registration.MappedToType} and {t}");
					}
					try
					{
						return containerRegistration.Type.MakeGenericType(t.GenericTypeArguments);
					}
					catch (ArgumentException innerException)
					{
						throw new MakeGenericTypeFailedException(innerException);
					}
				};
			}
			return true;
		}

		public override void PreBuildUp(ref BuilderContext context)
		{
			Converter<Type, Type> map = ((InternalRegistration)(object)context.Registration).Map;
			if (map != null)
			{
				context.Type = map(context.Type);
			}
			if (!((InternalRegistration)(object)context.Registration).BuildRequired && ((UnityContainer)(object)context.Container).RegistrationExists(context.Type, context.Name))
			{
				context.Existing = context.Resolve(context.Type, context.Name);
				context.BuildComplete = true;
			}
		}
	}
	public class BuildPlanStrategy : BuilderStrategy
	{
		public override bool RequiredToBuildType(IUnityContainer container, Type type, InternalRegistration registration, params InjectionMember[] injectionMembers)
		{
			registration.BuildRequired = (injectionMembers != null && injectionMembers.Any((InjectionMember m) => m.BuildRequired)) || (registration is ContainerRegistration containerRegistration && containerRegistration.LifetimeManager is PerResolveLifetimeManager);
			return true;
		}

		public override void PreBuildUp(ref BuilderContext context)
		{
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			ResolveDelegate<BuilderContext> val = PolicySetExtensions.Get<ResolveDelegate<BuilderContext>>(context.Registration) ?? ((ResolveDelegate<BuilderContext>)GetGeneric(ref context, typeof(ResolveDelegate<BuilderContext>)));
			if (val == null)
			{
				if (!(context.Registration is ContainerRegistration) && context.RegistrationType.IsGenericTypeDefinition)
				{
					throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The type {0} is an open generic type. An open generic type cannot be resolved.", context.RegistrationType.FullName), new InvalidRegistrationException());
				}
				if (context.Type.IsArray && context.Type.GetArrayRank() > 1)
				{
					throw new ArgumentException($"Invalid array {context.Type}. Only arrays of rank 1 are supported", new InvalidRegistrationException());
				}
				ResolveDelegateFactory resolveDelegateFactory = PolicySetExtensions.Get<ResolveDelegateFactory>(context.Registration) ?? ((ResolveDelegateFactory)(context.Get(context.Type, "ALL", typeof(ResolveDelegateFactory)) ?? GetGeneric(ref context, typeof(ResolveDelegateFactory)) ?? context.Get(null, null, typeof(ResolveDelegateFactory))));
				if (resolveDelegateFactory == null)
				{
					throw new ResolutionFailedException(context.Type, context.Name, $"Failed to find Resolve Delegate Factory for Type {context.Type}", (Exception)null);
				}
				val = resolveDelegateFactory(ref context);
				context.Registration.Set(typeof(ResolveDelegate<BuilderContext>), (object)val);
				context.Existing = val.Invoke(ref context);
			}
			else
			{
				context.Existing = val.Invoke(ref context);
			}
		}

		protected static TPolicyInterface Get_Policy<TPolicyInterface>(ref BuilderContext context, Type type, string name)
		{
			return (TPolicyInterface)(GetGeneric(ref context, typeof(TPolicyInterface), type, name) ?? context.Get(null, null, typeof(TPolicyInterface)));
		}

		protected static object GetGeneric(ref BuilderContext context, Type policyInterface)
		{
			if (context.Registration is ContainerRegistration && null != context.Type)
			{
				if (context.Type.IsGenericType)
				{
					Type genericTypeDefinition = context.Type.GetGenericTypeDefinition();
					return context.Get(genericTypeDefinition, context.Name, policyInterface) ?? context.Get(genericTypeDefinition, "ALL", policyInterface);
				}
			}
			else if (context.RegistrationType.IsGenericType)
			{
				Type genericTypeDefinition2 = context.RegistrationType.GetGenericTypeDefinition();
				return context.Get(genericTypeDefinition2, context.Name, policyInterface) ?? context.Get(genericTypeDefinition2, "ALL", policyInterface);
			}
			return null;
		}

		protected static object GetGeneric(ref BuilderContext context, Type policyInterface, Type type, string name)
		{
			if (type.IsGenericType)
			{
				Type genericTypeDefinition = type.GetGenericTypeDefinition();
				return context.Get(genericTypeDefinition, name, policyInterface) ?? context.Get(genericTypeDefinition, "ALL", policyInterface);
			}
			return null;
		}
	}
	public class LifetimeStrategy : BuilderStrategy
	{
		private readonly object _genericLifetimeManagerLock = new object();

		public override void PreBuildUp(ref BuilderContext context)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			LifetimeManager val = null;
			if (context.Registration is ContainerRegistration containerRegistration)
			{
				val = containerRegistration.LifetimeManager;
			}
			if (val == null || val is PerResolveLifetimeManager)
			{
				val = (LifetimeManager)context.Get(typeof(LifetimeManager));
			}
			if (val == null)
			{
				if (!context.RegistrationType.IsGenericType)
				{
					return;
				}
				LifetimeManager val2 = (LifetimeManager)context.Get(context.Type.GetGenericTypeDefinition(), context.Name, typeof(LifetimeManager));
				if (val2 == null)
				{
					return;
				}
				lock (_genericLifetimeManagerLock)
				{
					val = (LifetimeManager)context.Registration.Get(typeof(LifetimeManager));
					if (val == null)
					{
						val = val2.CreateLifetimePolicy();
						context.Registration.Set(typeof(LifetimeManager), (object)val);
						if (val is IDisposable)
						{
							context.Lifetime.Add((object)val);
						}
					}
				}
			}
			SynchronizedLifetimeManager requiresRecovery;
			if ((requiresRecovery = (SynchronizedLifetimeManager)(object)((val is SynchronizedLifetimeManager) ? val : null)) != null)
			{
				context.RequiresRecovery = requiresRecovery;
			}
			object value = val.GetValue(context.Lifetime);
			if (LifetimeManager.NoValue != value)
			{
				context.Existing = value;
				context.BuildComplete = true;
			}
		}

		public override void PostBuildUp(ref BuilderContext context)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			LifetimeManager val = null;
			if (context.Registration is ContainerRegistration containerRegistration)
			{
				val = containerRegistration.LifetimeManager;
			}
			if (val == null || val is PerResolveLifetimeManager)
			{
				val = (LifetimeManager)context.Get(typeof(LifetimeManager));
			}
			if (val != null)
			{
				val.SetValue(context.Existing, context.Lifetime);
			}
		}

		public override bool RequiredToBuildType(IUnityContainer container, Type type, InternalRegistration registration, params InjectionMember[] injectionMembers)
		{
			object obj = registration.Get(typeof(LifetimeManager));
			if (obj != null)
			{
				if (!(obj is TransientLifetimeManager))
				{
					return true;
				}
				return false;
			}
			if (!(registration is ContainerRegistration) && null != type && type.IsGenericType)
			{
				return true;
			}
			return false;
		}

		public override bool RequiredToResolveInstance(IUnityContainer container, InternalRegistration registration)
		{
			return true;
		}
	}
}
namespace Unity.Storage
{
	[SecuritySafeCritical]
	[DebuggerDisplay("HashRegistry ({Count}) ")]
	internal class HashRegistry : IRegistry<string, IPolicySet>
	{
		[DebuggerDisplay("Key='{Key}'   Value='{Value}'   Hash='{HashCode}'")]
		public struct Entry
		{
			public int HashCode;

			public int Next;

			public string Key;

			public IPolicySet Value;
		}

		private const float LoadFactor = 0.72f;

		public readonly int[] Buckets;

		public readonly Entry[] Entries;

		public int Count;

		public IPolicySet this[string key]
		{
			get
			{
				IPolicySet result = null;
				int num = ((key != null) ? (key.GetHashCode() & 0x7FFFFFFF) : 0);
				for (int num2 = Buckets[num % Buckets.Length]; num2 >= 0; num2 = Entries[num2].Next)
				{
					ref Entry reference = ref Entries[num2];
					if (reference.HashCode == num && object.Equals(reference.Key, key))
					{
						return reference.Value;
					}
					if ((object)reference.Key == "ALL")
					{
						result = reference.Value;
					}
				}
				return result;
			}
			set
			{
				int num = ((key != null) ? (key.GetHashCode() & 0x7FFFFFFF) : 0);
				int num2 = num % Buckets.Length;
				for (int num3 = Buckets[num2]; num3 >= 0; num3 = Entries[num3].Next)
				{
					if (Entries[num3].HashCode == num && object.Equals(Entries[num3].Key, key))
					{
						Entries[num3].Value = value;
						return;
					}
				}
				Entries[Count].HashCode = num;
				Entries[Count].Next = Buckets[num2];
				Entries[Count].Key = key;
				Entries[Count].Value = value;
				Buckets[num2] = Count;
				Count++;
			}
		}

		public bool RequireToGrow
		{
			get
			{
				if (Entries.Length - Count < 100)
				{
					return (float)Count / (float)Entries.Length > 0.72f;
				}
				return false;
			}
		}

		public IEnumerable<string> Keys
		{
			get
			{
				for (int i = 0; i < Count; i++)
				{
					yield return Entries[i].Key;
				}
			}
		}

		public IEnumerable<IPolicySet> Values
		{
			get
			{
				for (int i = 0; i < Count; i++)
				{
					yield return Entries[i].Value;
				}
			}
		}

		public unsafe HashRegistry(int capacity)
		{
			int prime = HashHelpers.GetPrime(capacity);
			Buckets = new int[prime];
			Entries = new Entry[prime];
			fixed (int* ptr = Buckets)
			{
				int* ptr2 = ptr;
				int* ptr3 = ptr + Buckets.Length;
				while (ptr2 < ptr3)
				{
					*(ptr2++) = -1;
				}
			}
		}

		public HashRegistry(int capacity, LinkedNode<string, IPolicySet> head)
			: this(capacity)
		{
			for (LinkedNode<string, IPolicySet> linkedNode = head; linkedNode != null; linkedNode = linkedNode.Next)
			{
				this[linkedNode.Key] = linkedNode.Value;
			}
		}

		public HashRegistry(HashRegistry dictionary)
			: this(HashHelpers.GetPrime(dictionary.Entries.Length * 2))
		{
			Array.Copy(dictionary.Entries, 0, Entries, 0, dictionary.Count);
			for (int i = 0; i < dictionary.Count; i++)
			{
				int hashCode = Entries[i].HashCode;
				if (hashCode >= 0)
				{
					int num = hashCode % Buckets.Length;
					Entries[i].Next = Buckets[num];
					Buckets[num] = i;
				}
			}
			Count = dictionary.Count;
			dictionary.Count = 0;
		}

		public IPolicySet GetOrAdd(string key, Func<IPolicySet> factory)
		{
			int num = (key?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num2 = num % Buckets.Length;
			for (int num3 = Buckets[num2]; num3 >= 0; num3 = Entries[num3].Next)
			{
				ref Entry reference = ref Entries[num3];
				if (reference.HashCode == num && object.Equals(reference.Key, key))
				{
					return reference.Value;
				}
			}
			IPolicySet val = factory();
			ref Entry reference2 = ref Entries[Count];
			reference2.HashCode = num;
			reference2.Next = Buckets[num2];
			reference2.Key = key;
			reference2.Value = val;
			Buckets[num2] = Count++;
			return val;
		}

		public IPolicySet SetOrReplace(string key, IPolicySet value)
		{
			int num = (key?.GetHashCode() ?? 0) & 0x7FFFFFFF;
			int num2 = num % Buckets.Length;
			for (int num3 = Buckets[num2]; num3 >= 0; num3 = Entries[num3].Next)
			{
				ref Entry reference = ref Entries[num3];
				if (reference.HashCode == num && object.Equals(reference.Key, key))
				{
					IPolicySet value2 = reference.Value;
					reference.Value = value;
					return value2;
				}
			}
			ref Entry reference2 = ref Entries[Count];
			reference2.HashCode = num;
			reference2.Next = Buckets[num2];
			reference2.Key = key;
			reference2.Value = value;
			Buckets[num2] = Count++;
			return null;
		}
	}
	public interface IRegistry<TKey, TValue>
	{
		TValue this[TKey index] { get; set; }

		bool RequireToGrow { get; }

		IEnumerable<TKey> Keys { get; }

		IEnumerable<TValue> Values { get; }

		TValue GetOrAdd(TKey key, Func<TValue> factory);

		TValue SetOrReplace(TKey key, TValue value);
	}
	public interface IStagedStrategyChain<in TStrategyType, in TStageEnum>
	{
		event EventHandler<EventArgs> Invalidated;

		void Add(TStrategyType strategy, TStageEnum stage);
	}
	public static class StagedStrategyChainExtensions
	{
		public static void AddNew<TStrategy, TStageEnum>(this IStagedStrategyChain<TStrategy, TStageEnum> chain, TStageEnum stage) where TStrategy : new()
		{
			chain.Add(new TStrategy(), stage);
		}
	}
	[DebuggerDisplay("Node:  Key={Key},  Value={Value}")]
	public class LinkedNode<TKey, TValue>
	{
		public TKey Key;

		public TValue Value;

		public LinkedNode<TKey, TValue> Next;
	}
	[DebuggerDisplay("LinkedRegistry ({_count}) ")]
	internal class LinkedRegistry : LinkedNode<string, IPolicySet>, IRegistry<string, IPolicySet>
	{
		private int _count;

		public const int ListToHashCutoverPoint = 8;

		public IPolicySet this[string key]
		{
			get
			{
				IPolicySet result = null;
				for (LinkedNode<string, IPolicySet> linkedNode = this; linkedNode != null; linkedNode = linkedNode.Next)
				{
					if (object.Equals(linkedNode.Key, key))
					{
						return linkedNode.Value;
					}
					if ((object)linkedNode.Key == "ALL")
					{
						result = linkedNode.Value;
					}
				}
				return result;
			}
			set
			{
				LinkedNode<string, IPolicySet> linkedNode = null;
				for (LinkedNode<string, IPolicySet> linkedNode2 = this; linkedNode2 != null; linkedNode2 = linkedNode2.Next)
				{
					if (object.Equals(linkedNode2.Key, key))
					{
						linkedNode2.Value = value;
						return;
					}
					linkedNode = linkedNode2;
				}
				linkedNode.Next = new LinkedNode<string, IPolicySet>
				{
					Key = key,
					Value = value
				};
				_count++;
			}
		}

		public bool RequireToGrow => 8 < _count;

		public IEnumerable<string> Keys
		{
			get
			{
				for (LinkedNode<string, IPolicySet> node = this; node != null; node = node.Next)
				{
					yield return node.Key;
				}
			}
		}

		public IEnumerable<IPolicySet> Values
		{
			get
			{
				for (LinkedNode<string, IPolicySet> node = this; node != null; node = node.Next)
				{
					yield return node.Value;
				}
			}
		}

		public LinkedRegistry(string key, IPolicySet value)
		{
			Key = key;
			Value = value;
		}

		public IPolicySet GetOrAdd(string name, Func<IPolicySet> factory)
		{
			LinkedNode<string, IPolicySet> linkedNode = null;
			for (LinkedNode<string, IPolicySet> linkedNode2 = this; linkedNode2 != null; linkedNode2 = linkedNode2.Next)
			{
				if (object.Equals(linkedNode2.Key, name))
				{
					if (linkedNode2.Value == null)
					{
						linkedNode2.Value = factory();
					}
					return linkedNode2.Value;
				}
				linkedNode = linkedNode2;
			}
			linkedNode.Next = new LinkedNode<string, IPolicySet>
			{
				Key = name,
				Value = factory()
			};
			_count++;
			return linkedNode.Next.Value;
		}

		public IPolicySet SetOrReplace(string name, IPolicySet value)
		{
			LinkedNode<string, IPolicySet> linkedNode = null;
			for (LinkedNode<string, IPolicySet> linkedNode2 = this; linkedNode2 != null; linkedNode2 = linkedNode2.Next)
			{
				if (object.Equals(linkedNode2.Key, name))
				{
					IPolicySet value2 = linkedNode2.Value;
					linkedNode2.Value = value;
					return value2;
				}
				linkedNode = linkedNode2;
			}
			linkedNode.Next = new LinkedNode<string, IPolicySet>
			{
				Key = name,
				Value = value
			};
			_count++;
			return null;
		}
	}
	public class PolicyList : IPolicyList
	{
		private struct PolicyKey
		{
			private readonly int _hash;

			private readonly Type _type;

			priv

Unity.Microsoft.Logging.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using Microsoft.Extensions.Logging;
using Unity.Builder;
using Unity.Extension;
using Unity.Policy;
using Unity.Resolution;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Unity Open Source Project")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © Unity Container Project 2018")]
[assembly: AssemblyDescription("Unity adapter for Microsoft.Extensions.Logging")]
[assembly: AssemblyFileVersion("5.11.1.0")]
[assembly: AssemblyInformationalVersion("5.11.1+1c24a00ecdaeebdf421bbc0c0ea204baba828983")]
[assembly: AssemblyProduct("Unity.Microsoft.Logging")]
[assembly: AssemblyTitle("Unity.Microsoft.Logging")]
[assembly: AssemblyVersion("5.11.1.0")]
namespace Unity.Microsoft.Logging;

[SecuritySafeCritical]
public class LoggingExtension : UnityContainerExtension
{
	private delegate object GenericLoggerFactory(ILoggerFactory factory);

	private static readonly MethodInfo CreateLoggerMethod = typeof(LoggingExtension).GetTypeInfo().GetDeclaredMethod("CreateLogger");

	public ILoggerFactory LoggerFactory { get; }

	[InjectionConstructor]
	public LoggingExtension()
		: this(new LoggerFactory())
	{
	}

	public LoggingExtension(ILoggerFactory factory)
	{
		LoggerFactory = factory ?? new LoggerFactory();
	}

	protected override void Initialize()
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Expected O, but got Unknown
		((UnityContainerExtension)this).Context.Policies.Set(typeof(ILogger), "ALL", typeof(ResolveDelegateFactory), (object)new ResolveDelegateFactory(GetResolver));
		((UnityContainerExtension)this).Context.Policies.Set(typeof(ILogger<>), "ALL", typeof(ResolveDelegateFactory), (object)new ResolveDelegateFactory(GetResolverGeneric));
		((UnityContainerExtension)this).Container.RegisterFactory(typeof(ILoggerFactory), "ALL", (Func<IUnityContainer, Type, string, object>)((IUnityContainer c, Type t, string n) => LoggerFactory), FactoryLifetime.Singleton);
	}

	public ResolveDelegate<BuilderContext> GetResolver(ref BuilderContext context)
	{
		return delegate(ref BuilderContext c)
		{
			Type declaringType = c.DeclaringType;
			return (!(null == declaringType)) ? LoggerFactory.CreateLogger(declaringType) : LoggerFactory.CreateLogger(((BuilderContext)(ref c)).Name ?? "ALL");
		};
	}

	public ResolveDelegate<BuilderContext> GetResolverGeneric(ref BuilderContext context)
	{
		Type type = ((BuilderContext)(ref context)).Type.GetTypeInfo().GenericTypeArguments[0];
		GenericLoggerFactory buildMethod = (GenericLoggerFactory)CreateLoggerMethod.MakeGenericMethod(type).CreateDelegate(typeof(GenericLoggerFactory));
		return delegate(ref BuilderContext c)
		{
			((BuilderContext)(ref c)).Existing = buildMethod(LoggerFactory);
			return ((BuilderContext)(ref c)).Existing;
		};
	}

	private static object CreateLogger<TElement>(ILoggerFactory factory)
	{
		return factory.CreateLogger<TElement>();
	}
}

VsTwitch.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using EntityStates.Missions.BrotherEncounter;
using HG;
using HG.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using On.EntityStates.Missions.BrotherEncounter;
using On.RoR2;
using RiskOfOptions;
using RiskOfOptions.OptionConfigs;
using RiskOfOptions.Options;
using RoR2;
using RoR2.Artifacts;
using RoR2.CharacterAI;
using RoR2.Networking;
using RoR2.UI;
using Tiltify;
using Tiltify.Events;
using TwitchLib.Api;
using TwitchLib.Api.Auth;
using TwitchLib.Api.Core.Interfaces;
using TwitchLib.Client;
using TwitchLib.Client.Enums;
using TwitchLib.Client.Events;
using TwitchLib.Client.Models;
using TwitchLib.Client.Models.Interfaces;
using TwitchLib.Communication.Events;
using TwitchLib.Communication.Interfaces;
using TwitchLib.PubSub;
using TwitchLib.PubSub.Events;
using TwitchLib.Unity;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;
using VsTwitch.Data;
using VsTwitch.ModCompatibility;
using VsTwitch.Twitch;
using VsTwitch.Twitch.Auth;
using VsTwitch.Twitch.Auth.Models;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: OptIn]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("VsTwitch")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+f245fd8f8feda140c82e72c54832031cef83810c")]
[assembly: AssemblyProduct("VsTwitch")]
[assembly: AssemblyTitle("VsTwitch")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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;
		}
	}
}
namespace VsTwitch
{
	public class Configuration
	{
		public enum VoteStrategies
		{
			MaxVote,
			MaxVoteRandomTie,
			Percentile
		}

		public ConfigEntry<bool> TwitchDebugLogs { get; }

		public ConfigEntry<bool> EnableItemVoting { get; }

		public ConfigEntry<int> VoteDurationSec { get; }

		public ConfigEntry<VoteStrategies> VoteStrategy { get; }

		public ConfigEntry<bool> EnableBitEvents { get; }

		public ConfigEntry<int> BitsThreshold { get; }

		public ConfigEntry<int> CurrentBits { get; }

		public ConfigEntry<bool> PublishToChat { get; }

		public ConfigEntry<string> TiltifyCampaignId { get; }

		public ConfigEntry<float> BitStormWeight { get; }

		public ConfigEntry<float> BountyWeight { get; }

		public ConfigEntry<float> ShrineOfOrderWeight { get; }

		public ConfigEntry<float> ShrineOfTheMountainWeight { get; }

		public ConfigEntry<float> TitanWeight { get; }

		public ConfigEntry<float> LunarWispWeight { get; }

		public ConfigEntry<float> MithrixWeight { get; }

		public ConfigEntry<float> ElderLemurianWeight { get; }

		public ConfigEntry<bool> ChannelPointsEnable { get; }

		public ConfigEntry<string> ChannelPointsAllyBeetle { get; }

		public ConfigEntry<string> ChannelPointsAllyLemurian { get; }

		public ConfigEntry<string> ChannelPointsAllyElderLemurian { get; }

		public ConfigEntry<string> ChannelPointsRustedKey { get; }

		public ConfigEntry<string> ChannelPointsBitStorm { get; }

		public ConfigEntry<string> ChannelPointsBounty { get; }

		public ConfigEntry<string> ChannelPointsShrineOfOrder { get; }

		public ConfigEntry<string> ChannelPointsShrineOfTheMountain { get; }

		public ConfigEntry<string> ChannelPointsTitan { get; }

		public ConfigEntry<string> ChannelPointsLunarWisp { get; }

		public ConfigEntry<string> ChannelPointsMithrix { get; }

		public ConfigEntry<string> ChannelPointsElderLemurian { get; }

		public ConfigEntry<bool> SimpleUI { get; }

		public ConfigEntry<bool> EnableChoosingLunarItems { get; }

		public ConfigEntry<bool> ForceUniqueRolls { get; }

		public Configuration(BaseUnityPlugin plugin, UnityAction reloadChannelPoints)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			EnsureConfigsRemoved(plugin.Config, new List<ConfigDefinition>
			{
				new ConfigDefinition("Twitch", "Channel"),
				new ConfigDefinition("Twitch", "ClientID"),
				new ConfigDefinition("Twitch", "Username"),
				new ConfigDefinition("Twitch", "ImplicitOAuth"),
				new ConfigDefinition("Language", "EnableLanguageEdits")
			});
			TwitchDebugLogs = plugin.Config.Bind<bool>("Twitch", "DebugLogs", false, "Enable debug logging for Twitch - will spam to the console!");
			EnableItemVoting = plugin.Config.Bind<bool>("Twitch", "EnableItemVoting", true, "Enable item voting on Twitch.");
			VoteDurationSec = plugin.Config.Bind<int>("Twitch", "VoteDurationdSec", 10, "How long to allow twitch voting.");
			VoteStrategy = plugin.Config.Bind<VoteStrategies>("Twitch", "VoteStrategy", VoteStrategies.MaxVote, "How to tabulate votes. One of: MaxVote, MaxVoteRandomTie, Percentile");
			EnableBitEvents = plugin.Config.Bind<bool>("Twitch", "EnableBitEvents", true, "Enable bit events from Twitch.");
			BitsThreshold = plugin.Config.Bind<int>("Twitch", "BitsThreshold", 1500, "How many Bits are needed before something happens.");
			CurrentBits = plugin.Config.Bind<int>("Twitch", "CurrentBits", 0, "(DO NOT EDIT) How many Bits have currently been donated.");
			PublishToChat = plugin.Config.Bind<bool>("Twitch", "PublishToChat", true, "Publish events (like voting) to Twitch chat.");
			TiltifyCampaignId = plugin.Config.Bind<string>("Tiltify", "CampaignId", "", "Tiltify Campaign ID to track donations");
			BitStormWeight = plugin.Config.Bind<float>("Event", "BitStormWeight", 1f, "Weight for the bit storm bit event. Set to 0 to disable.");
			BountyWeight = plugin.Config.Bind<float>("Event", "BountyWeight", 1f, "Weight for the doppleganger bit event. Set to 0 to disable.");
			ShrineOfOrderWeight = plugin.Config.Bind<float>("Event", "ShrineOfOrderWeight", 1f, "Weight for the Shrine of Order bit event. Set to 0 to disable.");
			ShrineOfTheMountainWeight = plugin.Config.Bind<float>("Event", "ShrineOfTheMountainWeight", 1f, "Weight for the Shrine of the Mountain bit event. Set to 0 to disable.");
			TitanWeight = plugin.Config.Bind<float>("Event", "TitanWeight", 1f, "Weight for the Aurelionite bit event. Set to 0 to disable.");
			LunarWispWeight = plugin.Config.Bind<float>("Event", "LunarWispWeight", 1f, "Weight for the Lunar Chimera (Wisp) bit event. Set to 0 to disable.");
			MithrixWeight = plugin.Config.Bind<float>("Event", "MithrixWeight", 1f, "Weight for the Mithrix bit event. Set to 0 to disable.");
			ElderLemurianWeight = plugin.Config.Bind<float>("Event", "ElderLemurianWeight", 1f, "Weight for the Elder Lemurian bit event. Set to 0 to disable.");
			ChannelPointsEnable = plugin.Config.Bind<bool>("ChannelPoints", "Enable", true, "Enable all Channel Point features.");
			ChannelPointsAllyBeetle = plugin.Config.Bind<string>("ChannelPoints", "AllyBeetle", "", "(Case Sensitive!) Channel Points Title to spawn Ally Elite Beetle. Leave empty to disable.");
			ChannelPointsAllyLemurian = plugin.Config.Bind<string>("ChannelPoints", "AllyLemurian", "", "(Case Sensitive!) Channel Points Title to spawn Ally Elite Lemurian. Leave empty to disable.");
			ChannelPointsAllyElderLemurian = plugin.Config.Bind<string>("ChannelPoints", "AllyElderLemurian", "", "(Case Sensitive!) Channel Points Title to spawn Ally Elite Elder Lemurian. Leave empty to disable.");
			ChannelPointsRustedKey = plugin.Config.Bind<string>("ChannelPoints", "RustedKey", "", "(Case Sensitive!) Channel Points Title to give everyone a Rusted Key. Leave empty to disable.");
			ChannelPointsBitStorm = plugin.Config.Bind<string>("ChannelPoints", "BitStorm", "", "(Case Sensitive!) Channel Points Title for the bit storm bit event. Leave empty to disable.");
			ChannelPointsBounty = plugin.Config.Bind<string>("ChannelPoints", "Bounty", "", "(Case Sensitive!) Channel Points Title for the doppleganger bit event. Leave empty to disable.");
			ChannelPointsShrineOfOrder = plugin.Config.Bind<string>("ChannelPoints", "ShrineOfOrder", "", "(Case Sensitive!) Channel Points Title for the Shrine of Order bit event. Leave empty to disable.");
			ChannelPointsShrineOfTheMountain = plugin.Config.Bind<string>("ChannelPoints", "ShrineOfTheMountain", "", "(Case Sensitive!) Channel Points Title for the Shrine of the Mountain bit event. Leave empty to disable.");
			ChannelPointsTitan = plugin.Config.Bind<string>("ChannelPoints", "Titan", "", "(Case Sensitive!) Channel Points Title for the Aurelionite bit event. Leave empty to disable.");
			ChannelPointsLunarWisp = plugin.Config.Bind<string>("ChannelPoints", "LunarWisp", "", "(Case Sensitive!) Channel Points Title for the Lunar Chimera (Wisp) bit event. Leave empty to disable.");
			ChannelPointsMithrix = plugin.Config.Bind<string>("ChannelPoints", "Mithrix", "", "(Case Sensitive!) Channel Points Title for the Mithrix bit event. Leave empty to disable.");
			ChannelPointsElderLemurian = plugin.Config.Bind<string>("ChannelPoints", "ElderLemurian", "", "(Case Sensitive!) Channel Points Title for the Elder Lemurian bit event. Leave empty to disable.");
			SimpleUI = plugin.Config.Bind<bool>("UI", "SimpleUI", false, "Simplify the UI. Set to true if you are playing Multiplayer.");
			EnableChoosingLunarItems = plugin.Config.Bind<bool>("Behaviour", "EnableChoosingLunarItems", true, "Twitch Chat chooses items when opening lunar chests (pods)");
			ForceUniqueRolls = plugin.Config.Bind<bool>("Behaviour", "ForceUniqueRolls", false, "Ensure, when rolling for items, that they are always different. This doesn't affect multi-shops.");
			if (RiskOfOptions.Enabled)
			{
				RiskOfOptions.ApplyRiskOfOptions(this, reloadChannelPoints);
			}
		}

		private static void EnsureConfigsRemoved(ConfigFile config, List<ConfigDefinition> configDefinitions)
		{
			foreach (ConfigDefinition configDefinition in configDefinitions)
			{
				config.Bind<string>(configDefinition, "", (ConfigDescription)null);
				config.Remove(configDefinition);
			}
			config.Save();
		}
	}
	internal class EventDirector : MonoBehaviour
	{
		private BlockingCollection<Func<EventDirector, IEnumerator>> eventQueue;

		private bool previousState;

		public event EventHandler<bool> OnProcessingEventsChanged;

		public void Awake()
		{
			eventQueue = new BlockingCollection<Func<EventDirector, IEnumerator>>();
			previousState = false;
		}

		public void OnDestroy()
		{
		}

		public void Update()
		{
			bool flag = ShouldProcessEvents();
			if (flag != previousState)
			{
				previousState = flag;
				try
				{
					this.OnProcessingEventsChanged?.Invoke(this, flag);
				}
				catch (Exception data)
				{
					Log.Exception(data);
				}
			}
			if (!flag || !eventQueue.TryTake(out var item))
			{
				return;
			}
			try
			{
				((MonoBehaviour)this).StartCoroutine(Wrap(item(this)));
			}
			catch (Exception data2)
			{
				Log.Exception(data2);
			}
		}

		public void AddEvent(Func<EventDirector, IEnumerator> eventToQueue)
		{
			eventQueue.Add(eventToQueue);
		}

		public void ClearEvents()
		{
			Func<EventDirector, IEnumerator> item;
			while (eventQueue.TryTake(out item))
			{
			}
		}

		private IEnumerator Wrap(IEnumerator coroutine)
		{
			while (true)
			{
				if (!ShouldProcessEvents())
				{
					yield return null;
					continue;
				}
				if (!coroutine.MoveNext())
				{
					break;
				}
				yield return coroutine.Current;
			}
		}

		private bool ShouldProcessEvents()
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Behaviour)this).enabled)
			{
				return false;
			}
			if (!NetworkServer.active)
			{
				return false;
			}
			if (!Object.op_Implicit((Object)(object)Run.instance) || Run.instance.isGameOverServer)
			{
				return false;
			}
			if (!Object.op_Implicit((Object)(object)Stage.instance) || Stage.instance.completed)
			{
				return false;
			}
			if (Object.op_Implicit((Object)(object)GameOverController.instance))
			{
				return false;
			}
			FixedTimeStamp entryTime = Stage.instance.entryTime;
			if (((FixedTimeStamp)(ref entryTime)).timeSince < 6f)
			{
				return false;
			}
			if (SceneExitController.isRunning)
			{
				return false;
			}
			if (Object.op_Implicit((Object)(object)TeleporterInteraction.instance) && TeleporterInteraction.instance.isInFinalSequence)
			{
				return false;
			}
			return true;
		}
	}
	[RequireComponent(typeof(MonsterSpawner))]
	internal class EventFactory : MonoBehaviour
	{
		private MonsterSpawner spawner;

		public void Awake()
		{
			Reset();
		}

		public void Reset()
		{
			if ((Object)(object)spawner != (Object)null)
			{
				Object.Destroy((Object)(object)spawner);
			}
			spawner = ((Component)this).gameObject.AddComponent<MonsterSpawner>();
		}

		public Func<EventDirector, IEnumerator> BroadcastChat(ChatMessageBase message)
		{
			return (EventDirector director) => BroadcastChatInternal(message);
		}

		private IEnumerator BroadcastChatInternal(ChatMessageBase message)
		{
			Chat.SendBroadcastChat(message);
			yield break;
		}

		public Func<EventDirector, IEnumerator> SpawnItem(PickupIndex pickupIndex)
		{
			//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)
			return (EventDirector director) => SpawnItemInternal(pickupIndex);
		}

		private IEnumerator SpawnItemInternal(PickupIndex pickupIndex)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if ((int)PickupCatalog.GetPickupDef(pickupIndex).equipmentIndex != -1)
			{
				if (RunArtifactManager.instance.IsArtifactEnabled(Artifacts.Command))
				{
					ItemManager.GiveToAllPlayers(pickupIndex);
				}
				else
				{
					ItemManager.DropToAllPlayers(pickupIndex, Vector3.up * 10f);
				}
			}
			else
			{
				ItemManager.GiveToAllPlayers(pickupIndex);
			}
			yield break;
		}

		public Func<EventDirector, IEnumerator> CreateBounty()
		{
			return (EventDirector director) => CreateBountyInternal();
		}

		private IEnumerator CreateBountyInternal()
		{
			try
			{
				DoppelgangerInvasionManager.PerformInvasion(new Xoroshiro128Plus((ulong)Random.Range(0f, 10000f)));
				string baseToken = "<color=#" + ColorUtility.ToHtmlStringRGB(Color.red) + "><size=120%>HOLD ON TO YER BOOTY!!</size></color>";
				Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
				{
					baseToken = baseToken
				});
			}
			catch (Exception data)
			{
				Log.Exception(data);
			}
			yield break;
		}

		public Func<EventDirector, IEnumerator> CreateBitStorm()
		{
			return (EventDirector director) => CreateBitStormInternal();
		}

		private IEnumerator CreateBitStormInternal()
		{
			try
			{
				foreach (PlayerCharacterMasterController instance in PlayerCharacterMasterController.instances)
				{
					if (!instance.master.IsDeadAndOutOfLivesServer())
					{
						CharacterBody body = instance.master.GetBody();
						MeteorStormController component = Object.Instantiate<GameObject>(LegacyResourcesAPI.Load<GameObject>("Prefabs/NetworkedObjects/MeteorStorm"), body.corePosition, Quaternion.identity).GetComponent<MeteorStormController>();
						component.owner = ((Component)this).gameObject;
						component.ownerDamage = body.damage * 2f;
						component.isCrit = Util.CheckRoll(body.crit, body.master);
						component.waveCount *= 3;
						NetworkServer.Spawn(((Component)component).gameObject);
					}
				}
				string baseToken = "<color=#9147ff><size=150%>HERE COMES THE BITS!!</size></color>";
				Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
				{
					baseToken = baseToken
				});
			}
			catch (Exception data)
			{
				Log.Exception(data);
			}
			yield break;
		}

		public Func<EventDirector, IEnumerator> TriggerShrineOfOrder()
		{
			return (EventDirector director) => TriggerShrineOfOrderInternal();
		}

		private IEnumerator TriggerShrineOfOrderInternal()
		{
			try
			{
				foreach (PlayerCharacterMasterController instance in PlayerCharacterMasterController.instances)
				{
					if (instance.master.IsDeadAndOutOfLivesServer())
					{
						continue;
					}
					Inventory inventory = instance.master.inventory;
					if (Object.op_Implicit((Object)(object)inventory))
					{
						inventory.ShrineRestackInventory(RoR2Application.rng);
						CharacterBody body = instance.master.GetBody();
						if (Object.op_Implicit((Object)(object)body))
						{
							Chat.SendBroadcastChat((ChatMessageBase)new SubjectFormatChatMessage
							{
								subjectAsCharacterBody = body,
								baseToken = "SHRINE_RESTACK_USE_MESSAGE"
							});
							EffectManager.SpawnEffect(LegacyResourcesAPI.Load<GameObject>("Prefabs/Effects/ShrineUseEffect"), new EffectData
							{
								origin = body.corePosition,
								rotation = Quaternion.identity,
								scale = body.bestFitRadius * 2f,
								color = Color32.op_Implicit(new Color(1f, 0.23f, 0.6337214f))
							}, true);
						}
					}
				}
				Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
				{
					baseToken = "<color=#9147ff>Twitch Chat decides you should have 'better' items.</color>"
				});
			}
			catch (Exception data)
			{
				Log.Exception(data);
			}
			yield break;
		}

		public Func<EventDirector, IEnumerator> TriggerShrineOfTheMountain(int count = 1)
		{
			return (EventDirector director) => TriggerShrineOfTheMountainInternal(count);
		}

		private IEnumerator TriggerShrineOfTheMountainInternal(int count)
		{
			if (SceneCatalog.GetSceneDefForCurrentScene().isFinalStage)
			{
				foreach (TeamComponent teamMember in TeamComponent.GetTeamMembers((TeamIndex)2))
				{
					CharacterBody body = teamMember.body;
					if (Object.op_Implicit((Object)(object)body) && body.inventory.GetItemCount(Items.ExtraLife) == 0 && body.inventory.GetItemCount(Items.ExtraLifeConsumed) == 0)
					{
						body.inventory.GiveItem(Items.ExtraLife, 1);
						body.inventory.GiveRandomItems(Run.instance.livingPlayerCount, false, true);
					}
				}
				Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
				{
					baseToken = "<color=#9147ff>Twitch Chat feels the last stage should be harder.</color>"
				});
				yield break;
			}
			if (Object.op_Implicit((Object)(object)TeleporterInteraction.instance) && !TeleporterInteraction.instance.isIdle)
			{
				Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
				{
					baseToken = "<color=#9147ff>Twitch Chat feels the boss should be harder on the next stage.</color>"
				});
			}
			yield return (object)new WaitUntil((Func<bool>)(() => Object.op_Implicit((Object)(object)TeleporterInteraction.instance) && TeleporterInteraction.instance.isIdle));
			try
			{
				if (Object.op_Implicit((Object)(object)TeleporterInteraction.instance))
				{
					for (int i = 0; i < count; i++)
					{
						TeleporterInteraction.instance.AddShrineStack();
					}
					foreach (PlayerCharacterMasterController instance in PlayerCharacterMasterController.instances)
					{
						CharacterBody body2 = instance.master.GetBody();
						if (Object.op_Implicit((Object)(object)body2))
						{
							Chat.SendBroadcastChat((ChatMessageBase)new SubjectFormatChatMessage
							{
								subjectAsCharacterBody = body2,
								baseToken = "SHRINE_BOSS_USE_MESSAGE"
							});
							EffectManager.SpawnEffect(LegacyResourcesAPI.Load<GameObject>("Prefabs/Effects/ShrineUseEffect"), new EffectData
							{
								origin = body2.corePosition,
								rotation = Quaternion.identity,
								scale = body2.bestFitRadius * 2f,
								color = Color32.op_Implicit(new Color(0.7372549f, 77f / 85f, 0.94509804f))
							}, true);
						}
					}
				}
				Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
				{
					baseToken = "<color=#9147ff>Twitch Chat feels the boss should be harder on this stage.</color>"
				});
			}
			catch (Exception data)
			{
				Log.Exception(data);
			}
		}

		public Func<EventDirector, IEnumerator> CreateMonster(string monster, EliteIndex eliteIndex)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return CreateMonster(monster, 1, eliteIndex);
		}

		public Func<EventDirector, IEnumerator> CreateMonster(string monster, int num = 1, EliteIndex eliteIndex = -1)
		{
			//IL_001b: 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)
			return (EventDirector director) => CreateMonsterInternal(director, monster, num, eliteIndex);
		}

		private IEnumerator CreateMonsterInternal(EventDirector director, string monster, int num, EliteIndex eliteIndex)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			CombatSquad squad = spawner.SpawnMonsters(monster, eliteIndex, FindFirstAliveBody(), num, director);
			string text = null;
			foreach (CharacterMaster readOnlyMembers in squad.readOnlyMembersList)
			{
				if (text == null)
				{
					text = Util.GetBestBodyName(readOnlyMembers.GetBodyObject());
				}
				((Component)readOnlyMembers).gameObject.AddComponent<SpawnedMonster>().teleportWhenOOB = true;
				CharacterBody body = readOnlyMembers.GetBody();
				if (Object.op_Implicit((Object)(object)body))
				{
					body.bodyFlags = (BodyFlags)(body.bodyFlags | 1);
				}
			}
			if (text == null)
			{
				text = "monster";
			}
			string text2 = ((squad.readOnlyMembersList.Count == 1) ? (text + " jumps") : $"{squad.readOnlyMembersList.Count} {text}'s jump");
			string baseToken = "<color=#9147ff>" + text2 + " out of the void...</color>";
			Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
			{
				baseToken = baseToken
			});
			if (!MonsterSpawner.Monsters.Brother.Equals(monster) && !MonsterSpawner.Monsters.BrotherGlass.Equals(monster))
			{
				yield break;
			}
			squad.onMemberLost += delegate
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Expected O, but got Unknown
				if (squad.memberCount == 0)
				{
					SimpleChatMessage val = new SimpleChatMessage();
					val.baseToken = "BROTHER_DIALOGUE_FORMAT";
					val.paramTokens = new string[1] { "I'll be back" };
					Chat.SendBroadcastChat((ChatMessageBase)(object)val);
				}
			};
		}

		public Func<EventDirector, IEnumerator> CreateAlly(string name, string monster, EliteIndex eliteIndex = -1)
		{
			//IL_001b: 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)
			return (EventDirector director) => CreateAllyInternal(name, monster, eliteIndex);
		}

		private IEnumerator CreateAllyInternal(string name, string monster, EliteIndex eliteIndex)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			string text = Util.EscapeRichTextForTextMeshPro(name);
			CharacterBody val = FindFirstAliveBody();
			CombatSquad squad = spawner.SpawnAllies(monster, eliteIndex, val);
			string baseToken = "<color=#" + ColorUtility.ToHtmlStringRGB(Color.green) + ">" + text + "</color><color=#9147ff> enters the game to help you...</color>";
			Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
			{
				baseToken = baseToken
			});
			squad.onMemberLost += delegate(CharacterMaster member)
			{
				//IL_002f: 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_0040: Unknown result type (might be due to invalid IL or missing references)
				//IL_0056: Expected O, but got Unknown
				if (squad.memberCount == 0)
				{
					string[] array = (string[])typeof(GlobalEventManager).GetField("standardDeathQuoteTokens", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
					Chat.SendBroadcastChat((ChatMessageBase)new PlayerDeathChatMessage
					{
						subjectAsCharacterBody = member.GetBody(),
						baseToken = array[Random.Range(0, array.Length)]
					});
				}
			};
			foreach (CharacterMaster readOnlyMembers in squad.readOnlyMembersList)
			{
				((Component)readOnlyMembers).gameObject.AddComponent<SetDontDestroyOnLoad>();
				((Component)readOnlyMembers).gameObject.AddComponent<ForceNameChange>().NameToken = text;
				((Component)readOnlyMembers).gameObject.AddComponent<SpawnedMonster>().teleportWhenOOB = false;
				readOnlyMembers.inventory.GiveItem(Items.HealWhileSafe, Run.instance.livingPlayerCount);
				readOnlyMembers.inventory.GiveItem(Items.Infusion, Run.instance.livingPlayerCount);
				if (!((Object)(object)val == (Object)null))
				{
					CharacterMaster master = val.master;
					readOnlyMembers.inventory.GiveItem(Items.Hoof, master.inventory.GetItemCount(Items.Hoof));
					readOnlyMembers.inventory.GiveItem(Items.SprintBonus, master.inventory.GetItemCount(Items.SprintBonus));
					if (Object.op_Implicit((Object)(object)master) && Object.op_Implicit((Object)(object)master.minionOwnership.ownerMaster))
					{
						_ = master.minionOwnership.ownerMaster;
					}
					readOnlyMembers.minionOwnership.SetOwner(val.master);
					AIOwnership component = ((Component)readOnlyMembers).gameObject.GetComponent<AIOwnership>();
					if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)val.master))
					{
						component.ownerMaster = val.master;
					}
					BaseAI component2 = ((Component)readOnlyMembers).gameObject.GetComponent<BaseAI>();
					if (Object.op_Implicit((Object)(object)component2))
					{
						component2.leader.gameObject = ((Component)val).gameObject;
						component2.fullVision = true;
						ApplyFollowingAI(component2);
					}
				}
			}
			yield break;
		}

		private void ApplyFollowingAI(BaseAI baseAI)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			AISkillDriver obj = ((Component)baseAI).gameObject.AddComponent<AISkillDriver>();
			obj.customName = "ReturnToOwnerLeash";
			obj.skillSlot = (SkillSlot)(-1);
			obj.requiredSkill = null;
			obj.requireSkillReady = false;
			obj.requireEquipmentReady = false;
			obj.minUserHealthFraction = float.NegativeInfinity;
			obj.maxUserHealthFraction = float.PositiveInfinity;
			obj.minTargetHealthFraction = float.NegativeInfinity;
			obj.maxTargetHealthFraction = float.PositiveInfinity;
			obj.minDistance = 50f;
			obj.maxDistance = float.PositiveInfinity;
			obj.selectionRequiresTargetLoS = false;
			obj.selectionRequiresOnGround = false;
			obj.moveTargetType = (TargetType)2;
			obj.activationRequiresTargetLoS = false;
			obj.activationRequiresAimConfirmation = false;
			obj.movementType = (MovementType)1;
			obj.moveInputScale = 1f;
			obj.aimType = (AimType)3;
			obj.ignoreNodeGraph = false;
			obj.shouldSprint = true;
			obj.shouldFireEquipment = false;
			obj.buttonPressType = (ButtonPressType)0;
			obj.driverUpdateTimerOverride = 3f;
			obj.resetCurrentEnemyOnNextDriverSelection = true;
			obj.noRepeat = false;
			obj.nextHighPriorityOverride = null;
			AISkillDriver obj2 = ((Component)baseAI).gameObject.AddComponent<AISkillDriver>();
			obj2.customName = "ReturnToLeaderDefault";
			obj2.skillSlot = (SkillSlot)(-1);
			obj2.requiredSkill = null;
			obj2.requireSkillReady = false;
			obj2.requireEquipmentReady = false;
			obj2.minUserHealthFraction = float.NegativeInfinity;
			obj2.maxUserHealthFraction = float.PositiveInfinity;
			obj2.minTargetHealthFraction = float.NegativeInfinity;
			obj2.maxTargetHealthFraction = float.PositiveInfinity;
			obj2.minDistance = 15f;
			obj2.maxDistance = float.PositiveInfinity;
			obj2.selectionRequiresTargetLoS = false;
			obj2.selectionRequiresOnGround = false;
			obj2.moveTargetType = (TargetType)2;
			obj2.activationRequiresTargetLoS = false;
			obj2.activationRequiresAimConfirmation = false;
			obj2.movementType = (MovementType)1;
			obj2.moveInputScale = 1f;
			obj2.aimType = (AimType)1;
			obj2.ignoreNodeGraph = false;
			obj2.shouldSprint = true;
			obj2.shouldFireEquipment = false;
			obj2.buttonPressType = (ButtonPressType)0;
			obj2.driverUpdateTimerOverride = -1f;
			obj2.resetCurrentEnemyOnNextDriverSelection = false;
			obj2.noRepeat = false;
			obj2.nextHighPriorityOverride = null;
			AISkillDriver obj3 = ((Component)baseAI).gameObject.AddComponent<AISkillDriver>();
			obj3.customName = "WaitNearLeaderDefault";
			obj3.skillSlot = (SkillSlot)(-1);
			obj3.requiredSkill = null;
			obj3.requireSkillReady = false;
			obj3.requireEquipmentReady = false;
			obj3.minUserHealthFraction = float.NegativeInfinity;
			obj3.maxUserHealthFraction = float.PositiveInfinity;
			obj3.minTargetHealthFraction = float.NegativeInfinity;
			obj3.maxTargetHealthFraction = float.PositiveInfinity;
			obj3.minDistance = 0f;
			obj3.maxDistance = float.PositiveInfinity;
			obj3.selectionRequiresTargetLoS = false;
			obj3.selectionRequiresOnGround = false;
			obj3.moveTargetType = (TargetType)2;
			obj3.activationRequiresTargetLoS = false;
			obj3.activationRequiresAimConfirmation = false;
			obj3.movementType = (MovementType)0;
			obj3.moveInputScale = 1f;
			obj3.aimType = (AimType)3;
			obj3.ignoreNodeGraph = false;
			obj3.shouldSprint = false;
			obj3.shouldFireEquipment = false;
			obj3.buttonPressType = (ButtonPressType)0;
			obj3.driverUpdateTimerOverride = -1f;
			obj3.resetCurrentEnemyOnNextDriverSelection = false;
			obj3.noRepeat = false;
			obj3.nextHighPriorityOverride = null;
			PropertyInfo property = typeof(BaseAI).GetProperty("skillDrivers", BindingFlags.Instance | BindingFlags.Public);
			if (property != null)
			{
				property.SetValue(baseAI, ((Component)baseAI).gameObject.GetComponents<AISkillDriver>(), null);
			}
		}

		private CharacterBody FindFirstAliveBody()
		{
			foreach (PlayerCharacterMasterController instance in PlayerCharacterMasterController.instances)
			{
				CharacterBody body = instance.master.GetBody();
				if ((Object)(object)body != (Object)null)
				{
					return body;
				}
			}
			return null;
		}
	}
	internal class ForceNameChange : MonoBehaviour
	{
		private CharacterMaster body;

		public string NameToken { get; set; }

		public void Awake()
		{
			body = ((Component)this).GetComponent<CharacterMaster>();
		}

		public void Update()
		{
			if (Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)body.GetBody()) && !body.GetBody().baseNameToken.Equals(NameToken))
			{
				body.GetBody().baseNameToken = NameToken;
			}
		}
	}
	internal class ItemManager
	{
		public static void GiveToAllPlayers(PickupIndex pickupIndex)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkServer.active)
			{
				Log.Warning("[Server] function 'System.Void ItemManager::GiveToAllPlayers()' called on client");
				return;
			}
			foreach (PlayerCharacterMasterController instance in PlayerCharacterMasterController.instances)
			{
				GiveToPlayer(instance.master, pickupIndex);
			}
		}

		public static void GiveToPlayer(CharacterMaster characterMaster, PickupIndex pickupIndex)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_003c: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkServer.active)
			{
				Log.Warning("[Server] function 'System.Void ItemManager::GiveToPlayer()' called on client");
				return;
			}
			PickupDef pickupDef = PickupCatalog.GetPickupDef(pickupIndex);
			if ((int)pickupDef.equipmentIndex != -1)
			{
				characterMaster.inventory.SetEquipmentIndex(pickupDef.equipmentIndex);
			}
			else
			{
				characterMaster.inventory.GiveItem(pickupDef.itemIndex, 1);
			}
			GenericPickupController.SendPickupMessage(characterMaster, pickupIndex);
		}

		public static void DropToAllPlayers(PickupIndex pickupIndex, Vector3 velocity)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkServer.active)
			{
				Log.Warning("[Server] function 'System.Void ItemManager::DropToAllPlayers()' called on client");
				return;
			}
			foreach (PlayerCharacterMasterController instance in PlayerCharacterMasterController.instances)
			{
				DropToPlayer(instance.master, pickupIndex, velocity);
			}
		}

		public static void DropToPlayer(CharacterMaster characterMaster, PickupIndex pickupIndex, Vector3 velocity)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkServer.active)
			{
				Log.Warning("[Server] function 'System.Void ItemManager::DropToPlayer()' called on client");
				return;
			}
			CharacterBody body = characterMaster.GetBody();
			if ((Object)(object)body != (Object)null)
			{
				PickupDropletController.CreatePickupDroplet(pickupIndex, body.corePosition + Vector3.up * 1.5f, velocity);
			}
		}
	}
	internal class MonsterSpawner : MonoBehaviour
	{
		private class SpawnFinalizer
		{
			public CombatSquad CombatSquad { get; set; }

			public EliteIndex EliteIndex { get; set; }

			public bool IsBoss { get; set; }

			public void OnCardSpawned(SpawnResult spawnResult)
			{
				//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_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: Unknown result type (might be due to invalid IL or missing references)
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0054: Invalid comparison between Unknown and I4
				//IL_005c: Unknown result type (might be due to invalid IL or missing references)
				if (spawnResult.success)
				{
					CharacterMaster component = spawnResult.spawnedInstance.GetComponent<CharacterMaster>();
					if (Object.op_Implicit((Object)(object)CombatSquad))
					{
						CombatSquad.AddMember(component);
					}
					EliteDef eliteDef = EliteCatalog.GetEliteDef(EliteIndex);
					EquipmentIndex val = (EquipmentIndex)((!((Object)(object)eliteDef != (Object)null)) ? (-1) : ((int)eliteDef.eliteEquipmentDef.equipmentIndex));
					if ((int)val != -1)
					{
						component.inventory.SetEquipmentIndex(val);
					}
					float num = 1f;
					float num2 = 1f;
					num += Run.instance.difficultyCoefficient / 1.5f;
					num2 += Run.instance.difficultyCoefficient / 15f;
					int num3 = Mathf.Max(1, Run.instance.livingPlayerCount);
					num *= Mathf.Pow((float)num3, 0.75f);
					component.inventory.GiveItem(Items.BoostHp, Mathf.RoundToInt((float)Mathf.RoundToInt(num - 1f) * 10f));
					component.inventory.GiveItem(Items.BoostDamage, Mathf.RoundToInt((float)Mathf.RoundToInt(num2 - 1f) * 10f));
					component.isBoss = IsBoss;
				}
			}
		}

		public class Monsters
		{
			public static readonly string ArchWisp = "SpawnCards/CharacterSpawnCards/cscArchWisp";

			public static readonly string BackupDrone = "SpawnCards/CharacterSpawnCards/cscBackupDrone";

			public static readonly string Beetle = "SpawnCards/CharacterSpawnCards/cscBeetle";

			public static readonly string BeetleCrystal = "SpawnCards/CharacterSpawnCards/cscBeetleCrystal";

			public static readonly string BeetleGuard = "SpawnCards/CharacterSpawnCards/cscBeetleGuard";

			public static readonly string BeetleGuardAlly = "SpawnCards/CharacterSpawnCards/cscBeetleGuardAlly";

			public static readonly string BeetleGuardCrystal = "SpawnCards/CharacterSpawnCards/cscBeetleGuardCrystal";

			public static readonly string BeetleQueen = "SpawnCards/CharacterSpawnCards/cscBeetleQueen";

			public static readonly string Bell = "SpawnCards/CharacterSpawnCards/cscBell";

			public static readonly string Bison = "SpawnCards/CharacterSpawnCards/cscBison";

			public static readonly string Brother = "SpawnCards/CharacterSpawnCards/cscBrother";

			public static readonly string BrotherGlass = "SpawnCards/CharacterSpawnCards/cscBrotherGlass";

			public static readonly string BrotherHurt = "SpawnCards/CharacterSpawnCards/cscBrotherHurt";

			public static readonly string ClayBoss = "SpawnCards/CharacterSpawnCards/cscClayBoss";

			public static readonly string ClayBruiser = "SpawnCards/CharacterSpawnCards/cscClayBruiser";

			public static readonly string ElectricWorm = "SpawnCards/CharacterSpawnCards/cscElectricWorm";

			public static readonly string Golem = "SpawnCards/CharacterSpawnCards/cscGolem";

			public static readonly string Gravekeeper = "SpawnCards/CharacterSpawnCards/cscGravekeeper";

			public static readonly string GreaterWisp = "SpawnCards/CharacterSpawnCards/cscGreaterWisp";

			public static readonly string HermitCrab = "SpawnCards/CharacterSpawnCards/cscHermitCrab";

			public static readonly string Imp = "SpawnCards/CharacterSpawnCards/cscImp";

			public static readonly string ImpBoss = "SpawnCards/CharacterSpawnCards/cscImpBoss";

			public static readonly string Jellyfish = "SpawnCards/CharacterSpawnCards/cscJellyfish";

			public static readonly string Lemurian = "SpawnCards/CharacterSpawnCards/cscLemurian";

			public static readonly string LemurianBruiser = "SpawnCards/CharacterSpawnCards/cscLemurianBruiser";

			public static readonly string LesserWisp = "SpawnCards/CharacterSpawnCards/cscLesserWisp";

			public static readonly string LunarGolem = "SpawnCards/CharacterSpawnCards/cscLunarGolem";

			public static readonly string LunarWisp = "SpawnCards/CharacterSpawnCards/cscLunarWisp";

			public static readonly string MagmaWorm = "SpawnCards/CharacterSpawnCards/cscMagmaWorm";

			public static readonly string MiniMushroom = "SpawnCards/CharacterSpawnCards/cscMiniMushroom";

			public static readonly string Nullifier = "SpawnCards/CharacterSpawnCards/cscNullifier";

			public static readonly string Parent = "SpawnCards/CharacterSpawnCards/cscParent";

			public static readonly string ParentPod = "SpawnCards/CharacterSpawnCards/cscParentPod";

			public static readonly string RoboBallBoss = "SpawnCards/CharacterSpawnCards/cscRoboBallBoss";

			public static readonly string RoboBallMini = "SpawnCards/CharacterSpawnCards/cscRoboBallMini";

			public static readonly string Scav = "SpawnCards/CharacterSpawnCards/cscScav";

			public static readonly string ScavLunar = "SpawnCards/CharacterSpawnCards/cscScavLunar";

			public static readonly string SquidTurret = "SpawnCards/CharacterSpawnCards/cscSquidTurret";

			public static readonly string SuperRoboBallBoss = "SpawnCards/CharacterSpawnCards/cscSuperRoboBallBoss";

			public static readonly string TitanGold = "SpawnCards/CharacterSpawnCards/cscTitanGold";

			public static readonly string TitanGoldAlly = "SpawnCards/CharacterSpawnCards/cscTitanGoldAlly";

			public static readonly string Vagrant = "SpawnCards/CharacterSpawnCards/cscVagrant";

			public static readonly string Vulture = "SpawnCards/CharacterSpawnCards/cscVulture";

			public static readonly string Grandparent = "SpawnCards/CharacterSpawnCards/cscGrandparent";

			public static readonly string TitanBlackBeach = "SpawnCards/CharacterSpawnCards/cscTitanBlackBeach";

			public static readonly string TitanDampCave = "SpawnCards/CharacterSpawnCards/cscTitanDampCave";

			public static readonly string TitanGolemPlains = "SpawnCards/CharacterSpawnCards/cscTitanGolemPlains";

			public static readonly string TitanGooLake = "SpawnCards/CharacterSpawnCards/cscTitanGooLake";

			private Monsters()
			{
			}
		}

		public CombatSquad SpawnAllies(string spawnCard, EliteIndex eliteIndex = -1, CharacterBody targetBody = null, int numMonsters = 1)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return SpawnMonstersInternal(spawnCard, eliteIndex, targetBody, numMonsters, null, (TeamIndex)1);
		}

		public CombatSquad SpawnMonsters(string spawnCard, EliteIndex eliteIndex = -1, CharacterBody targetBody = null, int numMonsters = 1, EventDirector director = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return SpawnMonstersInternal(spawnCard, eliteIndex, targetBody, numMonsters, director, (TeamIndex)2);
		}

		private CombatSquad SpawnMonstersInternal(string spawnCard, EliteIndex eliteIndex, CharacterBody targetBody, int numMonsters, EventDirector director, TeamIndex teamIndex)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Invalid comparison between Unknown and I4
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Invalid comparison between Unknown and I4
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Expected O, but got Unknown
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Expected O, but got Unknown
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Invalid comparison between Unknown and I4
			CombatSquad group = ((Component)this).gameObject.AddComponent<CombatSquad>();
			group.onMemberLost += delegate
			{
				if (group.memberCount == 0)
				{
					Object.Destroy((Object)(object)group);
				}
			};
			DirectorPlacementRule val = ((!Object.op_Implicit((Object)(object)targetBody)) ? new DirectorPlacementRule
			{
				placementMode = (PlacementMode)4
			} : new DirectorPlacementRule
			{
				placementMode = (PlacementMode)1,
				minDistance = 8f,
				maxDistance = 20f,
				spawnOnTarget = targetBody.transform
			});
			SpawnCard val2 = LegacyResourcesAPI.Load<SpawnCard>(spawnCard);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				Object.Destroy((Object)(object)group);
				return null;
			}
			SpawnFinalizer @object = new SpawnFinalizer
			{
				CombatSquad = group,
				EliteIndex = eliteIndex,
				IsBoss = ((int)teamIndex != 1)
			};
			DirectorSpawnRequest val3 = new DirectorSpawnRequest(val2, val, RoR2Application.rng)
			{
				ignoreTeamMemberLimit = true,
				teamIndexOverride = teamIndex,
				onSpawnedServer = @object.OnCardSpawned
			};
			if ((int)teamIndex == 1)
			{
				val3.summonerBodyObject = ((Component)targetBody).gameObject;
			}
			bool flag = false;
			for (int i = 0; i < numMonsters; i++)
			{
				GameObject val4 = DirectorCore.instance.TrySpawnObject(val3);
				if (!Object.op_Implicit((Object)(object)val4))
				{
					Log.Warning("Could not spawn monster near target body, spawning randomly on map");
					DirectorSpawnRequest val5 = new DirectorSpawnRequest(val2, new DirectorPlacementRule
					{
						placementMode = (PlacementMode)4
					}, RoR2Application.rng)
					{
						ignoreTeamMemberLimit = true,
						teamIndexOverride = teamIndex,
						onSpawnedServer = @object.OnCardSpawned
					};
					if ((int)teamIndex == 1)
					{
						val5.summonerBodyObject = ((Component)targetBody).gameObject;
					}
					val4 = DirectorCore.instance.TrySpawnObject(val5);
				}
				if (Object.op_Implicit((Object)(object)val4))
				{
					flag = true;
				}
			}
			if (!flag)
			{
				Log.Error("Couldn't spawn any monster!");
				Object.Destroy((Object)(object)group);
				return null;
			}
			return group;
		}
	}
	internal class SpawnedMonster : MonoBehaviour
	{
		public int suicideProtection;

		public bool teleportWhenOOB = true;
	}
	internal interface IItemRoller<T>
	{
		void RollForItem(List<T> indices, Action<T> callback);
	}
	internal class ItemRollerManager : IItemRoller<PickupIndex>
	{
		private readonly ReaderWriterLockSlim cacheLock;

		private readonly IVoteStrategy<PickupIndex> voteStrategy;

		private readonly BlockingCollection<Vote> voteQueue;

		private Vote currentVote;

		private Vote previousVote;

		private int id;

		public event EventHandler<IDictionary<int, PickupIndex>> OnVoteStart;

		public ItemRollerManager(IVoteStrategy<PickupIndex> voteStrategy)
		{
			cacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
			voteQueue = new BlockingCollection<Vote>();
			this.voteStrategy = voteStrategy;
			id = 1;
		}

		public int QueueSize()
		{
			cacheLock.EnterReadLock();
			try
			{
				return voteQueue.Count;
			}
			finally
			{
				cacheLock.ExitReadLock();
			}
		}

		public void EndVote()
		{
			OnVoteEnd();
		}

		public void ClearVotes()
		{
			cacheLock.EnterWriteLock();
			try
			{
				Vote item;
				while (voteQueue.TryTake(out item))
				{
				}
				EndVote();
				previousVote = null;
			}
			finally
			{
				cacheLock.ExitWriteLock();
			}
		}

		private void OnVoteEnd()
		{
			try
			{
				cacheLock.EnterWriteLock();
				try
				{
					if (currentVote != null)
					{
						currentVote.EndVote();
						previousVote = currentVote;
						currentVote = null;
					}
				}
				finally
				{
					cacheLock.ExitWriteLock();
				}
				TryStartVote();
			}
			catch (Exception data)
			{
				Log.Exception(data);
			}
		}

		public void RollForItem(List<PickupIndex> indices, Action<PickupIndex> callback)
		{
			Vote vote = new Vote(indices, voteStrategy, Interlocked.Increment(ref id));
			vote.OnVoteStart += this.OnVoteStart;
			vote.OnVoteEnd += delegate(object sender, PickupIndex e)
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				callback?.Invoke(e);
			};
			cacheLock.EnterWriteLock();
			try
			{
				if (isSameVote(vote, currentVote))
				{
					Log.Warning(string.Format("WARNING: Not adding roll for {0} with id {1} ", string.Join(", ", vote.GetCandidates().Values), vote.GetId()) + "because the previous vote was exactly that. There might be another mod causing issues making rolling busted.");
					return;
				}
				Log.Info(string.Format("Adding roll for {0} with id {1}", string.Join(", ", vote.GetCandidates().Values), vote.GetId()));
				voteQueue.Add(vote);
			}
			finally
			{
				cacheLock.ExitWriteLock();
			}
			TryStartVote();
		}

		private bool isSameVote(Vote vote, Vote lastVote)
		{
			if (vote == null || lastVote == null)
			{
				return false;
			}
			HashSet<PickupIndex> hashSet = new HashSet<PickupIndex>(vote.GetCandidates().Values);
			HashSet<PickupIndex> equals = new HashSet<PickupIndex>(lastVote.GetCandidates().Values);
			return hashSet.SetEquals(equals);
		}

		public void AddVote(string username, int index)
		{
			cacheLock.EnterReadLock();
			try
			{
				currentVote?.AddVote(username, index);
			}
			finally
			{
				cacheLock.ExitReadLock();
			}
		}

		private void TryStartVote()
		{
			cacheLock.EnterWriteLock();
			try
			{
				if (currentVote != null)
				{
					return;
				}
				while (true)
				{
					if (!voteQueue.TryTake(out currentVote))
					{
						return;
					}
					if (!isSameVote(previousVote, currentVote))
					{
						break;
					}
					Log.Warning(string.Format("WARNING: Not starting vote for {0} with id {1} ", string.Join(", ", currentVote.GetCandidates().Values), currentVote.GetId()) + "because the previous vote was exactly that. There might be another mod causing issues making rolling busted.");
				}
				currentVote.StartVote();
			}
			finally
			{
				cacheLock.ExitWriteLock();
			}
		}
	}
	internal class Vote
	{
		private readonly Dictionary<int, PickupIndex> indices;

		private readonly IVoteStrategy<PickupIndex> strategy;

		private readonly Dictionary<string, PickupIndex> votes;

		private readonly int id;

		public event EventHandler<IDictionary<int, PickupIndex>> OnVoteStart;

		public event EventHandler<PickupIndex> OnVoteEnd;

		public Vote(List<PickupIndex> indices, IVoteStrategy<PickupIndex> strategy, int id)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			this.indices = new Dictionary<int, PickupIndex>();
			int num = 1;
			foreach (PickupIndex index in indices)
			{
				this.indices[num] = index;
				num++;
			}
			this.strategy = strategy;
			votes = new Dictionary<string, PickupIndex>();
			this.id = id;
		}

		public IDictionary<int, PickupIndex> GetCandidates()
		{
			return new ReadOnlyDictionary<int, PickupIndex>(indices);
		}

		public int GetId()
		{
			return id;
		}

		public void StartVote()
		{
			this.OnVoteStart?.Invoke(this, GetCandidates());
		}

		public void AddVote(string username, int index)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (indices.TryGetValue(index, out var value))
			{
				votes[username] = value;
			}
		}

		public void EndVote()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (indices.Count == 0)
			{
				this.OnVoteEnd?.Invoke(this, PickupIndex.none);
				return;
			}
			PickupIndex[] array = (PickupIndex[])(object)new PickupIndex[indices.Values.Count];
			indices.Values.CopyTo(array, 0);
			this.OnVoteEnd?.Invoke(this, strategy.GetWinner(votes, array));
		}
	}
	public interface IVoteStrategy<T>
	{
		T GetWinner(Dictionary<string, T> votes, T[] allChoices);
	}
	public class MaxRandTieVoteStrategy<T> : IVoteStrategy<T>
	{
		public T GetWinner(Dictionary<string, T> votes, T[] allChoices)
		{
			if (votes.Count == 0)
			{
				return allChoices[Random.Range(0, allChoices.Length)];
			}
			Dictionary<T, int> dictionary = new Dictionary<T, int>();
			foreach (KeyValuePair<string, T> vote in votes)
			{
				if (dictionary.TryGetValue(vote.Value, out var value))
				{
					dictionary[vote.Value] = value + 1;
				}
				else
				{
					dictionary[vote.Value] = 1;
				}
			}
			List<T> list = new List<T>();
			int num = -1;
			foreach (KeyValuePair<T, int> item in dictionary)
			{
				if (item.Value > num)
				{
					list.Clear();
					list.Add(item.Key);
					num = item.Value;
				}
				else if (item.Value == num)
				{
					list.Add(item.Key);
				}
			}
			return list[Random.Range(0, list.Count)];
		}
	}
	public class MaxVoteStrategy<T> : IVoteStrategy<T>
	{
		public T GetWinner(Dictionary<string, T> votes, T[] allChoices)
		{
			if (votes.Count == 0)
			{
				return allChoices[0];
			}
			Dictionary<T, int> dictionary = new Dictionary<T, int>();
			foreach (KeyValuePair<string, T> vote in votes)
			{
				if (dictionary.TryGetValue(vote.Value, out var value))
				{
					dictionary[vote.Value] = value + 1;
				}
				else
				{
					dictionary[vote.Value] = 1;
				}
			}
			T result = default(T);
			int num = -1;
			foreach (KeyValuePair<T, int> item in dictionary)
			{
				if (item.Value > num)
				{
					result = item.Key;
					num = item.Value;
				}
			}
			return result;
		}
	}
	public class PercentileVoteStrategy<T> : IVoteStrategy<T>
	{
		public T GetWinner(Dictionary<string, T> votes, T[] allChoices)
		{
			if (votes.Count == 0)
			{
				return allChoices[Random.Range(0, allChoices.Length)];
			}
			Dictionary<T, int> dictionary = new Dictionary<T, int>();
			foreach (KeyValuePair<string, T> vote in votes)
			{
				int num = (dictionary.TryGetValue(vote.Value, out var value) ? value : 0);
				num = (dictionary[vote.Value] = num + 1);
			}
			int count = votes.Count;
			int num3 = Random.Range(0, count);
			T result = allChoices[Random.Range(0, allChoices.Length)];
			foreach (KeyValuePair<T, int> item in dictionary)
			{
				if (num3 <= item.Value)
				{
					result = item.Key;
					break;
				}
				num3 -= item.Value;
			}
			return result;
		}
	}
	internal static class Log
	{
		private static ManualLogSource _logSource;

		internal static void Init(ManualLogSource logSource)
		{
			_logSource = logSource;
		}

		internal static ILoggerFactory CreateLoggerFactory(Func<string?, string?, LogLevel, bool> filter)
		{
			return LoggerFactory.Create((Action<ILoggingBuilder>)delegate(ILoggingBuilder builder)
			{
				ConsoleLoggerExtensions.AddConsole(FilterLoggingBuilderExtensions.AddFilter(builder, filter));
			});
		}

		internal static void Debug(object data)
		{
			_logSource.LogDebug(data);
		}

		internal static void Error(object data)
		{
			_logSource.LogError(data);
		}

		internal static void Exception(Exception data)
		{
			_logSource.LogError((object)data);
		}

		internal static void Fatal(object data)
		{
			_logSource.LogFatal(data);
		}

		internal static void Info(object data)
		{
			_logSource.LogInfo(data);
		}

		internal static void Message(object data)
		{
			_logSource.LogMessage(data);
		}

		internal static void Warning(object data)
		{
			_logSource.LogWarning(data);
		}
	}
	internal class OnDonationArgs : EventArgs
	{
		public double Amount;

		public string Name;

		public string Comment;
	}
	internal class TiltifyManager
	{
		private TiltifyWebSocket tiltifyWebsocket;

		private string campaignId;

		public event EventHandler<OnDonationArgs> OnDonationReceived;

		public event EventHandler<EventArgs> OnConnected;

		public event EventHandler<EventArgs> OnDisconnected;

		public void Connect(string campaignId)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			Disconnect();
			if (string.IsNullOrWhiteSpace(campaignId))
			{
				throw new ArgumentException("Tiltify campaign ID must be specified!", "campaignId");
			}
			this.campaignId = campaignId;
			try
			{
				tiltifyWebsocket = new TiltifyWebSocket((ILogger<TiltifyWebSocket>)null, (WebSocketClientOptions)null);
				tiltifyWebsocket.OnLog += TiltifyWebsocket_OnLog;
				tiltifyWebsocket.OnTiltifyServiceConnected += TiltifyWebsocket_OnTiltifyServiceConnected;
				tiltifyWebsocket.OnCampaignDonation += TiltifyWebsocket_OnCampaignDonation;
				tiltifyWebsocket.Connect();
				tiltifyWebsocket.OnTiltifyServiceClosed += TiltifyWebsocket_OnTiltifyServiceClosed;
			}
			catch (Exception ex)
			{
				tiltifyWebsocket = null;
				throw ex;
			}
		}

		private void TiltifyWebsocket_OnLog(object sender, OnLogArgs e)
		{
			Log.Info("[Tiltify Websocket] " + e.Data);
		}

		private void TiltifyWebsocket_OnCampaignDonation(object sender, OnCampaignDonationArgs e)
		{
			this.OnDonationReceived(this, new OnDonationArgs
			{
				Amount = e.Donation.Amount,
				Name = e.Donation.Name,
				Comment = e.Donation.Comment
			});
		}

		private void TiltifyWebsocket_OnTiltifyServiceClosed(object sender, EventArgs e)
		{
			this.OnDisconnected(this, e);
		}

		private void TiltifyWebsocket_OnTiltifyServiceConnected(object sender, EventArgs e)
		{
			if (!string.IsNullOrWhiteSpace(campaignId))
			{
				tiltifyWebsocket.ListenToCampaignDonations(campaignId);
				tiltifyWebsocket.SendTopics(false);
			}
			this.OnConnected(this, e);
		}

		public void Disconnect()
		{
			if (tiltifyWebsocket != null && tiltifyWebsocket.IsConnected)
			{
				tiltifyWebsocket.Disconnect();
			}
			tiltifyWebsocket = null;
			campaignId = null;
			this.OnDisconnected(this, EventArgs.Empty);
		}

		public bool IsConnected()
		{
			if (tiltifyWebsocket != null)
			{
				return tiltifyWebsocket.IsConnected;
			}
			return false;
		}
	}
	internal class UpdateBitsEvent : EventArgs
	{
		public int Bits { get; set; }
	}
	internal class BitsManager
	{
		public int BitGoal { get; set; }

		public int Bits { get; private set; }

		public event EventHandler<UpdateBitsEvent> OnUpdateBits;

		public BitsManager()
			: this(0)
		{
		}

		public BitsManager(int initialBits)
		{
			Bits = initialBits;
			BitGoal = int.MaxValue;
		}

		public void AddBits(int bits)
		{
			if (bits > 0)
			{
				Bits += bits;
				this.OnUpdateBits?.Invoke(this, new UpdateBitsEvent
				{
					Bits = Bits
				});
			}
		}

		public void ResetBits(bool subtractGoal)
		{
			if (subtractGoal)
			{
				Bits = Math.Max(0, Bits - BitGoal);
			}
			else
			{
				Bits = 0;
			}
			this.OnUpdateBits?.Invoke(this, new UpdateBitsEvent
			{
				Bits = Bits
			});
		}
	}
	internal class ChannelPointsManager
	{
		private readonly Dictionary<string, Action<ChannelPointsManager, OnChannelPointsRewardRedeemedArgs>> channelEvents;

		public ChannelPointsManager()
		{
			channelEvents = new Dictionary<string, Action<ChannelPointsManager, OnChannelPointsRewardRedeemedArgs>>();
		}

		public bool RegisterEvent(string eventName, Action<ChannelPointsManager, OnChannelPointsRewardRedeemedArgs> e)
		{
			if (string.IsNullOrWhiteSpace(eventName))
			{
				return false;
			}
			channelEvents[eventName] = e;
			return true;
		}

		public bool UnregisterEvent(string eventName)
		{
			if (!channelEvents.ContainsKey(eventName))
			{
				return false;
			}
			channelEvents.Remove(eventName);
			return true;
		}

		public bool TriggerEvent(OnChannelPointsRewardRedeemedArgs e)
		{
			string title = e.RewardRedeemed.Redemption.Reward.Title;
			if (!channelEvents.ContainsKey(title))
			{
				return false;
			}
			try
			{
				channelEvents[title](this, e);
				return true;
			}
			catch (Exception data)
			{
				Log.Exception(data);
				return false;
			}
		}
	}
	internal class TwitchConstants
	{
		public const string TWITCH_COLOR_MAIN = "9147ff";

		public const string TWITCH_COLOR_MAIN_ACCENT = "772ce7";
	}
	internal class TwitchManager
	{
		private readonly ILoggerFactory loggerFactory;

		private readonly SetupHelper setupHelper;

		private AuthManager Auth;

		private PubSub TwitchPubSub;

		[CompilerGenerated]
		private AsyncEventHandler<OnMessageReceivedArgs> m_OnMessageReceived;

		[CompilerGenerated]
		private AsyncEventHandler<OnJoinedChannelArgs> m_OnConnected;

		[CompilerGenerated]
		private AsyncEventHandler<OnDisconnectedArgs> m_OnDisconnected;

		public bool DebugLogs { get; set; }

		public event AsyncEventHandler<OnMessageReceivedArgs> OnMessageReceived
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnMessageReceivedArgs> val = this.m_OnMessageReceived;
				AsyncEventHandler<OnMessageReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageReceivedArgs> value2 = (AsyncEventHandler<OnMessageReceivedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageReceived, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnMessageReceivedArgs> val = this.m_OnMessageReceived;
				AsyncEventHandler<OnMessageReceivedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnMessageReceivedArgs> value2 = (AsyncEventHandler<OnMessageReceivedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnMessageReceived, value2, val2);
				}
				while (val != val2);
			}
		}

		public event EventHandler<OnChannelPointsRewardRedeemedArgs> OnRewardRedeemed;

		public event AsyncEventHandler<OnJoinedChannelArgs> OnConnected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnJoinedChannelArgs> val = this.m_OnConnected;
				AsyncEventHandler<OnJoinedChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnJoinedChannelArgs> value2 = (AsyncEventHandler<OnJoinedChannelArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnJoinedChannelArgs> val = this.m_OnConnected;
				AsyncEventHandler<OnJoinedChannelArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnJoinedChannelArgs> value2 = (AsyncEventHandler<OnJoinedChannelArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnConnected, value2, val2);
				}
				while (val != val2);
			}
		}

		public event AsyncEventHandler<OnDisconnectedArgs> OnDisconnected
		{
			[CompilerGenerated]
			add
			{
				AsyncEventHandler<OnDisconnectedArgs> val = this.m_OnDisconnected;
				AsyncEventHandler<OnDisconnectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnDisconnectedArgs> value2 = (AsyncEventHandler<OnDisconnectedArgs>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnDisconnected, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				AsyncEventHandler<OnDisconnectedArgs> val = this.m_OnDisconnected;
				AsyncEventHandler<OnDisconnectedArgs> val2;
				do
				{
					val2 = val;
					AsyncEventHandler<OnDisconnectedArgs> value2 = (AsyncEventHandler<OnDisconnectedArgs>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref this.m_OnDisconnected, value2, val2);
				}
				while (val != val2);
			}
		}

		public TwitchManager(SetupHelper setupHelper)
		{
			DebugLogs = false;
			loggerFactory = Log.CreateLoggerFactory((string? type, string? category, LogLevel logLevel) => DebugLogs);
			this.setupHelper = setupHelper;
		}

		private async Task InitializeAuth()
		{
			if (Auth == null)
			{
				string text = Path.Combine(Application.persistentDataPath, "com.justinderby.vstwitch");
				Log.Debug("AuthManager::DataManager basepath = " + text);
				Auth = await AuthManager.Create(DataManager.LoadForModule(text, "TwitchAuth"), loggerFactory);
			}
		}

		public async Task MaybeSetup(Configuration config)
		{
			await Disconnect();
			LogDebug("TwitchManager::MaybeSetup");
			await InitializeAuth();
			if (!Auth.IsAuthed())
			{
				await setupHelper.GuideThroughTwitchIntegration(Auth, config);
			}
		}

		public async Task Connect()
		{
			await Disconnect();
			LogDebug("TwitchManager::Connect");
			LogDebug("[Twitch API] Logging in...");
			await InitializeAuth();
			await Auth.MaybeAuthUser();
			Auth.TwitchClient.OnJoinedChannel += this.OnConnected;
			Auth.TwitchClient.OnMessageReceived += this.OnMessageReceived;
			Auth.TwitchClient.OnConnected += delegate
			{
				Auth.TwitchClient.JoinChannelAsync(Auth.TwitchChannelId, false);
				return Task.CompletedTask;
			};
			Auth.TwitchClient.OnDisconnected += this.OnDisconnected;
			LogDebug("[Twitch Client] Connecting...");
			await Auth.TwitchClient.ConnectAsync();
			LogDebug("[Twitch PubSub] Creating...");
			TwitchPubSub = new PubSub((ILogger<TwitchPubSub>)loggerFactory.CreateLogger<PubSub>());
			TwitchPubSub.OnLog += TwitchPubSub_OnLog;
			TwitchPubSub.OnPubSubServiceConnected += delegate
			{
				Log.Info("[Twitch PubSub] Sending topics to listen too...");
				((TwitchPubSub)TwitchPubSub).ListenToChannelPoints(Auth.TwitchChannelId);
				((TwitchPubSub)TwitchPubSub).ListenToBitsEventsV2(Auth.TwitchChannelId);
				((TwitchPubSub)TwitchPubSub).SendTopicsAsync(Auth.TwitchAPI.Settings.AccessToken, false);
			};
			TwitchPubSub.OnPubSubServiceError += delegate(object sender, OnPubSubServiceErrorArgs e)
			{
				Log.Error($"[Twitch PubSub] ERROR: {e.Exception}");
			};
			TwitchPubSub.OnPubSubServiceClosed += delegate
			{
				Log.Info("[Twitch PubSub] Connection closed");
			};
			TwitchPubSub.OnListenResponse += delegate(object sender, OnListenResponseArgs e)
			{
				if (!e.Successful)
				{
					Log.Error("[Twitch PubSub] Failed to listen! Response: " + JsonConvert.SerializeObject((object)e.Response));
				}
				else
				{
					Log.Info("[Twitch PubSub] Listening to " + e.Topic + " - " + JsonConvert.SerializeObject((object)e.Response));
				}
			};
			TwitchPubSub.OnChannelPointsRewardRedeemed += this.OnRewardRedeemed;
			Log.Info("[Twitch PubSub] Connecting...");
			await ((TwitchPubSub)TwitchPubSub).ConnectAsync();
		}

		public async Task Disconnect()
		{
			LogDebug("TwitchManager::Disconnect");
			if (TwitchPubSub != null)
			{
				try
				{
					await ((TwitchPubSub)TwitchPubSub).DisconnectAsync();
				}
				catch (Exception data)
				{
					Log.Debug(data);
				}
				TwitchPubSub = null;
			}
			if (Auth != null)
			{
				try
				{
					await Auth.TwitchClient.DisconnectAsync();
				}
				catch (Exception data2)
				{
					Log.Debug(data2);
				}
				Auth = null;
			}
		}

		public bool IsConnected()
		{
			if (Auth.TwitchClient != null && Auth.TwitchClient.IsConnected)
			{
				return Auth.IsAuthed();
			}
			return false;
		}

		public void SendMessage(string message)
		{
			if (!IsConnected())
			{
				Log.Warning("[Twitch Client] Not connected to Twitch!");
			}
			else
			{
				Auth.TwitchClient.SendMessageAsync(Auth.TwitchUsername, message, false);
			}
		}

		private void TwitchPubSub_OnLog(object sender, OnLogArgs e)
		{
			LogDebug("[Twitch PubSub] " + e.Data);
		}

		private void LogDebug(string message)
		{
			if (DebugLogs)
			{
				Log.Debug(message);
			}
		}
	}
	internal class VoteItems : MonoBehaviour
	{
		private static readonly int OFFSET_VERTICAL = -128;

		private static readonly int OFFSET_HORIZONTAL = 128;

		private static readonly int TEXT_HEIGHT = 24;

		private GameObject notificationGameObject;

		private GenericNotification notification;

		private float startTime;

		private float duration;

		private int voteIndex;

		private string longTermTitle;

		public void Awake()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			notificationGameObject = Object.Instantiate<GameObject>(LegacyResourcesAPI.Load<GameObject>("Prefabs/NotificationPanel2"));
			SetPosition(new Vector3((float)(Screen.width / 2), (float)(Screen.height / 2), 0f) + new Vector3(0f, (float)OFFSET_VERTICAL, 0f));
			if ((Object)(object)notificationGameObject != (Object)null)
			{
				notification = notificationGameObject.GetComponent<GenericNotification>();
				((Component)notification).transform.SetParent(((Component)RoR2Application.instance.mainCanvas).transform);
				((Behaviour)notification.iconImage).enabled = false;
			}
			else
			{
				Log.Error("Could not load Prefabs/NotificationPanel2, object is null!");
			}
			voteIndex = 0;
			longTermTitle = "";
		}

		public void OnDestroy()
		{
			if ((Object)(object)notificationGameObject != (Object)null)
			{
				Object.Destroy((Object)(object)notificationGameObject);
			}
			notificationGameObject = null;
			notification = null;
		}

		private float GetTimeLeft()
		{
			return duration - (Run.instance.fixedTime - startTime);
		}

		public void Update()
		{
			float num = (Run.instance.fixedTime - startTime) / duration;
			if ((Object)(object)notification == (Object)null || num > 1f)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			notification.SetNotificationT(num);
			if (voteIndex != 0)
			{
				string arg = "";
				if (voteIndex == 1)
				{
					double num2 = Math.Max(0.0, Math.Round(GetTimeLeft()));
					arg = $"({num2} sec)";
				}
				typeof(LanguageTextMeshController).GetField("resolvedString", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(notification.titleText, $"{voteIndex}: {longTermTitle} {arg}");
				typeof(LanguageTextMeshController).GetMethod("UpdateLabel", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(notification.titleText, new object[0]);
			}
			else
			{
				double num3 = Math.Max(0.0, Math.Round(GetTimeLeft()));
				typeof(LanguageTextMeshController).GetField("resolvedString", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(notification.titleText, $"Twitch vote for one item! ({num3} sec)");
				typeof(LanguageTextMeshController).GetMethod("UpdateLabel", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(notification.titleText, new object[0]);
			}
		}

		public void SetItems(List<PickupIndex> items, float duration, int voteIndex = 0)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Invalid comparison between Unknown and I4
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Invalid comparison between Unknown and I4
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Invalid comparison between Unknown and I4
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: 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)
			if ((Object)(object)notification == (Object)null)
			{
				Log.Error("Cannot set items for notification, object is null!");
				return;
			}
			startTime = Run.instance.fixedTime;
			this.duration = duration;
			if (voteIndex != 0)
			{
				((Behaviour)notification.iconImage).enabled = true;
				PickupDef pickupDef = PickupCatalog.GetPickupDef(items[voteIndex - 1]);
				if ((int)pickupDef.equipmentIndex != -1)
				{
					notification.SetEquipment(EquipmentCatalog.GetEquipmentDef(pickupDef.equipmentIndex));
				}
				else if ((int)pickupDef.artifactIndex != -1)
				{
					notification.SetArtifact(ArtifactCatalog.GetArtifactDef(pickupDef.artifactIndex));
				}
				else if ((int)pickupDef.itemIndex != -1)
				{
					notification.SetItem(ItemCatalog.GetItemDef(pickupDef.itemIndex));
				}
				this.voteIndex = voteIndex;
				FieldInfo field = typeof(LanguageTextMeshController).GetField("resolvedString", BindingFlags.Instance | BindingFlags.NonPublic);
				longTermTitle = (string)field.GetValue(notification.titleText);
			}
			else
			{
				for (int i = 0; i < items.Count; i++)
				{
					PickupDef pickupDef2 = PickupCatalog.GetPickupDef(items[i]);
					GameObject val = (((int)pickupDef2.equipmentIndex == -1) ? CreateIcon(ItemCatalog.GetItemDef(pickupDef2.itemIndex).pickupIconSprite) : CreateIcon(EquipmentCatalog.GetEquipmentDef(pickupDef2.equipmentIndex).pickupIconSprite));
					val.transform.SetParent(((Component)notification).transform);
					val.transform.position = new Vector3((float)(Screen.width / 2), (float)(Screen.height / 2), 0f) + new Vector3((float)(i * OFFSET_HORIZONTAL - OFFSET_HORIZONTAL), (float)(OFFSET_VERTICAL + TEXT_HEIGHT), 0f);
				}
				longTermTitle = "";
				this.voteIndex = 0;
			}
		}

		public void SetPosition(Vector3 position)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			notificationGameObject.transform.position = position;
		}

		private static GameObject CreateIcon(Sprite pickupIcon)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("VoteItem_Icon");
			val.AddComponent<Image>().sprite = pickupIcon;
			if ((Object)(object)val.GetComponent<CanvasRenderer>() == (Object)null)
			{
				val.AddComponent<CanvasRenderer>();
			}
			if ((Object)(object)val.GetComponent<RectTransform>() == (Object)null)
			{
				val.AddComponent<RectTransform>();
			}
			val.GetComponent<RectTransform>().sizeDelta = new Vector2(64f, 64f);
			return val;
		}
	}
	[BepInPlugin("com.justinderby.vstwitch", "VsTwitch", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class VsTwitch : BaseUnityPlugin
	{
		private static readonly char[] SPACE = new char[1] { ' ' };

		public const string GUID = "com.justinderby.vstwitch";

		public const string ModName = "VsTwitch";

		public const string Version = "1.1.0";

		public static VsTwitch Instance;

		private TwitchManager twitchManager;

		private BitsManager bitsManager;

		private ChannelPointsManager channelPointsManager;

		private ItemRollerManager itemRollerManager;

		private EventDirector eventDirector;

		private EventFactory eventFactory;

		private TiltifyManager tiltifyManager;

		private Configuration configuration;

		private static void DumpAssemblies()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("===== DUMPING ASSEMBLY INFORMATION =====");
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				stringBuilder.AppendLine(assembly.FullName + ", " + assembly.Location);
			}
			stringBuilder.AppendLine("===== FINISHED DUMPING ASSEMBLY INFORMATION =====");
			Log.Error(stringBuilder.ToString());
		}

		public void Awake()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Expected O, but got Unknown
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Expected O, but got Unknown
			Log.Init(((BaseUnityPlugin)this).Logger);
			Instance = SingletonHelper.Assign<VsTwitch>(Instance, this);
			configuration = new Configuration((BaseUnityPlugin)(object)this, (UnityAction)delegate
			{
				SetUpChannelPoints();
			});
			if ((Object)(object)((Component)this).gameObject.GetComponent<EventDirector>() == (Object)null)
			{
				eventDirector = ((Component)this).gameObject.AddComponent<EventDirector>();
				eventDirector.OnProcessingEventsChanged += delegate(object sender, bool processing)
				{
					//IL_0000: 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)
					//IL_002e: Expected O, but got Unknown
					//IL_003b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0040: Unknown result type (might be due to invalid IL or missing references)
					//IL_0050: Expected O, but got Unknown
					Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
					{
						baseToken = "<color=#9147ff>VsTwitch:</color> Events " + (processing ? "enabled" : "paused") + "."
					});
					try
					{
						if (!twitchManager.IsConnected())
						{
							Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
							{
								baseToken = "<color=#9147ff>VsTwitch:</color> [WARNING] Not connected to Twitch!"
							});
						}
					}
					catch (Exception data)
					{
						Log.Error(data);
					}
				};
			}
			if ((Object)(object)((Component)this).gameObject.GetComponent<EventFactory>() == (Object)null)
			{
				eventFactory = ((Component)this).gameObject.AddComponent<EventFactory>();
			}
			bitsManager = new BitsManager(configuration.CurrentBits.Value);
			SetUpChannelPoints();
			SetupHelper setupHelper = ((Component)this).gameObject.GetComponent<SetupHelper>() ?? ((Component)this).gameObject.AddComponent<SetupHelper>();
			twitchManager = new TwitchManager(setupHelper)
			{
				DebugLogs = configuration.TwitchDebugLogs.Value
			};
			configuration.TwitchDebugLogs.SettingChanged += delegate
			{
				twitchManager.DebugLogs = configuration.TwitchDebugLogs.Value;
			};
			IVoteStrategy<PickupIndex> voteStrategy;
			switch (configuration.VoteStrategy.Value)
			{
			case Configuration.VoteStrategies.Percentile:
				Log.Info("Twitch Voting Strategy: Percentile");
				voteStrategy = new PercentileVoteStrategy<PickupIndex>();
				break;
			case Configuration.VoteStrategies.MaxVoteRandomTie:
				Log.Info("Twitch Voting Strategy: MaxVoteRandomTie");
				voteStrategy = new MaxRandTieVoteStrategy<PickupIndex>();
				break;
			case Configuration.VoteStrategies.MaxVote:
				Log.Info("Twitch Voting Strategy: MaxVote");
				voteStrategy = new MaxVoteStrategy<PickupIndex>();
				break;
			default:
				Log.Error($"Invalid setting for Twitch.VoteStrategy ({configuration.VoteStrategy.Value})! Using MaxVote strategy.");
				voteStrategy = new MaxVoteStrategy<PickupIndex>();
				break;
			}
			itemRollerManager = new ItemRollerManager(voteStrategy);
			tiltifyManager = new TiltifyManager();
			NetworkManagerSystem.onStartHostGlobal += GameNetworkManager_onStartHostGlobal;
			NetworkManagerSystem.onStopHostGlobal += GameNetworkManager_onStopHostGlobal;
			Run.OnEnable += new hook_OnEnable(Run_OnEnable);
			Run.OnDisable += new hook_OnDisable(Run_OnDisable);
			itemRollerManager.OnVoteStart += ItemRollerManager_OnVoteStart;
			bitsManager.BitGoal = configuration.BitsThreshold.Value;
			bitsManager.OnUpdateBits += BitsManager_OnUpdateBits;
			twitchManager.OnConnected += delegate(object? sender, OnJoinedChannelArgs joinedChannel)
			{
				Log.Info("Connected to Twitch! Watching " + joinedChannel.Channel + "...");
				Chat.AddMessage("<color=#9147ff>Connected to Twitch!</color> Watching " + joinedChannel.Channel + "...");
				return Task.CompletedTask;
			};
			twitchManager.OnDisconnected += delegate
			{
				Log.Info("Disconnected from Twitch!");
				Chat.AddMessage("<color=#9147ff>Disconnected from Twitch!</color>");
				return Task.CompletedTask;
			};
			twitchManager.OnMessageReceived += TwitchManager_OnMessageReceived;
			twitchManager.OnRewardRedeemed += TwitchManager_OnRewardRedeemed;
			tiltifyManager.OnConnected += delegate
			{
				Log.Info("Connected to Tiltify!");
				Chat.AddMessage("<color=#9147ff>Connected to Tiltify!</color>");
			};
			tiltifyManager.OnDisconnected += delegate
			{
				Log.Info("Disconnected from Tiltify!");
				Chat.AddMessage("<color=#9147ff>Disconnected from Tiltify!</color>");
			};
			tiltifyManager.OnDonationReceived += TiltifyManager_OnDonationReceived;
		}

		private void SetUpChannelPoints()
		{
			channelPointsManager = new ChannelPointsManager();
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsAllyBeetle.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				eventDirector.AddEvent(eventFactory.CreateAlly(e.RewardRedeemed.Redemption.User.DisplayName, MonsterSpawner.Monsters.Beetle, RollForElite(forceElite: true)));
			}))
			{
				Log.Info("Successfully registered Channel Points event: Ally Beetle (" + configuration.ChannelPointsAllyBeetle.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Ally Beetle");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsAllyLemurian.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				eventDirector.AddEvent(eventFactory.CreateAlly(e.RewardRedeemed.Redemption.User.DisplayName, MonsterSpawner.Monsters.Lemurian, RollForElite(forceElite: true)));
			}))
			{
				Log.Info("Successfully registered Channel Points event: Ally Lemurian (" + configuration.ChannelPointsAllyLemurian.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Ally Lemurian");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsAllyElderLemurian.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				eventDirector.AddEvent(eventFactory.CreateAlly(e.RewardRedeemed.Redemption.User.DisplayName, MonsterSpawner.Monsters.LemurianBruiser, RollForElite(forceElite: true)));
			}))
			{
				Log.Info("Successfully registered Channel Points event: Ally Elder Lemurian (" + configuration.ChannelPointsAllyElderLemurian.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Ally Elder Lemurian");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsRustedKey.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				GiveRustedKey(e.RewardRedeemed.Redemption.User.DisplayName);
			}))
			{
				Log.Info("Successfully registered Channel Points event: Rusted Key (" + configuration.ChannelPointsRustedKey.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Rusted Key");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsBitStorm.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				UsedChannelPoints(e);
				eventDirector.AddEvent(eventFactory.CreateBitStorm());
			}))
			{
				Log.Info("Successfully registered Channel Points event: Bit Storm (" + configuration.ChannelPointsBitStorm.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Bit Storm");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsBounty.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				UsedChannelPoints(e);
				eventDirector.AddEvent(eventFactory.CreateBounty());
			}))
			{
				Log.Info("Successfully registered Channel Points event: Bounty (" + configuration.ChannelPointsBounty.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Bounty");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsShrineOfOrder.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				UsedChannelPoints(e);
				eventDirector.AddEvent(eventFactory.TriggerShrineOfOrder());
			}))
			{
				Log.Info("Successfully registered Channel Points event: Shrine Of Order (" + configuration.ChannelPointsShrineOfOrder.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Shrine Of Order");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsShrineOfTheMountain.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				UsedChannelPoints(e);
				eventDirector.AddEvent(eventFactory.TriggerShrineOfTheMountain());
			}))
			{
				Log.Info("Successfully registered Channel Points event: Shrine Of The Mountain (" + configuration.ChannelPointsShrineOfTheMountain.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Shrine Of The Mountain");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsTitan.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				UsedChannelPoints(e);
				eventDirector.AddEvent(eventFactory.CreateMonster(MonsterSpawner.Monsters.TitanGold, 1, (EliteIndex)(-1)));
			}))
			{
				Log.Info("Successfully registered Channel Points event: Aurelionite (" + configuration.ChannelPointsTitan.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Aurelionite");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsLunarWisp.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				UsedChannelPoints(e);
				eventDirector.AddEvent(eventFactory.CreateMonster(MonsterSpawner.Monsters.LunarWisp, 2, (EliteIndex)(-1)));
			}))
			{
				Log.Info("Successfully registered Channel Points event: Lunar Chimera (Wisp) (" + configuration.ChannelPointsLunarWisp.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Lunar Chimera (Wisp)");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsMithrix.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				UsedChannelPoints(e);
				eventDirector.AddEvent(eventFactory.CreateMonster(MonsterSpawner.Monsters.Brother, 1, (EliteIndex)(-1)));
			}))
			{
				Log.Info("Successfully registered Channel Points event: Mithrix (" + configuration.ChannelPointsMithrix.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Mithrix");
			}
			if (channelPointsManager.RegisterEvent(configuration.ChannelPointsElderLemurian.Value, delegate(ChannelPointsManager manager, OnChannelPointsRewardRedeemedArgs e)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				UsedChannelPoints(e);
				eventDirector.AddEvent(eventFactory.CreateMonster(MonsterSpawner.Monsters.LemurianBruiser, RollForElite()));
			}))
			{
				Log.Info("Successfully registered Channel Points event: Elder Lemurian (" + configuration.ChannelPointsElderLemurian.Value + ")");
			}
			else
			{
				Log.Warning("Could not register Channel Points event: Elder Lemurian");
			}
			void UsedChannelPoints(OnChannelPointsRewardRedeemedArgs e)
			{
				//IL_000c: 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_005f: Expected O, but got Unknown
				eventDirector.AddEvent(eventFactory.BroadcastChat((ChatMessageBase)new SimpleChatMessage
				{
					baseToken = string.Format("<color=#{0}>{1} used their channel points ({2:N0}).</color>", "9147ff", Util.EscapeRichTextForTextMeshPro(e.RewardRedeemed.Redemption.User.DisplayName), e.RewardRedeemed.Redemption.Reward.Cost)
				}));
			}
		}

		public void OnDestroy()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			Instance = SingletonHelper.Unassign<VsTwitch>(Instance, this);
			NetworkManagerSystem.onStartHostGlobal -= GameNetworkManager_onStartHostGlobal;
			NetworkManagerSystem.onStopHostGlobal -= GameNetworkManager_onStopHostGlobal;
			Run.OnEnable -= new hook_OnEnable(Run_OnEnable);
			Run.OnDisable -= new hook_OnDisable(Run_OnDisable);
		}

		private void Run_OnEnable(orig_OnEnable orig, Run self)
		{
			//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)
			//IL_002c: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			orig.Invoke(self);
			if (IsRunning() && NetworkServer.active)
			{
				Chat.SendBroadcastChat((ChatMessageBase)new SimpleChatMessage
				{
					baseToken = "<color=#9147ff>VsTwitch 1.1.0 enabled for run</color>"
				});
				ChestBehavior.ItemDrop += new hook_ItemDrop(ChestBehavior_ItemDrop);
				ShopTerminalBehavior.DropPickup += new hook_DropPickup(ShopTerminalBehavior_DropPickup);
				MultiShopController.OnPurchase += new hook_OnPurchase(MultiShopController_OnPurchase);
				MapZone.TryZoneStart += new hook_TryZoneStart(MapZone_TryZoneStart);
				HealthComponent.Suicide += new hook_Suicide(HealthComponent_Suicide);
				BrotherEncounterBaseState.KillAllMonsters += new hook_KillAllMonsters(BrotherEncounterBaseState_KillAllMonsters);
				ArenaMissionController.EndRound += new hook_EndRound(ArenaMissionController_EndRound);
			}
		}

		private void Run_OnDisable(orig_OnDisable orig, Run self)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			orig.Invoke(self);
			if (IsRunning() && NetworkServer.active)
			{
				ChestBehavior.ItemDrop -= new hook_ItemDrop(ChestBehavior_ItemDrop);
				ShopTerminalBehavior.DropPickup -= new hook_DropPickup(ShopTerminalBehavior_DropPickup);
				MultiShopController.OnPurchase -= new hook_OnPurchase(MultiShopController_OnPurchase);
				MapZone.TryZoneStart -= new hook_TryZoneStart(MapZone_TryZoneStart);
				HealthComponent.Suicide -= new hook_Suicide(HealthComponent_Suicide);
				BrotherEncounterBaseState.KillAllMonsters -= new hook_KillAllMonsters(BrotherEncounterBaseState_KillAllMonsters);
				ArenaMissionController.EndRound -= new hook_EndRound(ArenaMissionController_EndRound);
				eventFactory?.Reset();
				eventDirector?.ClearEvents();
				itemRollerManager?.ClearVotes();
			}
		}

		[ConCommand(/*Could not decode attribute arguments.*/)]
		private static void CCTwitchAddBits(ConCommandArgs args)
		{
			int result;
			if (!Object.op_Implicit((Object)(object)Instance))
			{
				Debug.LogError((object)"VsTwitch mod not instatiated!");
			}
			else if (((ConCommandArgs)(ref args)).Count < 1)
			{
				Log.Error("Requires one arg: <bits>");
			}
			else if (int.TryParse(((ConCommandArgs)(ref args))[0], out result))
			{
				if (result <= 0)
				{
					Log.Error(((ConCommandArgs)(ref args))[0] + " must be positive");
				}
				else
				{
					Instance.RecievedBits("console", result);
				}
			}
			else
			{
				Log.Error(((ConCommandArgs)(ref args))[0] + " is not a number");
			}
		}

		[ConCommand(/*Could not decode attribute arguments.*/)]
		private static void CCTwitchSetBitGoal(ConCommandArgs args)
		{
			int result;
			if (!Object.op_Implicit((Object)(object)Instance))
			{
				Debug.LogError((object)"VsTwitch mod not instatiated!");
			}
			else if (((ConCommandArgs)(ref args)).Count < 1)
			{
				Log.Error("Requires one arg: <bits>");
			}
			else if (int.TryParse(((ConCommandArgs)(ref args))[0], out result))
			{
				if (result <= 0)
				{
					Log.Error(((ConCommandArgs)(ref args))[0] + " must be positive");
					return;
				}
				Instance.configuration.BitsThreshold.Value = result;
				Instance.bitsManager.BitGoal = result;
				Log.Info($"Bit goal set to {result}");
			}
			else
			{
				Log.Error(((ConCommandArgs)(ref args))[0] + " is not a number");
			}
		}

		private bool IsRunning()
		{
			try
			{
				return twitchManager != null && twitchManager.IsConnected();
			}
			catch (Exception data)
			{
				Log.Error(data);
				return false;
			}
		}

		private void GameNetworkManager_onStartHostGlobal()
		{
			Log.Info("Connecting to Twitch...");
			twitchManager.MaybeSetup(configuration).ContinueWith((Task t) => (t.Exception != null) ? Task.FromException(t.Exception) : twitchManager.Connect()).Unwrap()
				.ContinueWith(delegate(Task t)
				{
					if (t.Exception != null)
					{
						Log.Error(t.Exception);
						Chat.AddMessage("Couldn't connect to Twitch: " + t.Exception.Message);
						DumpAssemblies();
					}
				});
			try
			{
				if (!string.IsNullOrWhiteSpace(configuration.TiltifyCampaignId.Value))
				{
					Log.Info("Connecting to Tiltify and watching campaign ID " + configuration.TiltifyCampaignId.Value + "...");
					tiltifyManager.Connect(configuration.TiltifyCampaignId.Value);
				}
			}
			catch (Exception ex)
			{
				Log.Error(ex);
				Chat.AddMessage("Couldn't connect to Tiltify: " + ex.Message);
			}
		}

		private void GameNetworkManager_onStopHostGlobal()
		{
			twitchManager.Disconnect().ContinueWith(delegate(Task t)
			{
				if (t.Exception != null)
				{
					Log.Error(t.Exception);
				}
			});
			try
			{
				tiltifyManager.Disconnect();
			}
			catch (Exception data)
			{
				Log.Error(data);
			}
		}

		private Task TwitchManager_OnMessageReceived(object sender, OnMessageReceivedArgs e)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0686: Unknown result type (might be due to invalid IL or missing references)
			//IL_068b: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bc: Expected O, but got Unknown
			//IL_0642: Unknown result type (might be due to invalid IL or missing references)
			//IL_0647: Unknown result type (might be due to invalid IL or missing references)
			//IL_0671: Expected O, but got Unknown
			//IL_040f: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_046f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!NetworkServer.active)
				{
					Log.Warning("[Server] Server not active");
					return Task.CompletedTask;
				}
				string[] array = e.ChatMessage.Message.Trim().Split(SPACE, 2);
				if (int.TryParse(array[0], out var result))
				{
					Log.Info($"Vote added: {((TwitchLibMessage)e.ChatMessage).Username} ({((TwitchLibMessage)e.ChatMessage).UserId}) -> {result}");
					itemRollerManager.AddVote(((TwitchLibMessage)e.ChatMessage).UserId, result);
				}
				if (e.ChatMessage.Bits > 0 && configuration.EnableBitEvents.Value)
				{
					RecievedBits(((TwitchLibMessage)e.ChatMessage).DisplayName, e.ChatMessage.Bits);
				}
				if (!e.ChatMessage.IsMe)
				{
					UserDetail userDetail = ((TwitchLibMessage)e.ChatMessage).UserDetail;
					if (!((UserDetail)(ref userDetail)).IsModerator && !e.ChatMessage.IsBroadcaster)
					{
						goto IL_0610;
					}
				}
				if (!Object.op_Implicit((Object)(object)eventDirector) || !Object.op_Implicit((Object)(object)eventFactory))
				{
					return Task.CompletedTask;
				}
				switch (array[0])
				{
				case "!allychip":
					eventDirector.AddEvent(eventFactory.CreateAlly(GetUsernameFromCommand(array, "Chip"), MonsterSpawner.Monsters.Beetle, (EliteIndex)(-1)));
					break;
				case "!allysuperchip":
					eventDirector.AddEvent(eventFactory.CreateAlly(GetUsernameFromCommand(array, "Chip"), MonsterSpawner.Monsters.Beetle, RollForElite(forceElite: true)));
					break;
				case "!allydino":
					eventDirector.AddEvent(eventFactory.CreateAlly(GetUsernameFromCommand(array, "Dino"), MonsterSpawner.Monsters.Lemurian, (EliteIndex)(-1)));
					break;
				case "!allysuperdino":
					eventDirector.AddEvent(eventFactory.CreateAlly(GetUsernameFromCommand(array, "Dino"), MonsterSpawner.Monsters.Lemurian, RollForElite(forceElite: true)));
					break;
				case "!allybigdino":
					eventDirector.AddEvent(eventFactory.CreateAlly(GetUsernameFromCommand(array, "Big Dino"), MonsterSpawner.Monsters.LemurianBruiser, (EliteIndex)(-1)));
					break;
				case "!allysuperbigdino":
					eventDirector.AddEvent

Microsoft.Bcl.AsyncInterfaces.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Bcl.AsyncInterfaces")]
[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("Provides the IAsyncEnumerable<T> and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[assembly: TypeForwardedTo(typeof(IAsyncEnumerable<>))]
[assembly: TypeForwardedTo(typeof(IAsyncEnumerator<>))]
[assembly: TypeForwardedTo(typeof(IAsyncDisposable))]
[assembly: TypeForwardedTo(typeof(AsyncIteratorMethodBuilder))]
[assembly: TypeForwardedTo(typeof(AsyncIteratorStateMachineAttribute))]
[assembly: TypeForwardedTo(typeof(ConfiguredAsyncDisposable))]
[assembly: TypeForwardedTo(typeof(ConfiguredCancelableAsyncEnumerable<>))]
[assembly: TypeForwardedTo(typeof(EnumeratorCancellationAttribute))]
[assembly: TypeForwardedTo(typeof(ManualResetValueTaskSourceCore<>))]
[assembly: TypeForwardedTo(typeof(TaskAsyncEnumerableExtensions))]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 System.Diagnostics.CodeAnalysis
{
	[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
	}
}

Microsoft.Extensions.Configuration.Abstractions.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
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.Text;
using FxResources.Microsoft.Extensions.Configuration.Abstractions;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Primitives;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.Abstractions")]
[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("Provides abstractions of key-value pair based configuration. Interfaces defined in this package are implemented by classes in Microsoft.Extensions.Configuration and other configuration packages.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Configuration.Abstractions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
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.Microsoft.Extensions.Configuration.Abstractions
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string InvalidSectionName => GetResourceString("InvalidSectionName");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace Microsoft.Extensions.Configuration
{
	public readonly struct ConfigurationDebugViewContext
	{
		public string Path { get; }

		public string Key { get; }

		public string? Value { get; }

		public IConfigurationProvider ConfigurationProvider { get; }

		public ConfigurationDebugViewContext(string path, string key, string? value, IConfigurationProvider configurationProvider)
		{
			Path = path;
			Key = key;
			Value = value;
			ConfigurationProvider = configurationProvider;
		}
	}
	public static class ConfigurationExtensions
	{
		public static IConfigurationBuilder Add<TSource>(this IConfigurationBuilder builder, Action<TSource>? configureSource) where TSource : IConfigurationSource, new()
		{
			TSource val = new TSource();
			configureSource?.Invoke(val);
			return builder.Add(val);
		}

		public static string? GetConnectionString(this IConfiguration configuration, string name)
		{
			return configuration?.GetSection("ConnectionStrings")[name];
		}

		public static IEnumerable<KeyValuePair<string, string?>> AsEnumerable(this IConfiguration configuration)
		{
			return configuration.AsEnumerable(makePathsRelative: false);
		}

		public static IEnumerable<KeyValuePair<string, string?>> AsEnumerable(this IConfiguration configuration, bool makePathsRelative)
		{
			Stack<IConfiguration> stack = new Stack<IConfiguration>();
			stack.Push(configuration);
			int prefixLength = ((makePathsRelative && configuration is IConfigurationSection configurationSection) ? (configurationSection.Path.Length + 1) : 0);
			while (stack.Count > 0)
			{
				IConfiguration config = stack.Pop();
				if (config is IConfigurationSection configurationSection2 && (!makePathsRelative || config != configuration))
				{
					yield return new KeyValuePair<string, string>(configurationSection2.Path.Substring(prefixLength), configurationSection2.Value);
				}
				foreach (IConfigurationSection child in config.GetChildren())
				{
					stack.Push(child);
				}
			}
		}

		public static bool Exists([NotNullWhen(true)] this IConfigurationSection? section)
		{
			if (section == null)
			{
				return false;
			}
			if (section.Value == null)
			{
				return section.GetChildren().Any();
			}
			return true;
		}

		public static IConfigurationSection GetRequiredSection(this IConfiguration configuration, string key)
		{
			System.ThrowHelper.ThrowIfNull(configuration, "configuration");
			IConfigurationSection section = configuration.GetSection(key);
			if (section.Exists())
			{
				return section;
			}
			throw new InvalidOperationException(System.SR.Format(System.SR.InvalidSectionName, key));
		}
	}
	[AttributeUsage(AttributeTargets.Property)]
	public sealed class ConfigurationKeyNameAttribute : Attribute
	{
		public string Name { get; }

		public ConfigurationKeyNameAttribute(string name)
		{
			Name = name;
		}
	}
	public static class ConfigurationPath
	{
		public static readonly string KeyDelimiter = ":";

		public static string Combine(params string[] pathSegments)
		{
			System.ThrowHelper.ThrowIfNull(pathSegments, "pathSegments");
			return string.Join(KeyDelimiter, pathSegments);
		}

		public static string Combine(IEnumerable<string> pathSegments)
		{
			System.ThrowHelper.ThrowIfNull(pathSegments, "pathSegments");
			return string.Join(KeyDelimiter, pathSegments);
		}

		[return: NotNullIfNotNull("path")]
		public static string? GetSectionKey(string? path)
		{
			if (string.IsNullOrEmpty(path))
			{
				return path;
			}
			int num = path.LastIndexOf(':');
			if (num >= 0)
			{
				return path.Substring(num + 1);
			}
			return path;
		}

		public static string? GetParentPath(string? path)
		{
			if (string.IsNullOrEmpty(path))
			{
				return null;
			}
			int num = path.LastIndexOf(':');
			if (num >= 0)
			{
				return path.Substring(0, num);
			}
			return null;
		}
	}
	public static class ConfigurationRootExtensions
	{
		public static string GetDebugView(this IConfigurationRoot root)
		{
			return root.GetDebugView(null);
		}

		public static string GetDebugView(this IConfigurationRoot root, Func<ConfigurationDebugViewContext, string>? processValue)
		{
			IConfigurationRoot root2 = root;
			Func<ConfigurationDebugViewContext, string> processValue2 = processValue;
			StringBuilder stringBuilder2 = new StringBuilder();
			RecurseChildren(stringBuilder2, root2.GetChildren(), "");
			return stringBuilder2.ToString();
			void RecurseChildren(StringBuilder stringBuilder, IEnumerable<IConfigurationSection> children, string indent)
			{
				foreach (IConfigurationSection child in children)
				{
					(string, IConfigurationProvider) valueAndProvider = GetValueAndProvider(root2, child.Path);
					if (valueAndProvider.Item2 != null)
					{
						string text;
						if (processValue2 == null)
						{
							(text, _) = valueAndProvider;
						}
						else
						{
							text = processValue2(new ConfigurationDebugViewContext(child.Path, child.Key, valueAndProvider.Item1, valueAndProvider.Item2));
						}
						string value = text;
						stringBuilder.Append(indent).Append(child.Key).Append('=')
							.Append(value)
							.Append(" (")
							.Append(valueAndProvider.Item2)
							.AppendLine(")");
					}
					else
					{
						stringBuilder.Append(indent).Append(child.Key).AppendLine(":");
					}
					RecurseChildren(stringBuilder, child.GetChildren(), indent + "  ");
				}
			}
		}

		private static (string Value, IConfigurationProvider Provider) GetValueAndProvider(IConfigurationRoot root, string key)
		{
			foreach (IConfigurationProvider item in root.Providers.Reverse())
			{
				if (item.TryGet(key, out string value))
				{
					return (value, item);
				}
			}
			return (null, null);
		}
	}
	public interface IConfiguration
	{
		string? this[string key] { get; set; }

		IConfigurationSection GetSection(string key);

		IEnumerable<IConfigurationSection> GetChildren();

		IChangeToken GetReloadToken();
	}
	public interface IConfigurationBuilder
	{
		IDictionary<string, object> Properties { get; }

		IList<IConfigurationSource> Sources { get; }

		IConfigurationBuilder Add(IConfigurationSource source);

		IConfigurationRoot Build();
	}
	public interface IConfigurationManager : IConfiguration, IConfigurationBuilder
	{
	}
	public interface IConfigurationProvider
	{
		bool TryGet(string key, out string? value);

		void Set(string key, string? value);

		IChangeToken GetReloadToken();

		void Load();

		IEnumerable<string> GetChildKeys(IEnumerable<string> earlierKeys, string? parentPath);
	}
	public interface IConfigurationRoot : IConfiguration
	{
		IEnumerable<IConfigurationProvider> Providers { get; }

		void Reload();
	}
	public interface IConfigurationSection : IConfiguration
	{
		string Key { get; }

		string Path { get; }

		string? Value { get; set; }
	}
	public interface IConfigurationSource
	{
		IConfigurationProvider Build(IConfigurationBuilder builder);
	}
}

Microsoft.Extensions.Configuration.Binder.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
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.Serialization;
using System.Runtime.Versioning;
using FxResources.Microsoft.Extensions.Configuration.Binder;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.Binder.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.Binder.SourceGeneration.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.Binder")]
[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("Provides the functionality to bind an object to data in configuration providers for Microsoft.Extensions.Configuration. This package enables you to represent the configuration data as strongly-typed classes defined in the application code. To bind a configuration, use the Microsoft.Extensions.Configuration.ConfigurationBinder.Get extension method on the IConfiguration object. To use this package, you also need to install a package for the configuration provider, for example, Microsoft.Extensions.Configuration.Json for the JSON provider.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Configuration.Binder")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.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]
	[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.Microsoft.Extensions.Configuration.Binder
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
		}

		private static void Throw(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "")
		{
			if (argument == null)
			{
				throw new ArgumentNullException(paramName);
			}
			if (string.IsNullOrWhiteSpace(argument))
			{
				if (argument == null)
				{
					throw new ArgumentNullException(paramName);
				}
				throw new ArgumentException(paramName, "Argument is whitespace");
			}
			return argument;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Error_CannotActivateAbstractOrInterface => GetResourceString("Error_CannotActivateAbstractOrInterface");

		internal static string Error_CannotBindToConstructorParameter => GetResourceString("Error_CannotBindToConstructorParameter");

		internal static string Error_ConstructorParametersDoNotMatchProperties => GetResourceString("Error_ConstructorParametersDoNotMatchProperties");

		internal static string Error_FailedBinding => GetResourceString("Error_FailedBinding");

		internal static string Error_FailedToActivate => GetResourceString("Error_FailedToActivate");

		internal static string Error_GeneralErrorWhenBinding => GetResourceString("Error_GeneralErrorWhenBinding");

		internal static string Error_MissingConfig => GetResourceString("Error_MissingConfig");

		internal static string Error_MissingPublicInstanceConstructor => GetResourceString("Error_MissingPublicInstanceConstructor");

		internal static string Error_MultipleParameterizedConstructors => GetResourceString("Error_MultipleParameterizedConstructors");

		internal static string Error_ParameterBeingBoundToIsUnnamed => GetResourceString("Error_ParameterBeingBoundToIsUnnamed");

		internal static string Error_ParameterHasNoMatchingConfig => GetResourceString("Error_ParameterHasNoMatchingConfig");

		internal static string Error_UnsupportedMultidimensionalArray => GetResourceString("Error_UnsupportedMultidimensionalArray");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private 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.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | 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,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[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.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace Microsoft.Extensions.Internal
{
	internal static class ParameterDefaultValue
	{
		public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue)
		{
			bool tryToGetDefaultValue;
			bool num = CheckHasDefaultValue(parameter, out tryToGetDefaultValue);
			defaultValue = null;
			if (num)
			{
				if (tryToGetDefaultValue)
				{
					defaultValue = parameter.DefaultValue;
				}
				bool flag = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>);
				if (defaultValue == null && parameter.ParameterType.IsValueType && !flag)
				{
					defaultValue = CreateValueType(parameter.ParameterType);
				}
				if (defaultValue != null && flag)
				{
					Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType);
					if (underlyingType != null && underlyingType.IsEnum)
					{
						defaultValue = Enum.ToObject(underlyingType, defaultValue);
					}
				}
			}
			return num;
			[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")]
			static object? CreateValueType(Type t)
			{
				return FormatterServices.GetUninitializedObject(t);
			}
		}

		public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue)
		{
			tryToGetDefaultValue = true;
			try
			{
				return parameter.HasDefaultValue;
			}
			catch (FormatException) when (parameter.ParameterType == typeof(DateTime))
			{
				tryToGetDefaultValue = false;
				return true;
			}
		}
	}
}
namespace Microsoft.Extensions.Configuration
{
	public class BinderOptions
	{
		public bool BindNonPublicProperties { get; set; }

		public bool ErrorOnUnknownConfiguration { get; set; }
	}
	internal sealed class BindingPoint
	{
		private readonly Func<object> _initialValueProvider;

		private object _initialValue;

		private object _setValue;

		private bool _valueSet;

		public bool IsReadOnly { get; }

		public bool HasNewValue
		{
			get
			{
				if (IsReadOnly)
				{
					return false;
				}
				if (_valueSet)
				{
					return true;
				}
				Type type = _initialValue?.GetType();
				if ((object)type != null && type.IsValueType)
				{
					return !type.IsPrimitive;
				}
				return false;
			}
		}

		public object? Value
		{
			get
			{
				object obj;
				if (!_valueSet)
				{
					obj = _initialValue;
					if (obj == null)
					{
						return _initialValue = _initialValueProvider?.Invoke();
					}
				}
				else
				{
					obj = _setValue;
				}
				return obj;
			}
		}

		public BindingPoint(object? initialValue = null, bool isReadOnly = false)
		{
			_initialValue = initialValue;
			IsReadOnly = isReadOnly;
		}

		public BindingPoint(Func<object?> initialValueProvider, bool isReadOnly)
		{
			_initialValueProvider = initialValueProvider;
			IsReadOnly = isReadOnly;
		}

		public void SetValue(object? newValue)
		{
			_setValue = newValue;
			_valueSet = true;
		}

		public void TrySetValue(object? newValue)
		{
			if (!IsReadOnly)
			{
				SetValue(newValue);
			}
		}
	}
	public static class ConfigurationBinder
	{
		private const BindingFlags DeclaredOnlyLookup = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private const string DynamicCodeWarningMessage = "Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.";

		private const string TrimmingWarningMessage = "In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.";

		private const string InstanceGetTypeTrimmingWarningMessage = "Cannot statically analyze the type of instance so its members may be trimmed";

		private const string PropertyTrimmingWarningMessage = "Cannot statically analyze property.PropertyType so its members may be trimmed.";

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		public static T? Get<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(this IConfiguration configuration)
		{
			return configuration.Get<T>(null);
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		public static T? Get<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(this IConfiguration configuration, Action<BinderOptions>? configureOptions)
		{
			System.ThrowHelper.ThrowIfNull(configuration, "configuration");
			object obj = configuration.Get(typeof(T), configureOptions);
			if (obj == null)
			{
				return default(T);
			}
			return (T)obj;
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		public static object? Get(this IConfiguration configuration, Type type)
		{
			return configuration.Get(type, null);
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		public static object? Get(this IConfiguration configuration, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, Action<BinderOptions>? configureOptions)
		{
			System.ThrowHelper.ThrowIfNull(configuration, "configuration");
			System.ThrowHelper.ThrowIfNull(type, "type");
			BinderOptions binderOptions = new BinderOptions();
			configureOptions?.Invoke(binderOptions);
			BindingPoint bindingPoint = new BindingPoint();
			BindInstance(type, bindingPoint, configuration, binderOptions, isParentCollection: false);
			return bindingPoint.Value;
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze the type of instance so its members may be trimmed")]
		public static void Bind(this IConfiguration configuration, string key, object? instance)
		{
			System.ThrowHelper.ThrowIfNull(configuration, "configuration");
			configuration.GetSection(key).Bind(instance);
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze the type of instance so its members may be trimmed")]
		public static void Bind(this IConfiguration configuration, object? instance)
		{
			configuration.Bind(instance, null);
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze the type of instance so its members may be trimmed")]
		public static void Bind(this IConfiguration configuration, object? instance, Action<BinderOptions>? configureOptions)
		{
			System.ThrowHelper.ThrowIfNull(configuration, "configuration");
			if (instance != null)
			{
				BinderOptions binderOptions = new BinderOptions();
				configureOptions?.Invoke(binderOptions);
				BindingPoint bindingPoint = new BindingPoint(instance, isReadOnly: true);
				BindInstance(instance.GetType(), bindingPoint, configuration, binderOptions, isParentCollection: false);
			}
		}

		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		public static T? GetValue<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(this IConfiguration configuration, string key)
		{
			return configuration.GetValue(key, default(T));
		}

		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		[return: NotNullIfNotNull("defaultValue")]
		public static T? GetValue<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(this IConfiguration configuration, string key, T defaultValue)
		{
			return (T)configuration.GetValue(typeof(T), key, defaultValue);
		}

		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		public static object? GetValue(this IConfiguration configuration, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, string key)
		{
			return configuration.GetValue(type, key, null);
		}

		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		[return: NotNullIfNotNull("defaultValue")]
		public static object? GetValue(this IConfiguration configuration, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, string key, object? defaultValue)
		{
			System.ThrowHelper.ThrowIfNull(configuration, "configuration");
			System.ThrowHelper.ThrowIfNull(type, "type");
			IConfigurationSection section = configuration.GetSection(key);
			string value = section.Value;
			if (value != null)
			{
				return ConvertValue(type, value, section.Path);
			}
			return defaultValue;
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze property.PropertyType so its members may be trimmed.")]
		private static void BindProperties(object instance, IConfiguration configuration, BinderOptions options, ParameterInfo[] constructorParameters)
		{
			List<PropertyInfo> allProperties = GetAllProperties(instance.GetType());
			if (options.ErrorOnUnknownConfiguration)
			{
				HashSet<string> hashSet = new HashSet<string>(allProperties.Select((PropertyInfo mp) => mp.Name), StringComparer.OrdinalIgnoreCase);
				List<string> list = null;
				foreach (IConfigurationSection child in configuration.GetChildren())
				{
					if (!hashSet.Contains(child.Key))
					{
						(list ?? (list = new List<string>())).Add("'" + child.Key + "'");
					}
				}
				if (list != null)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.Error_MissingConfig, "ErrorOnUnknownConfiguration", "BinderOptions", instance.GetType(), string.Join(", ", list)));
				}
			}
			foreach (PropertyInfo property in allProperties)
			{
				if (constructorParameters == null || !constructorParameters.Any((ParameterInfo p) => p.Name == property.Name))
				{
					BindProperty(property, instance, configuration, options);
				}
				else
				{
					ResetPropertyValue(property, instance, options);
				}
			}
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze property.PropertyType so its members may be trimmed.")]
		private static void ResetPropertyValue(PropertyInfo property, object instance, BinderOptions options)
		{
			if ((object)property.GetMethod != null && (object)property.SetMethod != null && (options.BindNonPublicProperties || (property.GetMethod.IsPublic && property.SetMethod.IsPublic)) && property.GetMethod.GetParameters().Length == 0)
			{
				property.SetValue(instance, property.GetValue(instance));
			}
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze property.PropertyType so its members may be trimmed.")]
		private static void BindProperty(PropertyInfo property, object instance, IConfiguration config, BinderOptions options)
		{
			if (!(property.GetMethod == null) && (options.BindNonPublicProperties || property.GetMethod.IsPublic) && property.GetMethod.GetParameters().Length == 0)
			{
				BindingPoint bindingPoint = new BindingPoint(() => property.GetValue(instance), (object)property.SetMethod == null || (!property.SetMethod.IsPublic && !options.BindNonPublicProperties));
				BindInstance(property.PropertyType, bindingPoint, config.GetSection(GetPropertyName(property)), options, isParentCollection: false);
				if (!bindingPoint.IsReadOnly && bindingPoint.Value != null)
				{
					property.SetValue(instance, bindingPoint.Value);
				}
			}
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		private static void BindInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, BindingPoint bindingPoint, IConfiguration config, BinderOptions options, bool isParentCollection)
		{
			if (type == typeof(IConfigurationSection))
			{
				bindingPoint.TrySetValue(config);
			}
			else
			{
				if (config == null)
				{
					return;
				}
				IConfigurationSection configurationSection = config as IConfigurationSection;
				string text = configurationSection?.Value;
				if (text != null && TryConvertValue(type, text, configurationSection?.Path, out var result, out var error))
				{
					if (error != null)
					{
						throw error;
					}
					bindingPoint.TrySetValue(result);
				}
				else if (config.GetChildren().Any())
				{
					if (type.IsArray || IsImmutableArrayCompatibleInterface(type))
					{
						if (!bindingPoint.IsReadOnly)
						{
							bindingPoint.SetValue(BindArray(type, (IEnumerable)bindingPoint.Value, config, options));
						}
						return;
					}
					if (TypeIsASetInterface(type))
					{
						if (!bindingPoint.IsReadOnly || bindingPoint.Value != null)
						{
							object obj = BindSet(type, (IEnumerable)bindingPoint.Value, config, options);
							if (!bindingPoint.IsReadOnly && obj != null)
							{
								bindingPoint.SetValue(obj);
							}
						}
						return;
					}
					if (TypeIsADictionaryInterface(type))
					{
						if (!bindingPoint.IsReadOnly || bindingPoint.Value != null)
						{
							object obj2 = BindDictionaryInterface(bindingPoint.Value, type, config, options);
							if (!bindingPoint.IsReadOnly && obj2 != null)
							{
								bindingPoint.SetValue(obj2);
							}
						}
						return;
					}
					ParameterInfo[] constructorParameters = null;
					if (bindingPoint.Value == null)
					{
						if (bindingPoint.IsReadOnly)
						{
							return;
						}
						Type type2 = ((type.IsInterface && type.IsConstructedGenericType) ? type.GetGenericTypeDefinition() : null);
						if ((object)type2 != null && (type2 == typeof(ICollection<>) || type2 == typeof(IList<>)))
						{
							Type type3 = typeof(List<>).MakeGenericType(type.GenericTypeArguments);
							bindingPoint.SetValue(Activator.CreateInstance(type3));
						}
						else
						{
							bindingPoint.SetValue(CreateInstance(type, config, options, out constructorParameters));
						}
					}
					Type type4 = FindOpenGenericInterface(typeof(IDictionary<, >), type);
					if (type4 != null)
					{
						BindDictionary(bindingPoint.Value, type4, config, options);
						return;
					}
					Type type5 = FindOpenGenericInterface(typeof(ICollection<>), type);
					if (type5 != null)
					{
						BindCollection(bindingPoint.Value, type5, config, options);
					}
					else
					{
						BindProperties(bindingPoint.Value, config, options, constructorParameters);
					}
				}
				else if (isParentCollection && bindingPoint.Value == null && string.IsNullOrEmpty(text))
				{
					bindingPoint.TrySetValue(CreateInstance(type, config, options, out var _));
				}
			}
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("In case type is a Nullable<T>, cannot statically analyze what the underlying type is so its members may be trimmed.")]
		private static object CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type, IConfiguration config, BinderOptions options, out ParameterInfo[] constructorParameters)
		{
			constructorParameters = null;
			if (type.IsInterface || type.IsAbstract)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.Error_CannotActivateAbstractOrInterface, type));
			}
			ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
			bool flag = type.IsValueType || constructors.Any((ConstructorInfo ctor) => ctor.GetParameters().Length == 0);
			if (!type.IsValueType && constructors.Length == 0)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.Error_MissingPublicInstanceConstructor, type));
			}
			if (constructors.Length > 1 && !flag)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.Error_MultipleParameterizedConstructors, type));
			}
			if (constructors.Length == 1 && !flag)
			{
				ConstructorInfo constructorInfo = constructors[0];
				ParameterInfo[] parameters = constructorInfo.GetParameters();
				if (!CanBindToTheseConstructorParameters(parameters, out var nameOfInvalidParameter))
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.Error_CannotBindToConstructorParameter, type, nameOfInvalidParameter));
				}
				List<PropertyInfo> allProperties = GetAllProperties(type);
				if (!DoAllParametersHaveEquivalentProperties(parameters, allProperties, out var missing))
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.Error_ConstructorParametersDoNotMatchProperties, type, missing));
				}
				object[] array = new object[parameters.Length];
				for (int i = 0; i < parameters.Length; i++)
				{
					array[i] = BindParameter(parameters[i], type, config, options);
				}
				constructorParameters = parameters;
				return constructorInfo.Invoke(array);
			}
			object obj;
			try
			{
				obj = Activator.CreateInstance(Nullable.GetUnderlyingType(type) ?? type);
			}
			catch (Exception innerException)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.Error_FailedToActivate, type), innerException);
			}
			return obj ?? throw new InvalidOperationException(System.SR.Format(System.SR.Error_FailedToActivate, type));
		}

		private static bool DoAllParametersHaveEquivalentProperties(ParameterInfo[] parameters, List<PropertyInfo> properties, out string missing)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (PropertyInfo property in properties)
			{
				hashSet.Add(property.Name);
			}
			List<string> list = new List<string>();
			for (int i = 0; i < parameters.Length; i++)
			{
				string name = parameters[i].Name;
				if (!hashSet.Contains(name))
				{
					list.Add(name);
				}
			}
			missing = string.Join(",", list);
			return missing.Length == 0;
		}

		private static bool CanBindToTheseConstructorParameters(ParameterInfo[] constructorParameters, out string nameOfInvalidParameter)
		{
			nameOfInvalidParameter = string.Empty;
			foreach (ParameterInfo parameterInfo in constructorParameters)
			{
				if (parameterInfo.IsOut || parameterInfo.IsIn || parameterInfo.ParameterType.IsByRef)
				{
					nameOfInvalidParameter = parameterInfo.Name;
					return false;
				}
			}
			return true;
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze what the element type is of the value objects in the dictionary so its members may be trimmed.")]
		private static object BindDictionaryInterface(object source, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type dictionaryType, IConfiguration config, BinderOptions options)
		{
			Type type = dictionaryType.GenericTypeArguments[0];
			Type type2 = dictionaryType.GenericTypeArguments[1];
			bool isEnum = type.IsEnum;
			bool flag = type == typeof(sbyte) || type == typeof(byte) || type == typeof(short) || type == typeof(ushort) || type == typeof(int) || type == typeof(uint) || type == typeof(long) || type == typeof(ulong);
			if (type != typeof(string) && !isEnum && !flag)
			{
				return null;
			}
			MethodInfo method = dictionaryType.GetMethod("Add", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if ((object)method == null || source == null)
			{
				dictionaryType = typeof(Dictionary<, >).MakeGenericType(type, type2);
				object obj = Activator.CreateInstance(dictionaryType);
				method = dictionaryType.GetMethod("Add", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (source is IEnumerable enumerable)
				{
					Type type3 = typeof(KeyValuePair<, >).MakeGenericType(type, type2);
					PropertyInfo property = type3.GetProperty("Key", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					PropertyInfo property2 = type3.GetProperty("Value", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					object[] array = new object[2];
					foreach (object item in enumerable)
					{
						object obj2 = property.GetMethod.Invoke(item, null);
						object obj3 = property2.GetMethod.Invoke(item, null);
						array[0] = obj2;
						array[1] = obj3;
						method.Invoke(obj, array);
					}
				}
				source = obj;
			}
			BindDictionary(source, dictionaryType, config, options);
			return source;
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze what the element type is of the value objects in the dictionary so its members may be trimmed.")]
		private static void BindDictionary(object dictionary, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type dictionaryType, IConfiguration config, BinderOptions options)
		{
			Type type = dictionaryType.GenericTypeArguments[0];
			Type type2 = dictionaryType.GenericTypeArguments[1];
			bool isEnum = type.IsEnum;
			bool flag = type == typeof(sbyte) || type == typeof(byte) || type == typeof(short) || type == typeof(ushort) || type == typeof(int) || type == typeof(uint) || type == typeof(long) || type == typeof(ulong);
			if (type != typeof(string) && !isEnum && !flag)
			{
				return;
			}
			MethodInfo tryGetValue = dictionaryType.GetMethod("TryGetValue", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			PropertyInfo property = dictionaryType.GetProperty("Item", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (IConfigurationSection child in config.GetChildren())
			{
				try
				{
					object key = (isEnum ? Enum.Parse(type, child.Key, ignoreCase: true) : (flag ? Convert.ChangeType(child.Key, type) : child.Key));
					BindingPoint bindingPoint = new BindingPoint(delegate
					{
						object[] array = new object[2] { key, null };
						return (!(bool)tryGetValue.Invoke(dictionary, array)) ? null : array[1];
					}, isReadOnly: false);
					BindInstance(type2, bindingPoint, child, options, isParentCollection: true);
					if (bindingPoint.HasNewValue)
					{
						property.SetValue(dictionary, bindingPoint.Value, new object[1] { key });
					}
				}
				catch (Exception innerException)
				{
					if (options.ErrorOnUnknownConfiguration)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.Error_GeneralErrorWhenBinding, "ErrorOnUnknownConfiguration"), innerException);
					}
				}
			}
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze what the element type is of the object collection so its members may be trimmed.")]
		private static void BindCollection(object collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type collectionType, IConfiguration config, BinderOptions options)
		{
			Type type = collectionType.GenericTypeArguments[0];
			MethodInfo method = collectionType.GetMethod("Add", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (IConfigurationSection child in config.GetChildren())
			{
				try
				{
					BindingPoint bindingPoint = new BindingPoint();
					BindInstance(type, bindingPoint, child, options, isParentCollection: true);
					if (bindingPoint.HasNewValue)
					{
						method?.Invoke(collection, new object[1] { bindingPoint.Value });
					}
				}
				catch (Exception innerException)
				{
					if (options.ErrorOnUnknownConfiguration)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.Error_GeneralErrorWhenBinding, "ErrorOnUnknownConfiguration"), innerException);
					}
				}
			}
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze what the element type is of the Array so its members may be trimmed.")]
		private static Array BindArray(Type type, IEnumerable source, IConfiguration config, BinderOptions options)
		{
			Type type2;
			if (type.IsArray)
			{
				if (type.GetArrayRank() > 1)
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.Error_UnsupportedMultidimensionalArray, type));
				}
				type2 = type.GetElementType();
			}
			else
			{
				type2 = type.GetGenericArguments()[0];
			}
			List<object> list = new List<object>();
			if (source != null)
			{
				foreach (object item in source)
				{
					list.Add(item);
				}
			}
			foreach (IConfigurationSection child in config.GetChildren())
			{
				BindingPoint bindingPoint = new BindingPoint();
				try
				{
					BindInstance(type2, bindingPoint, child, options, isParentCollection: true);
					if (bindingPoint.HasNewValue)
					{
						list.Add(bindingPoint.Value);
					}
				}
				catch (Exception innerException)
				{
					if (options.ErrorOnUnknownConfiguration)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.Error_GeneralErrorWhenBinding, "ErrorOnUnknownConfiguration"), innerException);
					}
				}
			}
			Array array = Array.CreateInstance(type2, list.Count);
			((ICollection)list).CopyTo(array, 0);
			return array;
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze what the element type is of the Array so its members may be trimmed.")]
		private static object BindSet(Type type, IEnumerable source, IConfiguration config, BinderOptions options)
		{
			Type type2 = type.GetGenericArguments()[0];
			bool isEnum = type2.IsEnum;
			if (type2 != typeof(string) && !isEnum)
			{
				return null;
			}
			object[] array = new object[1];
			MethodInfo method = type.GetMethod("Add", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if ((object)method == null || source == null)
			{
				Type type3 = typeof(HashSet<>).MakeGenericType(type2);
				object obj = Activator.CreateInstance(type3);
				method = type3.GetMethod("Add", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (source != null)
				{
					foreach (object item in source)
					{
						array[0] = item;
						method.Invoke(obj, array);
					}
				}
				source = (IEnumerable)obj;
			}
			foreach (IConfigurationSection child in config.GetChildren())
			{
				BindingPoint bindingPoint = new BindingPoint();
				try
				{
					BindInstance(type2, bindingPoint, child, options, isParentCollection: true);
					if (bindingPoint.HasNewValue)
					{
						array[0] = bindingPoint.Value;
						method.Invoke(source, array);
					}
				}
				catch (Exception innerException)
				{
					if (options.ErrorOnUnknownConfiguration)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.Error_GeneralErrorWhenBinding, "ErrorOnUnknownConfiguration"), innerException);
					}
				}
			}
			return source;
		}

		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		private static bool TryConvertValue([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, string value, string path, out object result, out Exception error)
		{
			error = null;
			result = null;
			if (type == typeof(object))
			{
				result = value;
				return true;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
			{
				if (string.IsNullOrEmpty(value))
				{
					return true;
				}
				return TryConvertValue(Nullable.GetUnderlyingType(type), value, path, out result, out error);
			}
			TypeConverter converter = TypeDescriptor.GetConverter(type);
			if (converter.CanConvertFrom(typeof(string)))
			{
				try
				{
					result = converter.ConvertFromInvariantString(value);
				}
				catch (Exception innerException)
				{
					error = new InvalidOperationException(System.SR.Format(System.SR.Error_FailedBinding, path, type), innerException);
				}
				return true;
			}
			if (type == typeof(byte[]))
			{
				try
				{
					result = Convert.FromBase64String(value);
				}
				catch (FormatException innerException2)
				{
					error = new InvalidOperationException(System.SR.Format(System.SR.Error_FailedBinding, path, type), innerException2);
				}
				return true;
			}
			return false;
		}

		[RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
		private static object ConvertValue([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, string value, string path)
		{
			TryConvertValue(type, value, path, out var result, out var error);
			if (error != null)
			{
				throw error;
			}
			return result;
		}

		private static bool TypeIsADictionaryInterface(Type type)
		{
			if (!type.IsInterface || !type.IsConstructedGenericType)
			{
				return false;
			}
			Type genericTypeDefinition = type.GetGenericTypeDefinition();
			if (!(genericTypeDefinition == typeof(IDictionary<, >)))
			{
				return genericTypeDefinition == typeof(IReadOnlyDictionary<, >);
			}
			return true;
		}

		private static bool IsImmutableArrayCompatibleInterface(Type type)
		{
			if (!type.IsInterface || !type.IsConstructedGenericType)
			{
				return false;
			}
			Type genericTypeDefinition = type.GetGenericTypeDefinition();
			if (!(genericTypeDefinition == typeof(IEnumerable<>)) && !(genericTypeDefinition == typeof(IReadOnlyCollection<>)))
			{
				return genericTypeDefinition == typeof(IReadOnlyList<>);
			}
			return true;
		}

		private static bool TypeIsASetInterface(Type type)
		{
			if (!type.IsInterface || !type.IsConstructedGenericType)
			{
				return false;
			}
			return type.GetGenericTypeDefinition() == typeof(ISet<>);
		}

		private static Type FindOpenGenericInterface(Type expected, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] Type actual)
		{
			if (actual.IsGenericType && actual.GetGenericTypeDefinition() == expected)
			{
				return actual;
			}
			Type[] interfaces = actual.GetInterfaces();
			foreach (Type type in interfaces)
			{
				if (type.IsGenericType && type.GetGenericTypeDefinition() == expected)
				{
					return type;
				}
			}
			return null;
		}

		private static List<PropertyInfo> GetAllProperties([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type)
		{
			List<PropertyInfo> list = new List<PropertyInfo>();
			Type type2 = type;
			while (type2 != typeof(object))
			{
				PropertyInfo[] properties = type2.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (PropertyInfo propertyInfo in properties)
				{
					MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
					if ((object)setMethod == null || !setMethod.IsVirtual || setMethod == setMethod.GetBaseDefinition())
					{
						list.Add(propertyInfo);
					}
				}
				type2 = type2.BaseType;
			}
			return list;
		}

		[RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")]
		[RequiresUnreferencedCode("Cannot statically analyze property.PropertyType so its members may be trimmed.")]
		private static object BindParameter(ParameterInfo parameter, Type type, IConfiguration config, BinderOptions options)
		{
			string name = parameter.Name;
			if (name == null)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.Error_ParameterBeingBoundToIsUnnamed, type));
			}
			BindingPoint bindingPoint = new BindingPoint(config.GetSection(name).Value);
			BindInstance(parameter.ParameterType, bindingPoint, config.GetSection(name), options, isParentCollection: false);
			if (bindingPoint.Value == null)
			{
				if (!ParameterDefaultValue.TryGetDefaultValue(parameter, out object defaultValue))
				{
					throw new InvalidOperationException(System.SR.Format(System.SR.Error_ParameterHasNoMatchingConfig, type, name));
				}
				bindingPoint.SetValue(defaultValue);
			}
			return bindingPoint.Value;
		}

		private static string GetPropertyName(PropertyInfo property)
		{
			System.ThrowHelper.ThrowIfNull(property, "property");
			foreach (CustomAttributeData customAttributesDatum in property.GetCustomAttributesData())
			{
				if (!(customAttributesDatum.AttributeType != typeof(ConfigurationKeyNameAttribute)))
				{
					if (customAttributesDatum.ConstructorArguments.Count != 1)
					{
						break;
					}
					string text = customAttributesDatum.ConstructorArguments[0].Value?.ToString();
					return (!string.IsNullOrWhiteSpace(text)) ? text : property.Name;
				}
			}
			return property.Name;
		}
	}
}