Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of VNyanCommands v1.3.0
BepInEx/plugins/VNyanCommands/Microsoft.Extensions.Logging.Abstractions.dll
Decompiled 2 years agousing 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.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(".NETFrameworkAssembly", "")] [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("7.0.723.27404")] [assembly: AssemblyInformationalVersion("7.0.7+5b20af47d99620150c53eaf5db8636fdf730b126")] [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("7.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.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); } } 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 UnexpectedNumberOfNamedParameters => GetResourceString("UnexpectedNumberOfNamedParameters"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.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; 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) { int pos = _pos; 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(ReadOnlySpan<char> value) { int pos = _pos; 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 stringBuilder = new StringBuilder(); DisplayNameOptions options = new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter); ProcessType(stringBuilder, type, in options); return stringBuilder.ToString(); } private static void ProcessType(StringBuilder builder, Type type, in DisplayNameOptions options) { if (type.IsGenericType) { Type[] genericArguments = type.GetGenericArguments(); ProcessGenericType(builder, type, genericArguments, genericArguments.Length, in options); return; } if (type.IsArray) { ProcessArrayType(builder, type, in options); return; } if (_builtInTypeNames.TryGetValue(type, out var value)) { builder.Append(value); return; } if (type.IsGenericParameter) { if (options.IncludeGenericParameterNames) { builder.Append(type.Name); } return; } string text = (options.FullName ? type.FullName : type.Name); builder.Append(text); if (options.NestedTypeDelimiter != '+') { builder.Replace('+', options.NestedTypeDelimiter, builder.Length - text.Length, text.Length); } } private static void ProcessArrayType(StringBuilder builder, Type type, in DisplayNameOptions options) { Type type2 = type; while (type2.IsArray) { type2 = type2.GetElementType(); } ProcessType(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(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 _count; private static ConcurrentDictionary<string, LogValuesFormatter> _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 (_count >= 1024) { if (!_formatters.TryGetValue(format, out _formatter)) { _formatter = new LogValuesFormatter(format); } } else { _formatter = _formatters.GetOrAdd(format, delegate(string f) { Interlocked.Increment(ref _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 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 class Logger<T> : ILogger<T>, ILogger { private readonly ILogger _logger; public Logger(ILoggerFactory factory) { System.ThrowHelper.ThrowIfNull(factory, "factory"); _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T), fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.')); } 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); } } public enum LogLevel { Trace, Debug, Information, Warning, Error, Critical, None } internal sealed class LogValuesFormatter { private const string NullValue = "(null)"; private static readonly char[] FormatDelimiters = new char[2] { ',', ':' }; private readonly string _format; private readonly List<string> _valueNames = new List<string>(); public string OriginalFormat { get; private set; } 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 = FindIndexOfAny(format, FormatDelimiters, num2, num3); 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; } private static int FindIndexOfAny(string format, char[] chars, int startIndex, int endIndex) { int num = format.IndexOfAny(chars, startIndex, endIndex - startIndex); if (num != -1) { return num; } return endIndex; } 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 object FormatArgument(object value) { if (value == null) { return "(null)"; } if (value is string) { return value; } if (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; } return valueStringBuilder.ToString(); } return value; } } 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() { } } } namespace Microsoft.Extensions.Logging.Abstractions { 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; } } }
BepInEx/plugins/VNyanCommands/Newtonsoft.Json.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")] [assembly: CLSCompliant(true)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyFileVersion("13.0.3.27908")] [assembly: AssemblyInformationalVersion("13.0.3+0a2e291c0d9c0c7675d445703e51750363a549ef")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET .NET Standard 2.0")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("13.0.0.0")] 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; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } } namespace Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } public class DefaultJsonNameTable : JsonNameTable { private class Entry { internal readonly string Value; internal readonly int HashCode; internal Entry Next; internal Entry(string value, int hashCode, Entry next) { Value = value; HashCode = hashCode; Next = next; } } private static readonly int HashCodeRandomizer; private int _count; private Entry[] _entries; private int _mask = 31; static DefaultJsonNameTable() { HashCodeRandomizer = Environment.TickCount; } public DefaultJsonNameTable() { _entries = new Entry[_mask + 1]; } public override string? Get(char[] key, int start, int length) { if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; num += (num << 7) ^ key[start]; int num2 = start + length; for (int i = start + 1; i < num2; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; int num3 = Volatile.Read(ref _mask); int num4 = num & num3; for (Entry entry = _entries[num4]; entry != null; entry = entry.Next) { if (entry.HashCode == num && TextEquals(entry.Value, key, start, length)) { return entry.Value; } } return null; } public string Add(string key) { if (key == null) { throw new ArgumentNullException("key"); } int length = key.Length; if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; for (int i = 0; i < key.Length; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal)) { return entry.Value; } } return AddEntry(key, num); } private string AddEntry(string str, int hashCode) { int num = hashCode & _mask; Entry entry = new Entry(str, hashCode, _entries[num]); _entries[num] = entry; if (_count++ == _mask) { Grow(); } return entry.Value; } private void Grow() { Entry[] entries = _entries; int num = _mask * 2 + 1; Entry[] array = new Entry[num + 1]; for (int i = 0; i < entries.Length; i++) { Entry entry = entries[i]; while (entry != null) { int num2 = entry.HashCode & num; Entry next = entry.Next; entry.Next = array[num2]; array[num2] = entry; entry = next; } } _entries = array; Volatile.Write(ref _mask, num); } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) { return false; } for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) { return false; } } return true; } } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[]? array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type? _namingStrategyType; private object[]? _namingStrategyParameters; public string? Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[]? NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy? NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings>? DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } private static string ToStringInternal(BigInteger value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (StringUtils.IndexOf(text, '.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri? value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string? value) { return ToString(value, '"'); } public static string ToString(string? value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object? value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } [DebuggerStepThrough] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } [DebuggerStepThrough] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } [DebuggerStepThrough] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (settings == null || !settings.CheckAdditionalContent) { return; } while (jsonReader.Read()) { if (jsonReader.TokenType != JsonToken.Comment) { throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object."); } } } public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); return SerializeObject(node, formatting, xmlNodeConverter); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter); } public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, omitRootObject: false); } public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter); } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } public abstract class JsonConverter<T> : JsonConverter { public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } WriteJson(writer, (T)value, serializer); } public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool flag = existingValue == null; if (!flag && !(existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer); } public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); public sealed override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[]? ConverterParameters { get; } public JsonConverterAttribute(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception? innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } public abstract class JsonNameTable { public abstract string? Get(char[] key, int start, int length); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal MissingMemberHandling? _missingMemberHandling; internal Required? _itemRequired; internal NullValueHandling? _itemNullValueHandling; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public NullValueHandling ItemNullValueHandling { get { return _itemNullValueHandling.GetValueOrDefault(); } set { _itemNullValueHandling = value; } } public Required ItemRequired { get { return _itemRequired.GetValueOrDefault(); } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; internal JsonContainerType Type; internal int Position; internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); if (writer == null) { writer = new StringWriter(sb); } JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); sb.Append("']"); } else { if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); } break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); StringWriter writer = null; char[] buffer = null; if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder, ref writer, ref buffer); } } currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get; set; } public object[]? NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public int Order { get { return _order.GetValueOrDefault(); } set { _order = value; } } public Required Required { get { return _required.GetValueOrDefault(); } set { _required = value; } } public string? PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object? _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo? _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string? _dateFormatString; private List<JsonPosition>? _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string? DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object? Value => _value; public virtual Type? ValueType => _value?.GetType(); public virtual int Depth { get { int num = _stack?.Count ?? 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync(); } public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (TokenType == JsonToken.PropertyName) { await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth) { } } } internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken) { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { throw CreateUnexpectedEndException(); } } public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean()); } public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes()); } internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) { List<byte> buffer = new List<byte>(); do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(buffer)); byte[] array = buffer.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime()); } public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset()); } public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal()); } public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(ReadAsDouble()); } public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32()); } public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString()); } internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken) { bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (flag) { flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } return flag; } internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken) { JsonToken tokenType = TokenType; if (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { return MoveToContentFromNonContentAsync(cancellationToken); } return AsyncUtils.True; } private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken) { JsonToken tokenType; do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { return false; } tokenType = TokenType; } while (tokenType == JsonToken.None || tokenType == JsonToken.Comment); return true; } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; _maxDepth = 64; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth) { return; } _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is int) { return (int)value; } int num; if (value is BigInteger bigInteger) { num = (int)bigInteger; } else { try { num = Convert.ToInt32(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Integer, num, updateIndex: false); return num; } case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string? ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken)) { object value = Value; if (value != null) { string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture)); SetToken(JsonToken.String, text, updateIndex: false); return text; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[]? ReadAsBytes() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.StartObject: { ReadIntoWrappedTypeObject(); byte[] array2 = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (Value is Guid guid) { byte[] array = guid.ToByteArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); do { if (!Read()) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(list)); byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer) { switch (TokenType) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); return false; case JsonToken.EndArray: return true; case JsonToken.Comment: return false; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is double) { return (double)value; } double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger)); SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L)); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is decimal) { return (decimal)value; } decimal num; if (value is BigInteger bigInteger) { num = (decimal)bigInteger; } else { try { num = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset dateTimeOffset) { SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: return ReadDateTimeString((string)Value); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime dateTime) { SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value != null && Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value) { SetToken(newToken, value, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { _currentState = ((!SupportMultipleContent) ? State.Finished : State.Start); } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadForType(JsonContract? contract, bool hasConverter) { if (hasConverter) { return Read(); } switch (contract?.InternalReadType ?? ReadType.Read) { case ReadType.Read: return ReadAndMoveToContent(); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: { bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long))); } return result; } case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; default: throw new ArgumentOutOfRangeException(); } return TokenType != JsonToken.None; } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, path, lineNumber, linePosition, ex); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonSerializationException(message, path, lineNumber, linePosition, ex); } } public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection? _converters; internal IContractResolver _contractResolver; internal ITraceWriter? _traceWriter; internal IEqualityComparer? _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver? _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string? _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver? ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder is SerializationBinder result) { return result; } if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter) { return serializationBinderAdapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value); } } public virtual ISerializationBinder SerializationBinder { get { return _serializationBinder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = value; } } public virtual ITraceWriter? TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer? EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling; } set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting.GetValueOrDefault(); } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling.GetValueOrDefault(); } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling.GetValueOrDefault(); } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling.GetValueOrDefault(); } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling.GetValueOrDefault(); } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent.GetValueOrDefault(); } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling.HasValue) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } [DebuggerStepThrough] public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } [DebuggerStepThrough] public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader) { return Deserialize(reader, null); } [DebuggerStepThrough] public object? Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } [DebuggerStepThrough] public T? Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader, Type? objectType) { return DeserializeInternal(reader, objectType); } internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable(); } } private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable()) { jsonTextReader.PropertyNameTable = null; } } public void Serialize(TextWriter textWriter, object? value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object? value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object? value) { SerializeInternal(jsonWriter, value, null); } private TraceJsonReader CreateTraceJsonReader(JsonReader reader) { TraceJsonReader traceJsonReader = new TraceJsonReader(reader); if (reader.TokenType != 0) { traceJsonReader.WriteCurrentToken(); } return traceJsonReader; } internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? dateTimeZoneHandling = null; if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? floatFormatHandling = null; if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling) { floatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? stringEscapeHandling = null; if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { stringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo cultureInfo = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { cultureInfo = jsonWriter.Culture; jsonWriter.Culture = _culture; } string dateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { dateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null); new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } if (formatting.HasValue) { jsonWriter.Formatting = formatting.GetValueOrDefault(); } if (dateFormatHandling.HasValue) { jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault(); } if (dateTimeZoneHandling.HasValue) { jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault(); } if (floatFormatHandling.HasValue) { jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault(); } if (stringEscapeHandling.HasValue) { jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = dateFormatString; } if (cultureInfo != null) { jsonWriter.Culture = cultureInfo; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter? GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType) { if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (jsonConverter.CanConvert(objectType)) { return jsonConverter; } } } return null; } internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e) { this.Error?.Invoke(this, e); } } public class JsonSerializerSettings { internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; internal static readonly StreamingContext DefaultContext; internal const Formatting DefaultFormatting = Formatting.None; internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple; internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; internal const int DefaultMaxDepth = 64; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; internal DateTimeZoneHandling? _dateTimeZoneHandling; internal DateParseHandling? _dateParseHandling; internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; internal CultureInfo? _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; internal string? _dateFormatString; internal bool _dateFormatStringSet; internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling; internal DefaultValueHandling? _defaultValueHandling; internal PreserveReferencesHandling? _preserveReferencesHandling; internal NullValueHandling? _nullValueHandling; internal ObjectCreationHandling? _objectCreationHandling; internal MissingMemberHandling? _missingMemberHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal StreamingContext? _context; internal ConstructorHandling? _constructorHandling; internal TypeNameHandling? _typeNameHandling; internal MetadataPropertyHandling? _metadataPropertyHandling; public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public IList<JsonConverter> Converters { get; set; } public PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling.GetValueOrDefault(); } set { _preserveReferencesHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set {
BepInEx/plugins/VNyanCommands/System.Buffers.dll
Decompiled 2 years agousing 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; } } }
BepInEx/plugins/VNyanCommands/System.Collections.NonGeneric.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Security; using System.Threading; using FxResources.System.Collections.NonGeneric; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Collections.NonGeneric")] [assembly: AssemblyDescription("System.Collections.NonGeneric")] [assembly: AssemblyDefaultAlias("System.Collections.NonGeneric")] [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.Collections.NonGeneric { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Collections.NonGeneric.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_AddingDuplicate__ => GetResourceString("Argument_AddingDuplicate__", null); internal static string Argument_ImplementIComparable => GetResourceString("Argument_ImplementIComparable", null); internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall", null); internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported", null); internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow", null); internal static string Arg_RemoveArgNotFound => GetResourceString("Arg_RemoveArgNotFound", null); internal static string Argument_InvalidOffLen => GetResourceString("Argument_InvalidOffLen", null); internal static string ArgumentNull_Array => GetResourceString("ArgumentNull_Array", null); internal static string ArgumentNull_Collection => GetResourceString("ArgumentNull_Collection", null); internal static string ArgumentNull_Dictionary => GetResourceString("ArgumentNull_Dictionary", null); internal static string ArgumentNull_Key => GetResourceString("ArgumentNull_Key", null); internal static string ArgumentOutOfRange_ArrayListInsert => GetResourceString("ArgumentOutOfRange_ArrayListInsert", null); internal static string ArgumentOutOfRange_BiggerThanCollection => GetResourceString("ArgumentOutOfRange_BiggerThanCollection", null); internal static string ArgumentOutOfRange_Count => GetResourceString("ArgumentOutOfRange_Count", null); internal static string ArgumentOutOfRange_HashtableLoadFactor => GetResourceString("ArgumentOutOfRange_HashtableLoadFactor", null); internal static string ArgumentOutOfRange_Index => GetResourceString("ArgumentOutOfRange_Index", null); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null); internal static string ArgumentOutOfRange_SmallCapacity => GetResourceString("ArgumentOutOfRange_SmallCapacity", null); internal static string ArgumentOutOfRange_QueueGrowFactor => GetResourceString("ArgumentOutOfRange_QueueGrowFactor", null); internal static string ArgumentOutOfRange_MustBeNonNegNum => GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", null); internal static string InvalidOperation_EmptyQueue => GetResourceString("InvalidOperation_EmptyQueue", null); internal static string InvalidOperation_EmptyStack => GetResourceString("InvalidOperation_EmptyStack", null); internal static string InvalidOperation_EnumEnded => GetResourceString("InvalidOperation_EnumEnded", null); internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion", null); internal static string InvalidOperation_EnumNotStarted => GetResourceString("InvalidOperation_EnumNotStarted", null); internal static string InvalidOperation_EnumOpCantHappen => GetResourceString("InvalidOperation_EnumOpCantHappen", null); internal static string InvalidOperation_UnderlyingArrayListChanged => GetResourceString("InvalidOperation_UnderlyingArrayListChanged", null); internal static string InvalidOperation_HashInsertFailed => GetResourceString("InvalidOperation_HashInsertFailed", null); internal static string NotSupported_FixedSizeCollection => GetResourceString("NotSupported_FixedSizeCollection", null); internal static string NotSupported_KeyCollectionSet => GetResourceString("NotSupported_KeyCollectionSet", null); internal static string NotSupported_ReadOnlyCollection => GetResourceString("NotSupported_ReadOnlyCollection", null); internal static string NotSupported_RangeCollection => GetResourceString("NotSupported_RangeCollection", null); internal static string NotSupported_SortedListNestedWrite => GetResourceString("NotSupported_SortedListNestedWrite", null); internal static System.Type ResourceType => typeof(FxResources.System.Collections.NonGeneric.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.Collections { [DefaultMember("Item")] [DebuggerTypeProxy(typeof(ArrayListDebugView))] [DebuggerDisplay("Count = {Count}")] public class ArrayList : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { [DefaultMember("Item")] private class IListWrapper : ArrayList { private sealed class IListWrapperEnumWrapper : System.Collections.IEnumerator { private System.Collections.IEnumerator _en; private int _remaining; private int _initialStartIndex; private int _initialCount; private bool _firstCall; public object Current { get { //IL_000d: 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) if (_firstCall) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } if (_remaining < 0) { throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _en.Current; } } internal IListWrapperEnumWrapper(IListWrapper listWrapper, int startIndex, int count) { _en = listWrapper.GetEnumerator(); _initialStartIndex = startIndex; _initialCount = count; while (startIndex-- > 0 && _en.MoveNext()) { } _remaining = count; _firstCall = true; } public bool MoveNext() { if (_firstCall) { _firstCall = false; if (_remaining-- > 0) { return _en.MoveNext(); } return false; } if (_remaining < 0) { return false; } if (_en.MoveNext()) { return _remaining-- > 0; } return false; } public void Reset() { _en.Reset(); int initialStartIndex = _initialStartIndex; while (initialStartIndex-- > 0 && _en.MoveNext()) { } _remaining = _initialCount; _firstCall = true; } } private System.Collections.IList _list; public override int Capacity { get { return ((System.Collections.ICollection)_list).Count; } set { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (value < Count) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity); } } } public override int Count => ((System.Collections.ICollection)_list).Count; public override bool IsReadOnly => _list.IsReadOnly; public override bool IsFixedSize => _list.IsFixedSize; public override bool IsSynchronized => ((System.Collections.ICollection)_list).IsSynchronized; public override object this[int index] { get { return _list[index]; } set { _list[index] = value; _version++; } } public override object SyncRoot => ((System.Collections.ICollection)_list).SyncRoot; internal IListWrapper(System.Collections.IList list) { _list = list; _version = 0; } public override int Add(object obj) { int result = _list.Add(obj); _version++; return result; } public override void AddRange(System.Collections.ICollection c) { InsertRange(Count, c); } public override int BinarySearch(int index, int count, object value, IComparer comparer) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (comparer == null) { comparer = (IComparer)(object)Comparer.Default; } int num = index; int num2 = index + count - 1; while (num <= num2) { int num3 = (num + num2) / 2; int num4 = comparer.Compare(value, _list[num3]); if (num4 == 0) { return num3; } if (num4 < 0) { num2 = num3 - 1; } else { num = num3 + 1; } } return ~num; } public override void Clear() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (_list.IsFixedSize) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } _list.Clear(); _version++; } public override object Clone() { return new IListWrapper(_list); } public override bool Contains(object obj) { return _list.Contains(obj); } public override void CopyTo(System.Array array, int index) { ((System.Collections.ICollection)_list).CopyTo(array, index); } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { //IL_0008: 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) //IL_0040: 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_0070: 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) if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || arrayIndex < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } for (int i = index; i < index + count; i++) { array.SetValue(_list[i], arrayIndex++); } } public override System.Collections.IEnumerator GetEnumerator() { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { //IL_001d: 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 (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new IListWrapperEnumWrapper(this, index, count); } public override int IndexOf(object value) { return _list.IndexOf(value); } public override int IndexOf(object value, int startIndex) { return IndexOf(value, startIndex, ((System.Collections.ICollection)_list).Count - startIndex); } public override int IndexOf(object value, int startIndex, int count) { //IL_0017: 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) if (startIndex < 0 || startIndex > Count) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > Count - count) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } int num = startIndex + count; if (value == null) { for (int i = startIndex; i < num; i++) { if (_list[i] == null) { return i; } } return -1; } for (int j = startIndex; j < num; j++) { if (_list[j] != null && _list[j].Equals(value)) { return j; } } return -1; } public override void Insert(int index, object obj) { _list.Insert(index, obj); _version++; } public override void InsertRange(int index, System.Collections.ICollection c) { //IL_000d: 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 (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } if (index < 0 || index > Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (c.Count <= 0) { return; } if (_list is ArrayList arrayList) { arrayList.InsertRange(index, c); } else { System.Collections.IEnumerator enumerator = ((System.Collections.IEnumerable)c).GetEnumerator(); while (enumerator.MoveNext()) { _list.Insert(index++, enumerator.Current); } } _version++; } public override int LastIndexOf(object value) { return LastIndexOf(value, ((System.Collections.ICollection)_list).Count - 1, ((System.Collections.ICollection)_list).Count); } public override int LastIndexOf(object value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public override int LastIndexOf(object value, int startIndex, int count) { //IL_002b: 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) if (((System.Collections.ICollection)_list).Count == 0) { return -1; } if (startIndex < 0 || startIndex >= ((System.Collections.ICollection)_list).Count) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || count > startIndex + 1) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } int num = startIndex - count + 1; if (value == null) { for (int num2 = startIndex; num2 >= num; num2--) { if (_list[num2] == null) { return num2; } } return -1; } for (int num3 = startIndex; num3 >= num; num3--) { if (_list[num3] != null && _list[num3].Equals(value)) { return num3; } } return -1; } public override void Remove(object value) { int num = IndexOf(value); if (num >= 0) { RemoveAt(num); } } public override void RemoveAt(int index) { _list.RemoveAt(index); _version++; } public override void RemoveRange(int index, int count) { //IL_001d: 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 (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (count > 0) { _version++; } while (count > 0) { _list.RemoveAt(index); count--; } } public override void Reverse(int index, int count) { //IL_001d: 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 (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int num = index; int num2 = index + count - 1; while (num < num2) { object obj = _list[num]; _list[num++] = _list[num2]; _list[num2--] = obj; } _version++; } public override void SetRange(int index, System.Collections.ICollection c) { //IL_000d: 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) if (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } if (index < 0 || index > ((System.Collections.ICollection)_list).Count - c.Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (c.Count > 0) { System.Collections.IEnumerator enumerator = ((System.Collections.IEnumerable)c).GetEnumerator(); while (enumerator.MoveNext()) { _list[index++] = enumerator.Current; } _version++; } } public override ArrayList GetRange(int index, int count) { //IL_001d: 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 (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new Range(this, index, count); } public override void Sort(int index, int count, IComparer comparer) { //IL_001d: 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 (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } object[] array = new object[count]; CopyTo(index, array, 0, count); System.Array.Sort((System.Array)array, 0, count, comparer); for (int i = 0; i < count; i++) { _list[i + index] = array[i]; } _version++; } public override object[] ToArray() { if (Count == 0) { return System.Array.Empty<object>(); } object[] array = new object[Count]; ((System.Collections.ICollection)_list).CopyTo((System.Array)array, 0); return array; } [SecuritySafeCritical] public override System.Array ToArray(System.Type type) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (type == null) { throw new ArgumentNullException("type"); } System.Array array = System.Array.CreateInstance(type, ((System.Collections.ICollection)_list).Count); ((System.Collections.ICollection)_list).CopyTo(array, 0); return array; } public override void TrimToSize() { } } [DefaultMember("Item")] private class SyncArrayList : ArrayList { private ArrayList _list; private object _root; public override int Capacity { get { lock (_root) { return _list.Capacity; } } set { lock (_root) { _list.Capacity = value; } } } public override int Count { get { lock (_root) { return _list.Count; } } } public override bool IsReadOnly => _list.IsReadOnly; public override bool IsFixedSize => _list.IsFixedSize; public override bool IsSynchronized => true; public override object this[int index] { get { lock (_root) { return _list[index]; } } set { lock (_root) { _list[index] = value; } } } public override object SyncRoot => _root; internal SyncArrayList(ArrayList list) : base(trash: false) { _list = list; _root = list.SyncRoot; } public override int Add(object value) { lock (_root) { return _list.Add(value); } } public override void AddRange(System.Collections.ICollection c) { lock (_root) { _list.AddRange(c); } } public override int BinarySearch(object value) { lock (_root) { return _list.BinarySearch(value); } } public override int BinarySearch(object value, IComparer comparer) { lock (_root) { return _list.BinarySearch(value, comparer); } } public override int BinarySearch(int index, int count, object value, IComparer comparer) { lock (_root) { return _list.BinarySearch(index, count, value, comparer); } } public override void Clear() { lock (_root) { _list.Clear(); } } public override object Clone() { lock (_root) { return new SyncArrayList((ArrayList)_list.Clone()); } } public override bool Contains(object item) { lock (_root) { return _list.Contains(item); } } public override void CopyTo(System.Array array) { lock (_root) { _list.CopyTo(array); } } public override void CopyTo(System.Array array, int index) { lock (_root) { _list.CopyTo(array, index); } } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { lock (_root) { _list.CopyTo(index, array, arrayIndex, count); } } public override System.Collections.IEnumerator GetEnumerator() { lock (_root) { return _list.GetEnumerator(); } } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { lock (_root) { return _list.GetEnumerator(index, count); } } public override int IndexOf(object value) { lock (_root) { return _list.IndexOf(value); } } public override int IndexOf(object value, int startIndex) { lock (_root) { return _list.IndexOf(value, startIndex); } } public override int IndexOf(object value, int startIndex, int count) { lock (_root) { return _list.IndexOf(value, startIndex, count); } } public override void Insert(int index, object value) { lock (_root) { _list.Insert(index, value); } } public override void InsertRange(int index, System.Collections.ICollection c) { lock (_root) { _list.InsertRange(index, c); } } public override int LastIndexOf(object value) { lock (_root) { return _list.LastIndexOf(value); } } public override int LastIndexOf(object value, int startIndex) { lock (_root) { return _list.LastIndexOf(value, startIndex); } } public override int LastIndexOf(object value, int startIndex, int count) { lock (_root) { return _list.LastIndexOf(value, startIndex, count); } } public override void Remove(object value) { lock (_root) { _list.Remove(value); } } public override void RemoveAt(int index) { lock (_root) { _list.RemoveAt(index); } } public override void RemoveRange(int index, int count) { lock (_root) { _list.RemoveRange(index, count); } } public override void Reverse(int index, int count) { lock (_root) { _list.Reverse(index, count); } } public override void SetRange(int index, System.Collections.ICollection c) { lock (_root) { _list.SetRange(index, c); } } public override ArrayList GetRange(int index, int count) { lock (_root) { return _list.GetRange(index, count); } } public override void Sort() { lock (_root) { _list.Sort(); } } public override void Sort(IComparer comparer) { lock (_root) { _list.Sort(comparer); } } public override void Sort(int index, int count, IComparer comparer) { lock (_root) { _list.Sort(index, count, comparer); } } public override object[] ToArray() { lock (_root) { return _list.ToArray(); } } public override System.Array ToArray(System.Type type) { lock (_root) { return _list.ToArray(type); } } public override void TrimToSize() { lock (_root) { _list.TrimToSize(); } } } [DefaultMember("Item")] private class SyncIList : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private System.Collections.IList _list; private object _root; public virtual int Count { get { lock (_root) { return ((System.Collections.ICollection)_list).Count; } } } public virtual bool IsReadOnly => _list.IsReadOnly; public virtual bool IsFixedSize => _list.IsFixedSize; public virtual bool IsSynchronized => true; public virtual object this[int index] { get { lock (_root) { return _list[index]; } } set { lock (_root) { _list[index] = value; } } } public virtual object SyncRoot => _root; internal SyncIList(System.Collections.IList list) { _list = list; _root = ((System.Collections.ICollection)list).SyncRoot; } public virtual int Add(object value) { lock (_root) { return _list.Add(value); } } public virtual void Clear() { lock (_root) { _list.Clear(); } } public virtual bool Contains(object item) { lock (_root) { return _list.Contains(item); } } public virtual void CopyTo(System.Array array, int index) { lock (_root) { ((System.Collections.ICollection)_list).CopyTo(array, index); } } public virtual System.Collections.IEnumerator GetEnumerator() { lock (_root) { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } } public virtual int IndexOf(object value) { lock (_root) { return _list.IndexOf(value); } } public virtual void Insert(int index, object value) { lock (_root) { _list.Insert(index, value); } } public virtual void Remove(object value) { lock (_root) { _list.Remove(value); } } public virtual void RemoveAt(int index) { lock (_root) { _list.RemoveAt(index); } } } [DefaultMember("Item")] private class FixedSizeList : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private System.Collections.IList _list; public virtual int Count => ((System.Collections.ICollection)_list).Count; public virtual bool IsReadOnly => _list.IsReadOnly; public virtual bool IsFixedSize => true; public virtual bool IsSynchronized => ((System.Collections.ICollection)_list).IsSynchronized; public virtual object this[int index] { get { return _list[index]; } set { _list[index] = value; } } public virtual object SyncRoot => ((System.Collections.ICollection)_list).SyncRoot; internal FixedSizeList(System.Collections.IList l) { _list = l; } public virtual int Add(object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public virtual void Clear() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public virtual bool Contains(object obj) { return _list.Contains(obj); } public virtual void CopyTo(System.Array array, int index) { ((System.Collections.ICollection)_list).CopyTo(array, index); } public virtual System.Collections.IEnumerator GetEnumerator() { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } public virtual int IndexOf(object value) { return _list.IndexOf(value); } public virtual void Insert(int index, object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public virtual void Remove(object value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public virtual void RemoveAt(int index) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } } [DefaultMember("Item")] private class FixedSizeArrayList : ArrayList { private ArrayList _list; public override int Count => _list.Count; public override bool IsReadOnly => _list.IsReadOnly; public override bool IsFixedSize => true; public override bool IsSynchronized => _list.IsSynchronized; public override object this[int index] { get { return _list[index]; } set { _list[index] = value; _version = _list._version; } } public override object SyncRoot => _list.SyncRoot; public override int Capacity { get { return _list.Capacity; } set { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } } internal FixedSizeArrayList(ArrayList l) { _list = l; _version = _list._version; } public override int Add(object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void AddRange(System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override int BinarySearch(int index, int count, object value, IComparer comparer) { return _list.BinarySearch(index, count, value, comparer); } public override void Clear() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override object Clone() { FixedSizeArrayList fixedSizeArrayList = new FixedSizeArrayList(_list); fixedSizeArrayList._list = (ArrayList)_list.Clone(); return fixedSizeArrayList; } public override bool Contains(object obj) { return _list.Contains(obj); } public override void CopyTo(System.Array array, int index) { _list.CopyTo(array, index); } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { _list.CopyTo(index, array, arrayIndex, count); } public override System.Collections.IEnumerator GetEnumerator() { return _list.GetEnumerator(); } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { return _list.GetEnumerator(index, count); } public override int IndexOf(object value) { return _list.IndexOf(value); } public override int IndexOf(object value, int startIndex) { return _list.IndexOf(value, startIndex); } public override int IndexOf(object value, int startIndex, int count) { return _list.IndexOf(value, startIndex, count); } public override void Insert(int index, object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void InsertRange(int index, System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override int LastIndexOf(object value) { return _list.LastIndexOf(value); } public override int LastIndexOf(object value, int startIndex) { return _list.LastIndexOf(value, startIndex); } public override int LastIndexOf(object value, int startIndex, int count) { return _list.LastIndexOf(value, startIndex, count); } public override void Remove(object value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void RemoveAt(int index) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void RemoveRange(int index, int count) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void SetRange(int index, System.Collections.ICollection c) { _list.SetRange(index, c); _version = _list._version; } public override ArrayList GetRange(int index, int count) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new Range(this, index, count); } public override void Reverse(int index, int count) { _list.Reverse(index, count); _version = _list._version; } public override void Sort(int index, int count, IComparer comparer) { _list.Sort(index, count, comparer); _version = _list._version; } public override object[] ToArray() { return _list.ToArray(); } public override System.Array ToArray(System.Type type) { return _list.ToArray(type); } public override void TrimToSize() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } } [DefaultMember("Item")] private class ReadOnlyList : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private System.Collections.IList _list; public virtual int Count => ((System.Collections.ICollection)_list).Count; public virtual bool IsReadOnly => true; public virtual bool IsFixedSize => true; public virtual bool IsSynchronized => ((System.Collections.ICollection)_list).IsSynchronized; public virtual object this[int index] { get { return _list[index]; } set { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } public virtual object SyncRoot => ((System.Collections.ICollection)_list).SyncRoot; internal ReadOnlyList(System.Collections.IList l) { _list = l; } public virtual int Add(object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public virtual void Clear() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public virtual bool Contains(object obj) { return _list.Contains(obj); } public virtual void CopyTo(System.Array array, int index) { ((System.Collections.ICollection)_list).CopyTo(array, index); } public virtual System.Collections.IEnumerator GetEnumerator() { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } public virtual int IndexOf(object value) { return _list.IndexOf(value); } public virtual void Insert(int index, object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public virtual void Remove(object value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public virtual void RemoveAt(int index) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } [DefaultMember("Item")] private class ReadOnlyArrayList : ArrayList { private ArrayList _list; public override int Count => _list.Count; public override bool IsReadOnly => true; public override bool IsFixedSize => true; public override bool IsSynchronized => _list.IsSynchronized; public override object this[int index] { get { return _list[index]; } set { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } public override object SyncRoot => _list.SyncRoot; public override int Capacity { get { return _list.Capacity; } set { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } internal ReadOnlyArrayList(ArrayList l) { _list = l; } public override int Add(object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void AddRange(System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override int BinarySearch(int index, int count, object value, IComparer comparer) { return _list.BinarySearch(index, count, value, comparer); } public override void Clear() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override object Clone() { ReadOnlyArrayList readOnlyArrayList = new ReadOnlyArrayList(_list); readOnlyArrayList._list = (ArrayList)_list.Clone(); return readOnlyArrayList; } public override bool Contains(object obj) { return _list.Contains(obj); } public override void CopyTo(System.Array array, int index) { _list.CopyTo(array, index); } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { _list.CopyTo(index, array, arrayIndex, count); } public override System.Collections.IEnumerator GetEnumerator() { return _list.GetEnumerator(); } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { return _list.GetEnumerator(index, count); } public override int IndexOf(object value) { return _list.IndexOf(value); } public override int IndexOf(object value, int startIndex) { return _list.IndexOf(value, startIndex); } public override int IndexOf(object value, int startIndex, int count) { return _list.IndexOf(value, startIndex, count); } public override void Insert(int index, object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void InsertRange(int index, System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override int LastIndexOf(object value) { return _list.LastIndexOf(value); } public override int LastIndexOf(object value, int startIndex) { return _list.LastIndexOf(value, startIndex); } public override int LastIndexOf(object value, int startIndex, int count) { return _list.LastIndexOf(value, startIndex, count); } public override void Remove(object value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void RemoveAt(int index) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void RemoveRange(int index, int count) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void SetRange(int index, System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override ArrayList GetRange(int index, int count) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new Range(this, index, count); } public override void Reverse(int index, int count) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void Sort(int index, int count, IComparer comparer) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override object[] ToArray() { return _list.ToArray(); } public override System.Array ToArray(System.Type type) { return _list.ToArray(type); } public override void TrimToSize() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } private sealed class ArrayListEnumerator : System.Collections.IEnumerator { private ArrayList _list; private int _index; private int _endIndex; private int _version; private object _currentElement; private int _startIndex; public object Current { get { //IL_0013: 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) if (_index < _startIndex) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } if (_index > _endIndex) { throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _currentElement; } } internal ArrayListEnumerator(ArrayList list, int index, int count) { _list = list; _startIndex = index; _index = index - 1; _endIndex = _index + count; _version = list._version; _currentElement = null; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (_index < _endIndex) { _currentElement = _list[++_index]; return true; } _index = _endIndex + 1; return false; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = _startIndex - 1; } } [DefaultMember("Item")] private class Range : ArrayList { private ArrayList _baseList; private int _baseIndex; private int _baseSize; private int _baseVersion; public override int Capacity { get { return _baseList.Capacity; } set { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (value < Count) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity); } } } public override int Count { get { InternalUpdateRange(); return _baseSize; } } public override bool IsReadOnly => _baseList.IsReadOnly; public override bool IsFixedSize => _baseList.IsFixedSize; public override bool IsSynchronized => _baseList.IsSynchronized; public override object SyncRoot => _baseList.SyncRoot; public override object this[int index] { get { //IL_001d: Unknown result type (might be due to invalid IL or missing references) InternalUpdateRange(); if (index < 0 || index >= _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } return _baseList[_baseIndex + index]; } set { //IL_001d: Unknown result type (might be due to invalid IL or missing references) InternalUpdateRange(); if (index < 0 || index >= _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } _baseList[_baseIndex + index] = value; InternalUpdateVersion(); } } internal Range(ArrayList list, int index, int count) : base(trash: false) { _baseList = list; _baseIndex = index; _baseSize = count; _baseVersion = list._version; _version = list._version; } private void InternalUpdateRange() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_baseVersion != _baseList._version) { throw new InvalidOperationException(SR.InvalidOperation_UnderlyingArrayListChanged); } } private void InternalUpdateVersion() { _baseVersion++; _version++; } public override int Add(object value) { InternalUpdateRange(); _baseList.Insert(_baseIndex + _baseSize, value); InternalUpdateVersion(); return _baseSize++; } public override void AddRange(System.Collections.ICollection c) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c"); } InternalUpdateRange(); int count = c.Count; if (count > 0) { _baseList.InsertRange(_baseIndex + _baseSize, c); InternalUpdateVersion(); _baseSize += count; } } public override int BinarySearch(int index, int count, object value, IComparer comparer) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); int num = _baseList.BinarySearch(_baseIndex + index, count, value, comparer); if (num >= 0) { return num - _baseIndex; } return num + _baseIndex; } public override void Clear() { InternalUpdateRange(); if (_baseSize != 0) { _baseList.RemoveRange(_baseIndex, _baseSize); InternalUpdateVersion(); _baseSize = 0; } } public override object Clone() { InternalUpdateRange(); Range range = new Range(_baseList, _baseIndex, _baseSize); range._baseList = (ArrayList)_baseList.Clone(); return range; } public override bool Contains(object item) { InternalUpdateRange(); if (item == null) { for (int i = 0; i < _baseSize; i++) { if (_baseList[_baseIndex + i] == null) { return true; } } return false; } for (int j = 0; j < _baseSize; j++) { if (_baseList[_baseIndex + j] != null && _baseList[_baseIndex + j].Equals(item)) { return true; } } return false; } public override void CopyTo(System.Array array, int index) { //IL_0008: 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_0035: 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 (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _baseSize) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); _baseList.CopyTo(_baseIndex, array, index, _baseSize); } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { //IL_0008: 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_0045: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); _baseList.CopyTo(_baseIndex + index, array, arrayIndex, count); } public override System.Collections.IEnumerator GetEnumerator() { return GetEnumerator(0, _baseSize); } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); return _baseList.GetEnumerator(_baseIndex + index, count); } public override ArrayList GetRange(int index, int count) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); return new Range(this, index, count); } public override int IndexOf(object value) { InternalUpdateRange(); int num = _baseList.IndexOf(value, _baseIndex, _baseSize); if (num >= 0) { return num - _baseIndex; } return -1; } public override int IndexOf(object value, int startIndex) { //IL_000e: 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) if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (startIndex > _baseSize) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } InternalUpdateRange(); int num = _baseList.IndexOf(value, _baseIndex + startIndex, _baseSize - startIndex); if (num >= 0) { return num - _baseIndex; } return -1; } public override int IndexOf(object value, int startIndex, int count) { //IL_0017: 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) if (startIndex < 0 || startIndex > _baseSize) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > _baseSize - count) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } InternalUpdateRange(); int num = _baseList.IndexOf(value, _baseIndex + startIndex, count); if (num >= 0) { return num - _baseIndex; } return -1; } public override void Insert(int index, object value) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index > _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } InternalUpdateRange(); _baseList.Insert(_baseIndex + index, value); InternalUpdateVersion(); _baseSize++; } public override void InsertRange(int index, System.Collections.ICollection c) { //IL_0017: 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 (index < 0 || index > _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (c == null) { throw new ArgumentNullException("c"); } InternalUpdateRange(); int count = c.Count; if (count > 0) { _baseList.InsertRange(_baseIndex + index, c); _baseSize += count; InternalUpdateVersion(); } } public override int LastIndexOf(object value) { InternalUpdateRange(); int num = _baseList.LastIndexOf(value, _baseIndex + _baseSize - 1, _baseSize); if (num >= 0) { return num - _baseIndex; } return -1; } public override int LastIndexOf(object value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public override int LastIndexOf(object value, int startIndex, int count) { //IL_0023: 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) InternalUpdateRange(); if (_baseSize == 0) { return -1; } if (startIndex >= _baseSize) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } int num = _baseList.LastIndexOf(value, _baseIndex + startIndex, count); if (num >= 0) { return num - _baseIndex; } return -1; } public override void RemoveAt(int index) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } InternalUpdateRange(); _baseList.RemoveAt(_baseIndex + index); InternalUpdateVersion(); _baseSize--; } public override void RemoveRange(int index, int count) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); if (count > 0) { _baseList.RemoveRange(_baseIndex + index, count); InternalUpdateVersion(); _baseSize -= count; } } public override void Reverse(int index, int count) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); _baseList.Reverse(_baseIndex + index, count); InternalUpdateVersion(); } public override void SetRange(int index, System.Collections.ICollection c) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) InternalUpdateRange(); if (index < 0 || index >= _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } _baseList.SetRange(_baseIndex + index, c); if (c.Count > 0) { InternalUpdateVersion(); } } public override void Sort(int index, int count, IComparer comparer) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); _baseList.Sort(_baseIndex + index, count, comparer); InternalUpdateVersion(); } public override object[] ToArray() { InternalUpdateRange(); if (_baseSize == 0) { return System.Array.Empty<object>(); } object[] array = new object[_baseSize]; System.Array.Copy((System.Array)_baseList._items, _baseIndex, (System.Array)array, 0, _baseSize); return array; } [SecuritySafeCritical] public override System.Array ToArray(System.Type type) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (type == null) { throw new ArgumentNullException("type"); } InternalUpdateRange(); System.Array array = System.Array.CreateInstance(type, _baseSize); _baseList.CopyTo(_baseIndex, array, 0, _baseSize); return array; } public override void TrimToSize() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_RangeCollection); } } private sealed class ArrayListEnumeratorSimple : System.Collections.IEnumerator { private ArrayList _list; private int _index; private int _version; private object _currentElement; private bool _isArrayList; private static object s_dummyObject = new object(); public object Current { get { //IL_0028: 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) object currentElement = _currentElement; if (s_dummyObject == currentElement) { if (_index == -1) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return currentElement; } } internal ArrayListEnumeratorSimple(ArrayList list) { _list = list; _index = -1; _version = list._version; _isArrayList = ((object)list).GetType() == typeof(ArrayList); _currentElement = s_dummyObject; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (_isArrayList) { if (_index < _list._size - 1) { _currentElement = _list._items[++_index]; return true; } _currentElement = s_dummyObject; _index = _list._size; return false; } if (_index < _list.Count - 1) { _currentElement = _list[++_index]; return true; } _index = _list.Count; _currentElement = s_dummyObject; return false; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _currentElement = s_dummyObject; _index = -1; } } internal class ArrayListDebugView { private ArrayList _arrayList; [DebuggerBrowsable(/*Could not decode attribute arguments.*/)] public object[] Items => _arrayList.ToArray(); public ArrayListDebugView(ArrayList arrayList) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (arrayList == null) { throw new ArgumentNullException("arrayList"); } _arrayList = arrayList; } } private object[] _items; private int _size; private int _version; private object _syncRoot; private const int _defaultCapacity = 4; internal const int MaxArrayLength = 2146435071; public virtual int Capacity { get { return _items.Length; } set { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (value < _size) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity); } if (value == _items.Length) { return; } if (value > 0) { object[] array = new object[value]; if (_size > 0) { System.Array.Copy((System.Array)_items, 0, (System.Array)array, 0, _size); } _items = array; } else { _items = new object[4]; } } } public virtual int Count => _size; public virtual bool IsFixedSize => false; public virtual bool IsReadOnly => false; public virtual bool IsSynchronized => false; public virtual object SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange<object>(ref _syncRoot, new object(), (object)null); } return _syncRoot; } } public virtual object this[int index] { get { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } return _items[index]; } set { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } _items[index] = value; _version++; } } internal ArrayList(bool trash) { } public ArrayList() { _items = System.Array.Empty<object>(); } public ArrayList(int capacity) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, "capacity")); } if (capacity == 0) { _items = System.Array.Empty<object>(); } else { _items = new object[capacity]; } } public ArrayList(System.Collections.ICollection c) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } int count = c.Count; if (count == 0) { _items = System.Array.Empty<object>(); return; } _items = new object[count]; AddRange(c); } public static ArrayList Adapter(System.Collections.IList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new IListWrapper(list); } public virtual int Add(object value) { if (_size == _items.Length) { EnsureCapacity(_size + 1); } _items[_size] = value; _version++; return _size++; } public virtual void AddRange(System.Collections.ICollection c) { InsertRange(_size, c); } public virtual int BinarySearch(int index, int count, object value, IComparer comparer) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return System.Array.BinarySearch((System.Array)_items, index, count, value, comparer); } public virtual int BinarySearch(object value) { return BinarySearch(0, Count, value, null); } public virtual int BinarySearch(object value, IComparer comparer) { return BinarySearch(0, Count, value, comparer); } public virtual void Clear() { if (_size > 0) { System.Array.Clear((System.Array)_items, 0, _size); _size = 0; } _version++; } public virtual object Clone() { ArrayList arrayList = new ArrayList(_size); arrayList._size = _size; arrayList._version = _version; System.Array.Copy((System.Array)_items, 0, (System.Array)arrayList._items, 0, _size); return arrayList; } public virtual bool Contains(object item) { if (item == null) { for (int i = 0; i < _size; i++) { if (_items[i] == null) { return true; } } return false; } for (int j = 0; j < _size; j++) { if (_items[j] != null && _items[j].Equals(item)) { return true; } } return false; } public virtual void CopyTo(System.Array array) { CopyTo(array, 0); } public virtual void CopyTo(System.Array array, int arrayIndex) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (array != null && array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } System.Array.Copy((System.Array)_items, 0, array, arrayIndex, _size); } public virtual void CopyTo(int index, System.Array array, int arrayIndex, int count) { //IL_0011: 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 (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (array != null && array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } System.Array.Copy((System.Array)_items, index, array, arrayIndex, count); } private void EnsureCapacity(int min) { if (_items.Length < min) { int num = ((_items.Length == 0) ? 4 : (_items.Length * 2)); if ((uint)num > 2146435071u) { num = 2146435071; } if (num < min) { num = min; } Capacity = num; } } public static System.Collections.IList FixedSize(System.Collections.IList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new FixedSizeList(list); } public static ArrayList FixedSize(ArrayList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new FixedSizeArrayList(list); } public virtual System.Collections.IEnumerator GetEnumerator() { return new ArrayListEnumeratorSimple(this); } public virtual System.Collections.IEnumerator GetEnumerator(int index, int count) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new ArrayListEnumerator(this, index, count); } public virtual int IndexOf(object value) { return System.Array.IndexOf((System.Array)_items, value, 0, _size); } public virtual int IndexOf(object value, int startIndex) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (startIndex > _size) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } return System.Array.IndexOf((System.Array)_items, value, startIndex, _size - startIndex); } public virtual int IndexOf(object value, int startIndex, int count) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (startIndex > _size) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > _size - count) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } return System.Array.IndexOf((System.Array)_items, value, startIndex, count); } public virtual void Insert(int index, object value) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index > _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_ArrayListInsert); } if (_size == _items.Length) { EnsureCapacity(_size + 1); } if (index < _size) { System.Array.Copy((System.Array)_items, index, (System.Array)_items, index + 1, _size - index); } _items[index] = value; _size++; _version++; } public virtual void InsertRange(int index, System.Collections.ICollection c) { //IL_000d: 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 (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } if (index < 0 || index > _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } int count = c.Count; if (count > 0) { EnsureCapacity(_size + count); if (index < _size) { System.Array.Copy((System.Array)_items, index, (System.Array)_items, index + count, _size - index); } object[] array = new object[count]; c.CopyTo((System.Array)array, 0); ((System.Array)array).CopyTo((System.Array)_items, index); _size += count; _version++; } } public virtual int LastIndexOf(object value) { return LastIndexOf(value, _size - 1, _size); } public virtual int LastIndexOf(object value, int startIndex) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (startIndex >= _size) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } return LastIndexOf(value, startIndex, startIndex + 1); } public virtual int LastIndexOf(object value, int startIndex, int count) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) if (Count != 0 && (startIndex < 0 || count < 0)) { throw new ArgumentOutOfRangeException((startIndex < 0) ? "startIndex" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size == 0) { return -1; } if (startIndex >= _size || count > startIndex + 1) { throw new ArgumentOutOfRangeException((startIndex >= _size) ? "startIndex" : "count", SR.ArgumentOutOfRange_BiggerThanCollection); } return System.Array.LastIndexOf((System.Array)_items, value, startIndex, count); } public static System.Collections.IList ReadOnly(System.Collections.IList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new ReadOnlyList(list); } public static ArrayList ReadOnly(ArrayList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new ReadOnlyArrayList(list); } public virtual void Remove(object obj) { int num = IndexOf(obj); if (num >= 0) { RemoveAt(num); } } public virtual void RemoveAt(int index) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } _size--; if (index < _size) { System.Array.Copy((System.Array)_items, index + 1, (System.Array)_items, index, _size - index); } _items[_size] = null; _version++; } public virtual void RemoveRange(int index, int count) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (count > 0) { int num = _size; _size -= count; if (index < _size) { System.Array.Copy((System.Array)_items, index + count, (System.Array)_items, index, _size - index); } while (num > _size) { _items[--num] = null; } _version++; } } public static ArrayList Repeat(object value, int count) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } ArrayList arrayList = new ArrayList((count > 4) ? count : 4); for (int i = 0; i < count; i++) { arrayList.Add(value); } return arrayList; } public virtual void Reverse() { Reverse(0, Count); } public virtual void Reverse(int index, int count) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } System.Array.Reverse((System.Array)_items, index, count); _version++; } public virtual void SetRange(int index, System.Collections.ICollection c) { //IL_000d: 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) if (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } int count = c.Count; if (index < 0 || index > _size - count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (count > 0) { c.CopyTo((System.Array)_items, index); _version++; } } public virtual ArrayList GetRange(int index, int count) { //IL_001d: 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) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new Range(this, index, count); } public virtual void Sort() { Sort(0, Count, (IComparer)(object)Comparer.Default); } public virtual void Sort(IComparer comparer) { Sort(0, Count, comparer); } public virtual void Sort(int index, int count, IComparer comparer) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } System.Array.Sort((System.Array)_items, index, count, comparer); _version++; } public static System.Collections.IList Synchronized(System.Collections.IList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new SyncIList(list); } public static ArrayList Synchronized(ArrayList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new SyncArrayList(list); } public virtual object[] ToArray() { if (_size == 0) { return System.Array.Empty<object>(); } object[] array = new object[_size]; System.Array.Copy((System.Array)_items, 0, (System.Array)array, 0, _size); return array; } [SecuritySafeCritical] public virtual System.Array ToArray(System.Type type) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (type == null) { throw new ArgumentNullException("type"); } System.Array array = System.Array.CreateInstance(type, _size); System.Array.Copy((System.Array)_items, 0, array, 0, _size); return array; } public virtual void TrimToSize() { Capacity = _size; } } public class CaseInsensitiveComparer : IComparer { private CompareInfo _compareInfo; private static volatile CaseInsensitiveComparer s_InvariantCaseInsensitiveComparer; public static CaseInsensitiveComparer Default => new CaseInsensitiveComparer(CultureInfo.CurrentCulture); public static CaseInsensitiveComparer DefaultInvariant { get { if (s_InvariantCaseInsensitiveComparer == null) { s_InvariantCaseInsensitiveComparer = new CaseInsensitiveComparer(CultureInfo.InvariantCulture); } return s_InvariantCaseInsensitiveComparer; } } public CaseInsensitiveComparer() { _compareInfo = CultureInfo.CurrentCulture.CompareInfo; } public CaseInsensitiveComparer(CultureInfo culture) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (culture == null) { throw new ArgumentNullException("culture"); } _compareInfo = culture.CompareInfo; } public int Compare(object a, object b) { string text = a as string; string text2 = b as string; if (text != null && text2 != null) { return _compareInfo.Compare(text, text2, (CompareOptions)1); } return Comparer.Default.Compare(a, b); } } public abstract class CollectionBase : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private ArrayList _list; protected ArrayList InnerList => _list; protected System.Collections.IList List => this; public int Capacity { get { return InnerList.Capacity; } set { InnerList.Capacity = value; } } public int Count => _list.Count; bool System.Collections.IList.IsReadOnly => InnerList.IsReadOnly; bool System.Collections.IList.IsFixedSize => InnerList.IsFixedSize; bool System.Collections.ICollection.IsSynchronized => InnerList.IsSynchronized; object System.Collections.ICollection.SyncRoot => InnerList.SyncRoot; object System.Collections.IList.this[int index] { get { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } return InnerList[index]; } set { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } OnValidate(value); object obj = InnerList[index]; OnSet(index, obj, value); InnerList[index] = value; try { OnSetComplete(index, obj, value); } catch { InnerList[index] = obj; throw; } } } protected CollectionBase() { _list = new ArrayList(); } protected CollectionBase(int capacity) { _list = new ArrayList(capacity); } public void Clear() { OnClear(); InnerList.Clear(); OnClearComplete(); } public void RemoveAt(int index) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } object value = InnerList[index]; OnValidate(value); OnRemove(index, value); InnerList.RemoveAt(index); try { OnRemoveComplete(index, value); } catch { InnerList.Insert(index, value); throw; } } void System.Collections.ICollection.CopyTo(System.Array array, int index) { InnerList.CopyTo(array, index); } bool System.Collections.IList.Contains(object value) { return InnerList.Contains(value); } int System.Collections.IList.Add(object value) { OnValidate(value); OnInsert(InnerList.Count, value); int num = InnerList.Add(value); try { OnInsertComplete(num, value); return num; } catch { InnerList.RemoveAt(num); throw; } } void System.Collections.IList.Remove(object value) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) OnValidate(value); int num = InnerList.IndexOf(value); if (num < 0) { throw new ArgumentException(SR.Arg_RemoveArgNotFound); } OnRemove(num, value); InnerList.RemoveAt(num); try { OnRemoveComplete(num, value); } catch { InnerList.Insert(num, value); throw; } } int System.Collections.IList.IndexOf(object value) { return InnerList.IndexOf(value); } void System.Collections.IList.Insert(int index, object value) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index > Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } OnValidate(value); OnInsert(index, value); InnerList.Insert(index, value); try { OnInsertComplete(index, value); } catch { InnerList.RemoveAt(index); throw; } } public System.Collections.IEnumerator GetEnumerator() { return InnerList.GetEnumerator(); } protected virtual void OnSet(int index, object oldValue, object newValue) { } protected virtual void OnInsert(int index, object value) { } protected virtual void OnClear() { } protected virtual void OnRemove(int index, object value) { } protected virtual void OnValidate(object value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (value == null) { throw new ArgumentNullException("value"); } } protected virtual void OnSetComplete(int index, object oldValue, object newValue) { } protected virtual void OnInsertComplete(int index, object value) { } protected virtual void OnClearComplete() { } protected virtual void OnRemoveComplete(int index, object value) { } } public sealed class Comparer : IComparer { private CompareInfo _compareInfo; public static readonly Comparer Default = new Comparer(CultureInfo.CurrentCulture); public static readonly Comparer DefaultInvariant = new Comparer(CultureInfo.InvariantCulture); private const string CompareInfoName = "CompareInfo"; public Comparer(CultureInfo culture) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (culture == null) { throw new ArgumentNullException("culture"); } _compareInfo = culture.CompareInfo; } public int Compare(object a, object b) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) if (a == b) { return 0; } if (a == null) { return -1; } if (b == null) { return 1; } string text = a as string; string text2 = b as string; if (text != null && text2 != null) { return _compareInfo.Compare(text, text2); } IComparable val = (IComparable)((a is IComparable) ? a : null); if (val != null) { return val.CompareTo(b); } IComparable val2 = (IComparable)((b is IComparable) ? b : null); if (val2 != null) { return -val2.CompareTo(a); } throw new ArgumentException(SR.Argument_ImplementIComparable); } } public abstract class DictionaryBase : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private Hashtable _hashtable; protected Hashtable InnerHashtable { get { if (_hashtable == null) { _hashtable = new Hashtable(); } return _hashtable; } } protected IDictionary Dictionary => (IDictionary)(object)this; public int Count { get { if (_hashtable != null) { return _hashtable.Count; } return 0; } } bool IDictionary.IsReadOnly => InnerHashtable.IsReadOnly; bool IDictionary.IsFixedSize => InnerHashtable.IsFixedSize; bool System.Collections.ICollection.IsSynchronized => InnerHashtable.IsSynchronized; System.Collections.ICollection IDictionary.Keys => InnerHashtable.Keys; object System.Collections.ICollection.SyncRoot => InnerHashtable.SyncRoot; System.Collections.ICollection IDictionary.Values => InnerHashtable.Values; object IDictionary.this[object key] { get { object obj = InnerHashtable[key]; OnGet(key, obj); return obj; } set { OnValidate(key, value); bool flag = true; object obj = InnerHashtable[key]; if (obj == null) { flag = InnerHashtable.Contains(key); } OnSet(key, obj, value); InnerHashtable[key] = value; try { OnSetComplete(key, obj, value); } catch { if (flag) { InnerHashtable[key] = obj; } else { InnerHashtable.Remove(key); } throw; } } } public void CopyTo(System.Array array, int index) { InnerHashtable.CopyTo(array, index); } bool IDictionary.Contains(object key) { return InnerHashtable.Contains(key); } void IDictionary.Add(object key, object value) { OnValidate(key, value); OnInsert(key, value); InnerHashtable.Add(key, value); try { OnInsertComplete(key, value); } catch { InnerHashtable.Remove(key); throw; } } public void Clear() { OnClear(); InnerHashtable.Clear(); OnClearComplete(); } void IDictionary.Remove(object key) { if (InnerHashtable.Contains(key)) { object value = InnerHashtable[key]; OnValidate(key, value); OnRemove(key, value); InnerHashtable.Remove(key); try { OnRemoveComplete(key, value); } catch { InnerHashtable.Add(key, value); throw; } } } public IDictionaryEnumerator GetEnumerator() { return InnerHashtable.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)InnerHashtable.GetEnumerator(); } protected virtual object OnGet(object key, object currentValue) { return currentValue; } protected virtual void OnSet(object key, object oldValue, object newValue) { } protected virtual void OnInsert(object key, object value) { } protected virtual void OnClear() { } protected virtual void OnRemove(object key, object value) { } protected virtual void OnValidate(object key, object value) { } protected virtual void OnSetComplete(object key, object oldValue, object newValue) { } protected virtual void OnInsertComplete(object key, object value) { } protected virtual void OnClearComplete() { } protected virtual void OnRemoveComplete(object key, object value) { } } [DefaultMember("Item")] [DebuggerTypeProxy(typeof(HashtableDebugView))] [DebuggerDisplay("Count = {Count}")] public class Hashtable : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private struct bucket { public object key; public object val; public int hash_coll; } private class KeyCollection : System.Collections.ICollection, System.Collections.IEnumerable { private Hashtable _hashtable; public virtual bool IsSynchronized => _hashtable.IsSynchronized; public virtual object SyncRoot => _hashtable.SyncRoot; public virtual int Count => _hashtable._count; internal KeyCollection(Hashtable hashtable) { _hashtable = hashtable; } public virtual void CopyTo(System.Array array, int arrayIndex) { //IL_0008: 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_0035: 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 (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < _hashtable._count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } _hashtable.CopyKeys(array, arrayIndex); } public virtual System.Collections.IEnumerator GetEnumerator() { return new HashtableEnumerator(_hashtable, 1); } } private class ValueCollection : System.Collections.ICollection, System.Collections.IEnumerable { private Hashtable _hashtable; public virtual bool IsSynchronized => _hashtable.IsSynchronized; public virtual object SyncRoot => _hashtable.SyncRoot; public virtual int Count => _hashtable._count; internal ValueCollection(Hashtable hashtable) { _hashtable = hashtable; } public virtual void CopyTo(System.Array array, int arrayIndex) { //IL_0008: 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_0035: 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 (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < _hashtable._count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } _hashtable.CopyValues(array, arrayIndex); } public virtual System.Collections.IEnumerator GetEnumerator() { return new HashtableEnumerator(_hashtable, 2); } } [DefaultMember("Item")] private class SyncHashtable : Hashtable, System.Collections.IEnumerable { protected Hashtable _table; public override int Count => _table.Count; public override bool IsReadOnly => _table.IsReadOnly; public override bool IsFixedSize => _table.IsFixedSize; public override bool IsSynchronized => true; public override object this[object key] { get { return _table[key]; } set { lock (_table.SyncRoot) { _table[key] = value; } } } public override object SyncRoot => _table.SyncRoot; public override System.Collections.ICollection Keys { get { lock (_table.SyncRoot) { return _table.Keys; } } } public override System.Collections.ICollection Values { get { lock (_table.SyncRoot) { return _table.Values; } } } internal SyncHashtable(Hashtable table) : base(trash: false) { _table = table; } public override void Add(object key, object value) { lock (_table.SyncRoot) { _table.Add(key, value); } } public override void Clear() { lock (_table.SyncRoot) { _table.Clear(); } } public override bool Contains(object key) { return _table.Contains(key); } public override bool ContainsKey(object key) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key", SR.ArgumentNull_Key); } return _table.ContainsKey(key); } public override bool ContainsValue(object key) { lock (_table.SyncRoot) { return _table.ContainsValue(key); } } public override void CopyTo(System.Array array, int arrayIndex) { lock (_table.SyncRoot) { _table.CopyTo(array, arrayIndex); } } public override object Clone() { lock (_table.SyncRoot) { return Synchronized((Hashtable)_table.Clone()); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)_table.GetEnumerator(); } public override IDictionaryEnumerator GetEnumerator() { return _table.GetEnumerator(); } public override void Remove(object key) { lock (_table.SyncRoot) { _table.Remove(key); } } internal override KeyValuePairs[] ToKeyValuePairsArray() { return _table.ToKeyValuePairsArray(); } } private class HashtableEnumerator : IDictionaryEnumerator, System.Collections.IEnumerator { private Hashtable _hashtable; private int _bucket; private int _version; private bool _current; private int _getObjectRetType; private object _currentKey; private object _currentValue; internal const int Keys = 1; internal const int Values = 2; internal const int DictEntry = 3; public virtual object Key { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } return _currentKey; } } public virtual DictionaryEntry Entry { get { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(_currentKey, _currentValue); } } public virtual object Current { get { //IL_000d: 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) if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_getObjectRetType == 1) { return _currentKey; } if (_getObjectRetType == 2) { return _currentValue; } return (object)new DictionaryEntry(_currentKey, _currentValue); } } public virtual object Value { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) i
BepInEx/plugins/VNyanCommands/System.Collections.Specialized.dll
Decompiled 2 years agousing System; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using FxResources.System.Collections.Specialized; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Collections.Specialized")] [assembly: AssemblyDescription("System.Collections.Specialized")] [assembly: AssemblyDefaultAlias("System.Collections.Specialized")] [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.Collections.Specialized { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Collections.Specialized.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_AddingDuplicate => GetResourceString("Argument_AddingDuplicate", null); internal static string Argument_InvalidValue => GetResourceString("Argument_InvalidValue", null); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null); internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion", null); internal static string InvalidOperation_EnumOpCantHappen => GetResourceString("InvalidOperation_EnumOpCantHappen", null); internal static string Arg_MultiRank => GetResourceString("Arg_MultiRank", null); internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound", null); internal static string Arg_InsufficientSpace => GetResourceString("Arg_InsufficientSpace", null); internal static string CollectionReadOnly => GetResourceString("CollectionReadOnly", null); internal static string BitVectorFull => GetResourceString("BitVectorFull", null); internal static string OrderedDictionary_ReadOnly => GetResourceString("OrderedDictionary_ReadOnly", null); internal static System.Type ResourceType => typeof(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.Collections.Specialized { [DefaultMember("Item")] public struct BitVector32 { public struct Section { private readonly short _mask; private readonly short _offset; public short Mask => _mask; public short Offset => _offset; internal Section(short mask, short offset) { _mask = mask; _offset = offset; } public bool Equals(object o) { if (o is Section) { return Equals((Section)o); } return false; } public bool Equals(Section obj) { if (obj._mask == _mask) { return obj._offset == _offset; } return false; } public static bool operator ==(Section a, Section b) { return a.Equals(b); } public static bool operator !=(Section a, Section b) { return !(a == b); } public int GetHashCode() { return base.GetHashCode(); } public static string ToString(Section value) { return string.Concat(new string[5] { "Section{0x", Convert.ToString(value.Mask, 16), ", 0x", Convert.ToString(value.Offset, 16), "}" }); } public string ToString() { return ToString(this); } } private uint _data; public bool this[int bit] { get { return (_data & bit) == (uint)bit; } set { if (value) { _data |= (uint)bit; } else { _data &= (uint)(~bit); } } } public int this[Section section] { get { return (int)((_data & (uint)(section.Mask << (int)section.Offset)) >> (int)section.Offset); } set { value <<= (int)section.Offset; int num = (0xFFFF & section.Mask) << (int)section.Offset; _data = (_data & (uint)(~num)) | (uint)(value & num); } } public int Data => (int)_data; public BitVector32(int data) { _data = (uint)data; } public BitVector32(BitVector32 value) { _data = value._data; } private static short CountBitsSet(short mask) { short num = 0; while (((uint)mask & (true ? 1u : 0u)) != 0) { num++; mask >>= 1; } return num; } public static int CreateMask() { return CreateMask(0); } public static int CreateMask(int previous) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return previous switch { 0 => 1, -2147483648 => throw new InvalidOperationException(System.SR.BitVectorFull), _ => previous << 1, }; } private static short CreateMaskFromHighValue(short highValue) { short num = 16; while ((highValue & 0x8000) == 0) { num--; highValue <<= 1; } ushort num2 = 0; while (num > 0) { num--; num2 <<= 1; num2 = (ushort)(num2 | 1u); } return (short)num2; } public static Section CreateSection(short maxValue) { return CreateSectionHelper(maxValue, 0, 0); } public static Section CreateSection(short maxValue, Section previous) { return CreateSectionHelper(maxValue, previous.Mask, previous.Offset); } private static Section CreateSectionHelper(short maxValue, short priorMask, short priorOffset) { //IL_001e: 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 (maxValue < 1) { throw new ArgumentException(System.SR.Format(System.SR.Argument_InvalidValue, "maxValue", 1), "maxValue"); } short num = (short)(priorOffset + CountBitsSet(priorMask)); if (num >= 32) { throw new InvalidOperationException(System.SR.BitVectorFull); } return new Section(CreateMaskFromHighValue(maxValue), num); } public bool Equals(object o) { if (!(o is BitVector32)) { return false; } return _data == ((BitVector32)o)._data; } public int GetHashCode() { return base.GetHashCode(); } public static string ToString(BitVector32 value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown StringBuilder val = new StringBuilder(45); val.Append("BitVector32{"); int num = (int)value._data; for (int i = 0; i < 32; i++) { if ((num & 0x80000000u) != 0L) { val.Append('1'); } else { val.Append('0'); } num <<= 1; } val.Append('}'); return ((object)val).ToString(); } public string ToString() { return ToString(this); } } [DefaultMember("Item")] public class HybridDictionary : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private const int CutoverPoint = 9; private const int InitialHashtableSize = 13; private const int FixedSizeCutoverPoint = 6; private ListDictionary _list; private Hashtable _hashtable; private readonly bool _caseInsensitive; public object this[object key] { get { //IL_002f: Unknown result type (might be due to invalid IL or missing references) ListDictionary list = _list; if (_hashtable != null) { return _hashtable[key]; } if (list != null) { return list[key]; } if (key == null) { throw new ArgumentNullException("key"); } return null; } set { if (_hashtable != null) { _hashtable[key] = value; } else if (_list != null) { if (_list.Count >= 8) { ChangeOver(); _hashtable[key] = value; } else { _list[key] = value; } } else { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); _list[key] = value; } } } private ListDictionary List { get { if (_list == null) { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); } return _list; } } public int Count { get { ListDictionary list = _list; if (_hashtable != null) { return _hashtable.Count; } return list?.Count ?? 0; } } public System.Collections.ICollection Keys { get { if (_hashtable != null) { return _hashtable.Keys; } return List.Keys; } } public bool IsReadOnly => false; public bool IsFixedSize => false; public bool IsSynchronized => false; public object SyncRoot => this; public System.Collections.ICollection Values { get { if (_hashtable != null) { return _hashtable.Values; } return List.Values; } } public HybridDictionary() { } public HybridDictionary(int initialSize) : this(initialSize, caseInsensitive: false) { } public HybridDictionary(bool caseInsensitive) { _caseInsensitive = caseInsensitive; } public HybridDictionary(int initialSize, bool caseInsensitive) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown _caseInsensitive = caseInsensitive; if (initialSize >= 6) { if (caseInsensitive) { _hashtable = new Hashtable(initialSize, (IEqualityComparer)(object)StringComparer.OrdinalIgnoreCase); } else { _hashtable = new Hashtable(initialSize); } } } private void ChangeOver() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown IDictionaryEnumerator enumerator = _list.GetEnumerator(); Hashtable val = ((!_caseInsensitive) ? new Hashtable(13) : new Hashtable(13, (IEqualityComparer)(object)StringComparer.OrdinalIgnoreCase)); while (((System.Collections.IEnumerator)enumerator).MoveNext()) { val.Add(enumerator.Key, enumerator.Value); } _hashtable = val; _list = null; } public void Add(object key, object value) { if (_hashtable != null) { _hashtable.Add(key, value); } else if (_list == null) { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); _list.Add(key, value); } else if (_list.Count + 1 >= 9) { ChangeOver(); _hashtable.Add(key, value); } else { _list.Add(key, value); } } public void Clear() { if (_hashtable != null) { Hashtable hashtable = _hashtable; _hashtable = null; hashtable.Clear(); } if (_list != null) { ListDictionary list = _list; _list = null; list.Clear(); } } public bool Contains(object key) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) ListDictionary list = _list; if (_hashtable != null) { return _hashtable.Contains(key); } if (list != null) { return list.Contains(key); } if (key == null) { throw new ArgumentNullException("key"); } return false; } public void CopyTo(System.Array array, int index) { if (_hashtable != null) { _hashtable.CopyTo(array, index); } else { List.CopyTo(array, index); } } public IDictionaryEnumerator GetEnumerator() { if (_hashtable != null) { return _hashtable.GetEnumerator(); } if (_list == null) { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); } return _list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { if (_hashtable != null) { return (System.Collections.IEnumerator)_hashtable.GetEnumerator(); } if (_list == null) { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); } return (System.Collections.IEnumerator)_list.GetEnumerator(); } public void Remove(object key) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (_hashtable != null) { _hashtable.Remove(key); } else if (_list != null) { _list.Remove(key); } else if (key == null) { throw new ArgumentNullException("key"); } } } [DefaultMember("Item")] public interface IOrderedDictionary : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { object this[int index] { get; set; } IDictionaryEnumerator GetEnumerator(); void Insert(int index, object key, object value); void RemoveAt(int index); } [DefaultMember("Item")] public class ListDictionary : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private class NodeEnumerator : IDictionaryEnumerator, System.Collections.IEnumerator { private ListDictionary _list; private DictionaryNode _current; private int _version; private bool _start; public object Current => Entry; public DictionaryEntry Entry { get { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_current == null) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(_current.key, _current.value); } } public object Key { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_current == null) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } return _current.key; } } public object Value { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_current == null) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } return _current.value; } } public NodeEnumerator(ListDictionary list) { _list = list; _version = list._version; _start = true; _current = null; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } if (_start) { _current = _list._head; _start = false; } else if (_current != null) { _current = _current.next; } return _current != null; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } _start = true; _current = null; } } private class NodeKeyValueCollection : System.Collections.ICollection, System.Collections.IEnumerable { private class NodeKeyValueEnumerator : System.Collections.IEnumerator { private ListDictionary _list; private DictionaryNode _current; private int _version; private bool _isKeys; private bool _start; public object Current { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_current == null) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } if (!_isKeys) { return _current.value; } return _current.key; } } public NodeKeyValueEnumerator(ListDictionary list, bool isKeys) { _list = list; _isKeys = isKeys; _version = list._version; _start = true; _current = null; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } if (_start) { _current = _list._head; _start = false; } else if (_current != null) { _current = _current.next; } return _current != null; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } _start = true; _current = null; } } private ListDictionary _list; private bool _isKeys; int System.Collections.ICollection.Count { get { int num = 0; for (DictionaryNode dictionaryNode = _list._head; dictionaryNode != null; dictionaryNode = dictionaryNode.next) { num++; } return num; } } bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => _list.SyncRoot; public NodeKeyValueCollection(ListDictionary list, bool isKeys) { _list = list; _isKeys = isKeys; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { //IL_0008: 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) if (array == null) { throw new ArgumentNullException("array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } for (DictionaryNode dictionaryNode = _list._head; dictionaryNode != null; dictionaryNode = dictionaryNode.next) { array.SetValue(_isKeys ? dictionaryNode.key : dictionaryNode.value, index); index++; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new NodeKeyValueEnumerator(_list, _isKeys); } } private class DictionaryNode { public object key; public object value; public DictionaryNode next; } private DictionaryNode _head; private int _version; private int _count; private readonly IComparer _comparer; private object _syncRoot; public object this[object key] { get { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } DictionaryNode dictionaryNode = _head; if (_comparer == null) { while (dictionaryNode != null) { object key2 = dictionaryNode.key; if (key2.Equals(key)) { return dictionaryNode.value; } dictionaryNode = dictionaryNode.next; } } else { while (dictionaryNode != null) { object key3 = dictionaryNode.key; if (_comparer.Compare(key3, key) == 0) { return dictionaryNode.value; } dictionaryNode = dictionaryNode.next; } } return null; } set { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _version++; DictionaryNode dictionaryNode = null; DictionaryNode dictionaryNode2; for (dictionaryNode2 = _head; dictionaryNode2 != null; dictionaryNode2 = dictionaryNode2.next) { object key2 = dictionaryNode2.key; if ((_comparer == null) ? key2.Equals(key) : (_comparer.Compare(key2, key) == 0)) { break; } dictionaryNode = dictionaryNode2; } if (dictionaryNode2 != null) { dictionaryNode2.value = value; return; } DictionaryNode dictionaryNode3 = new DictionaryNode(); dictionaryNode3.key = key; dictionaryNode3.value = value; if (dictionaryNode != null) { dictionaryNode.next = dictionaryNode3; } else { _head = dictionaryNode3; } _count++; } } public int Count => _count; public System.Collections.ICollection Keys => new NodeKeyValueCollection(this, isKeys: true); public bool IsReadOnly => false; public bool IsFixedSize => false; public bool IsSynchronized => false; public object SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); } return _syncRoot; } } public System.Collections.ICollection Values => new NodeKeyValueCollection(this, isKeys: false); public ListDictionary() { } public ListDictionary(IComparer comparer) { _comparer = comparer; } public void Add(object key, object value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _version++; DictionaryNode dictionaryNode = null; for (DictionaryNode dictionaryNode2 = _head; dictionaryNode2 != null; dictionaryNode2 = dictionaryNode2.next) { object key2 = dictionaryNode2.key; if ((_comparer == null) ? key2.Equals(key) : (_comparer.Compare(key2, key) == 0)) { throw new ArgumentException(System.SR.Format(System.SR.Argument_AddingDuplicate, key)); } dictionaryNode = dictionaryNode2; } DictionaryNode dictionaryNode3 = new DictionaryNode(); dictionaryNode3.key = key; dictionaryNode3.value = value; if (dictionaryNode != null) { dictionaryNode.next = dictionaryNode3; } else { _head = dictionaryNode3; } _count++; } public void Clear() { _count = 0; _head = null; _version++; } public bool Contains(object key) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } for (DictionaryNode dictionaryNode = _head; dictionaryNode != null; dictionaryNode = dictionaryNode.next) { object key2 = dictionaryNode.key; if ((_comparer == null) ? key2.Equals(key) : (_comparer.Compare(key2, key) == 0)) { return true; } } return false; } public void CopyTo(System.Array array, int index) { //IL_0008: 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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _count) { throw new ArgumentException(System.SR.Arg_InsufficientSpace); } for (DictionaryNode dictionaryNode = _head; dictionaryNode != null; dictionaryNode = dictionaryNode.next) { array.SetValue((object)new DictionaryEntry(dictionaryNode.key, dictionaryNode.value), index); index++; } } public IDictionaryEnumerator GetEnumerator() { return (IDictionaryEnumerator)(object)new NodeEnumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new NodeEnumerator(this); } public void Remove(object key) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _version++; DictionaryNode dictionaryNode = null; DictionaryNode dictionaryNode2; for (dictionaryNode2 = _head; dictionaryNode2 != null; dictionaryNode2 = dictionaryNode2.next) { object key2 = dictionaryNode2.key; if ((_comparer == null) ? key2.Equals(key) : (_comparer.Compare(key2, key) == 0)) { break; } dictionaryNode = dictionaryNode2; } if (dictionaryNode2 != null) { if (dictionaryNode2 == _head) { _head = dictionaryNode2.next; } else { dictionaryNode.next = dictionaryNode2.next; } _count--; } } } public abstract class NameObjectCollectionBase : System.Collections.ICollection, System.Collections.IEnumerable { internal class NameObjectEntry { internal string Key; internal object Value; internal NameObjectEntry(string name, object value) { Key = name; Value = value; } } internal class NameObjectKeysEnumerator : System.Collections.IEnumerator { private int _pos; private NameObjectCollectionBase _coll; private int _version; public object Current { get { //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (_pos >= 0 && _pos < _coll.Count) { return _coll.BaseGetKey(_pos); } throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } } internal NameObjectKeysEnumerator(NameObjectCollectionBase coll) { _coll = coll; _version = _coll._version; _pos = -1; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _coll._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } if (_pos < _coll.Count - 1) { _pos++; return true; } _pos = _coll.Count; return false; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _coll._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } _pos = -1; } } [DefaultMember("Item")] public class KeysCollection : System.Collections.ICollection, System.Collections.IEnumerable { private NameObjectCollectionBase _coll; public string this[int index] => Get(index); public int Count => _coll.Count; object System.Collections.ICollection.SyncRoot => ((System.Collections.ICollection)_coll).SyncRoot; bool System.Collections.ICollection.IsSynchronized => false; internal KeysCollection(NameObjectCollectionBase coll) { _coll = coll; } public virtual string Get(int index) { return _coll.BaseGetKey(index); } public System.Collections.IEnumerator GetEnumerator() { return new NameObjectKeysEnumerator(_coll); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { //IL_0008: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(System.SR.Arg_MultiRank, "array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _coll.Count) { throw new ArgumentException(System.SR.Arg_InsufficientSpace); } System.Collections.IEnumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { array.SetValue(enumerator.Current, index++); } } } private bool _readOnly; private ArrayList _entriesArray; private IEqualityComparer _keyComparer; private volatile Hashtable _entriesTable; private volatile NameObjectEntry _nullKeyEntry; private KeysCollection _keys; private int _version; private object _syncRoot; private static readonly StringComparer s_defaultComparer = GlobalizationExtensions.GetStringComparer(CultureInfo.InvariantCulture.CompareInfo, (CompareOptions)1); internal IEqualityComparer Comparer { get { return _keyComparer; } set { _keyComparer = value; } } protected bool IsReadOnly { get { return _readOnly; } set { _readOnly = value; } } public virtual int Count => _entriesArray.Count; object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); } return _syncRoot; } } bool System.Collections.ICollection.IsSynchronized => false; public virtual KeysCollection Keys { get { if (_keys == null) { _keys = new KeysCollection(this); } return _keys; } } protected NameObjectCollectionBase() : this((IEqualityComparer)(object)s_defaultComparer) { } protected NameObjectCollectionBase(IEqualityComparer equalityComparer) { IEqualityComparer keyComparer; if (equalityComparer != null) { keyComparer = equalityComparer; } else { IEqualityComparer val = (IEqualityComparer)(object)s_defaultComparer; keyComparer = val; } _keyComparer = keyComparer; Reset(); } protected NameObjectCollectionBase(int capacity, IEqualityComparer equalityComparer) : this(equalityComparer) { Reset(capacity); } protected NameObjectCollectionBase(int capacity) { _keyComparer = (IEqualityComparer)(object)s_defaultComparer; Reset(capacity); } private void Reset() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown _entriesArray = new ArrayList(); _entriesTable = new Hashtable(_keyComparer); _nullKeyEntry = null; _version++; } private void Reset(int capacity) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown _entriesArray = new ArrayList(capacity); _entriesTable = new Hashtable(capacity, _keyComparer); _nullKeyEntry = null; _version++; } private NameObjectEntry FindEntry(string key) { if (key != null) { return (NameObjectEntry)_entriesTable[(object)key]; } return _nullKeyEntry; } protected bool BaseHasKeys() { return _entriesTable.Count > 0; } protected void BaseAdd(string name, object value) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } NameObjectEntry nameObjectEntry = new NameObjectEntry(name, value); if (name != null) { if (_entriesTable[(object)name] == null) { _entriesTable.Add((object)name, (object)nameObjectEntry); } } else if (_nullKeyEntry == null) { _nullKeyEntry = nameObjectEntry; } _entriesArray.Add((object)nameObjectEntry); _version++; } protected void BaseRemove(string name) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } if (name != null) { _entriesTable.Remove((object)name); for (int num = _entriesArray.Count - 1; num >= 0; num--) { if (_keyComparer.Equals((object)name, (object)BaseGetKey(num))) { _entriesArray.RemoveAt(num); } } } else { _nullKeyEntry = null; for (int num2 = _entriesArray.Count - 1; num2 >= 0; num2--) { if (BaseGetKey(num2) == null) { _entriesArray.RemoveAt(num2); } } } _version++; } protected void BaseRemoveAt(int index) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } string text = BaseGetKey(index); if (text != null) { _entriesTable.Remove((object)text); } else { _nullKeyEntry = null; } _entriesArray.RemoveAt(index); _version++; } protected void BaseClear() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } Reset(); } protected object BaseGet(string name) { return FindEntry(name)?.Value; } protected void BaseSet(string name, object value) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } NameObjectEntry nameObjectEntry = FindEntry(name); if (nameObjectEntry != null) { nameObjectEntry.Value = value; _version++; } else { BaseAdd(name, value); } } protected object BaseGet(int index) { NameObjectEntry nameObjectEntry = (NameObjectEntry)_entriesArray[index]; return nameObjectEntry.Value; } protected string BaseGetKey(int index) { NameObjectEntry nameObjectEntry = (NameObjectEntry)_entriesArray[index]; return nameObjectEntry.Key; } protected void BaseSet(int index, object value) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } NameObjectEntry nameObjectEntry = (NameObjectEntry)_entriesArray[index]; nameObjectEntry.Value = value; _version++; } public virtual System.Collections.IEnumerator GetEnumerator() { return new NameObjectKeysEnumerator(this); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { //IL_0008: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(System.SR.Arg_MultiRank, "array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _entriesArray.Count) { throw new ArgumentException(System.SR.Arg_InsufficientSpace); } System.Collections.IEnumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { array.SetValue(enumerator.Current, index++); } } protected string[] BaseGetAllKeys() { int count = _entriesArray.Count; string[] array = new string[count]; for (int i = 0; i < count; i++) { array[i] = BaseGetKey(i); } return array; } protected object[] BaseGetAllValues() { int count = _entriesArray.Count; object[] array = new object[count]; for (int i = 0; i < count; i++) { array[i] = BaseGet(i); } return array; } protected object[] BaseGetAllValues(System.Type type) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) int count = _entriesArray.Count; if (type == null) { throw new ArgumentNullException("type"); } object[] array = (object[])System.Array.CreateInstance(type, count); for (int i = 0; i < count; i++) { array[i] = BaseGet(i); } return array; } } [DefaultMember("Item")] public class NameValueCollection : NameObjectCollectionBase { private string[] _all; private string[] _allKeys; public string this[string name] { get { return Get(name); } set { Set(name, value); } } public string this[int index] => Get(index); public virtual string[] AllKeys { get { if (_allKeys == null) { _allKeys = BaseGetAllKeys(); } return _allKeys; } } public NameValueCollection() { } public NameValueCollection(NameValueCollection col) : base(col?.Comparer) { Add(col); } public NameValueCollection(int capacity) : base(capacity) { } public NameValueCollection(IEqualityComparer equalityComparer) : base(equalityComparer) { } public NameValueCollection(int capacity, IEqualityComparer equalityComparer) : base(capacity, equalityComparer) { } public NameValueCollection(int capacity, NameValueCollection col) : base(capacity, col?.Comparer) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (col == null) { throw new ArgumentNullException("col"); } base.Comparer = col.Comparer; Add(col); } protected void InvalidateCachedArrays() { _all = null; _allKeys = null; } private static string GetAsOneString(ArrayList list) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown int num = ((list != null) ? list.Count : 0); if (num == 1) { return (string)list[0]; } if (num > 1) { StringBuilder val = new StringBuilder((string)list[0]); for (int i = 1; i < num; i++) { val.Append(','); val.Append((string)list[i]); } return ((object)val).ToString(); } return null; } private static string[] GetAsStringArray(ArrayList list) { int num = ((list != null) ? list.Count : 0); if (num == 0) { return null; } string[] array = new string[num]; list.CopyTo(0, (System.Array)array, 0, num); return array; } public void Add(NameValueCollection c) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c"); } InvalidateCachedArrays(); int count = c.Count; for (int i = 0; i < count; i++) { string key = c.GetKey(i); string[] values = c.GetValues(i); if (values != null) { for (int j = 0; j < values.Length; j++) { Add(key, values[j]); } } else { Add(key, null); } } } public virtual void Clear() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (base.IsReadOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } InvalidateCachedArrays(); BaseClear(); } public void CopyTo(System.Array dest, int index) { //IL_0008: 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_003b: 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) if (dest == null) { throw new ArgumentNullException("dest"); } if (dest.Rank != 1) { throw new ArgumentException(System.SR.Arg_MultiRank, "dest"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (dest.Length - index < Count) { throw new ArgumentException(System.SR.Arg_InsufficientSpace); } int count = Count; if (_all == null) { string[] array = new string[count]; for (int i = 0; i < count; i++) { array[i] = Get(i); dest.SetValue((object)array[i], i + index); } _all = array; } else { for (int j = 0; j < count; j++) { dest.SetValue((object)_all[j], j + index); } } } public bool HasKeys() { return InternalHasKeys(); } internal virtual bool InternalHasKeys() { return BaseHasKeys(); } public virtual void Add(string name, string value) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_000d: 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_0030: Expected O, but got Unknown if (base.IsReadOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } InvalidateCachedArrays(); ArrayList val = (ArrayList)BaseGet(name); if (val == null) { val = new ArrayList(1); if (value != null) { val.Add((object)value); } BaseAdd(name, val); } else if (value != null) { val.Add((object)value); } } public virtual string Get(string name) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ArrayList list = (ArrayList)BaseGet(name); return GetAsOneString(list); } public virtual string[] GetValues(string name) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ArrayList list = (ArrayList)BaseGet(name); return GetAsStringArray(list); } public virtual void Set(string name, string value) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (base.IsReadOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } InvalidateCachedArrays(); ArrayList val = new ArrayList(1); val.Add((object)value); BaseSet(name, val); } public virtual void Remove(string name) { InvalidateCachedArrays(); BaseRemove(name); } public virtual string Get(int index) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ArrayList list = (ArrayList)BaseGet(index); return GetAsOneString(list); } public virtual string[] GetValues(int index) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ArrayList list = (ArrayList)BaseGet(index); return GetAsStringArray(list); } public virtual string GetKey(int index) { return BaseGetKey(index); } } [DefaultMember("Item")] public class OrderedDictionary : IOrderedDictionary, IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private class OrderedDictionaryEnumerator : IDictionaryEnumerator, System.Collections.IEnumerator { private int _objectReturnType; internal const int Keys = 1; internal const int Values = 2; internal const int DictionaryEntry = 3; private System.Collections.IEnumerator _arrayEnumerator; public object Current { get { //IL_0014: 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_0045: 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_003b: Unknown result type (might be due to invalid IL or missing references) DictionaryEntry val; if (_objectReturnType == 1) { val = (DictionaryEntry)_arrayEnumerator.Current; return ((DictionaryEntry)(ref val)).Key; } if (_objectReturnType == 2) { val = (DictionaryEntry)_arrayEnumerator.Current; return ((DictionaryEntry)(ref val)).Value; } return Entry; } } public DictionaryEntry Entry { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //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) //IL_0028: 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) DictionaryEntry val = (DictionaryEntry)_arrayEnumerator.Current; object key = ((DictionaryEntry)(ref val)).Key; val = (DictionaryEntry)_arrayEnumerator.Current; return new DictionaryEntry(key, ((DictionaryEntry)(ref val)).Value); } } public object Key { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) DictionaryEntry val = (DictionaryEntry)_arrayEnumerator.Current; return ((DictionaryEntry)(ref val)).Key; } } public object Value { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) DictionaryEntry val = (DictionaryEntry)_arrayEnumerator.Current; return ((DictionaryEntry)(ref val)).Value; } } internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType) { _arrayEnumerator = array.GetEnumerator(); _objectReturnType = objectReturnType; } public bool MoveNext() { return _arrayEnumerator.MoveNext(); } public void Reset() { _arrayEnumerator.Reset(); } } private class OrderedDictionaryKeyValueCollection : System.Collections.ICollection, System.Collections.IEnumerable { private ArrayList _objects; private bool _isKeys; int System.Collections.ICollection.Count => _objects.Count; bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => _objects.SyncRoot; public OrderedDictionaryKeyValueCollection(ArrayList array, bool isKeys) { _objects = array; _isKeys = isKeys; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { //IL_0008: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: 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_004c: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } foreach (object @object in _objects) { DictionaryEntry val; object obj; if (!_isKeys) { val = (DictionaryEntry)@object; obj = ((DictionaryEntry)(ref val)).Value; } else { val = (DictionaryEntry)@object; obj = ((DictionaryEntry)(ref val)).Key; } array.SetValue(obj, index); index++; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new OrderedDictionaryEnumerator(_objects, _isKeys ? 1 : 2); } } private ArrayList _objectsArray; private Hashtable _objectsTable; private readonly int _initialCapacity; private readonly IEqualityComparer _comparer; private readonly bool _readOnly; private object _syncRoot; public int Count => objectsArray.Count; bool IDictionary.IsFixedSize => _readOnly; public bool IsReadOnly => _readOnly; bool System.Collections.ICollection.IsSynchronized => false; public System.Collections.ICollection Keys => new OrderedDictionaryKeyValueCollection(objectsArray, isKeys: true); private ArrayList objectsArray { get { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown if (_objectsArray == null) { _objectsArray = new ArrayList(_initialCapacity); } return _objectsArray; } } private Hashtable objectsTable { get { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (_objectsTable == null) { _objectsTable = new Hashtable(_initialCapacity, _comparer); } return _objectsTable; } } object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); } return _syncRoot; } } public object this[int index] { get { //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) DictionaryEntry val = (DictionaryEntry)objectsArray[index]; return ((DictionaryEntry)(ref val)).Value; } set { //IL_000d: 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_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_0053: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (index < 0 || index >= objectsArray.Count) { throw new ArgumentOutOfRangeException("index"); } DictionaryEntry val = (DictionaryEntry)objectsArray[index]; object key = ((DictionaryEntry)(ref val)).Key; objectsArray[index] = (object)new DictionaryEntry(key, value); objectsTable[key] = value; } } public object this[object key] { get { return objectsTable[key]; } set { //IL_000d: 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 (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (objectsTable.Contains(key)) { objectsTable[key] = value; objectsArray[IndexOfKey(key)] = (object)new DictionaryEntry(key, value); } else { Add(key, value); } } } public System.Collections.ICollection Values => new OrderedDictionaryKeyValueCollection(objectsArray, isKeys: false); public OrderedDictionary() : this(0) { } public OrderedDictionary(int capacity) : this(capacity, null) { } public OrderedDictionary(IEqualityComparer comparer) : this(0, comparer) { } public OrderedDictionary(int capacity, IEqualityComparer comparer) { _initialCapacity = capacity; _comparer = comparer; } private OrderedDictionary(OrderedDictionary dictionary) { _readOnly = true; _objectsArray = dictionary._objectsArray; _objectsTable = dictionary._objectsTable; _comparer = dictionary._comparer; _initialCapacity = dictionary._initialCapacity; } public void Add(object key, object value) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } objectsTable.Add(key, value); objectsArray.Add((object)new DictionaryEntry(key, value)); } public void Clear() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } objectsTable.Clear(); objectsArray.Clear(); } public OrderedDictionary AsReadOnly() { return new OrderedDictionary(this); } public bool Contains(object key) { return objectsTable.Contains(key); } public void CopyTo(System.Array array, int index) { objectsTable.CopyTo(array, index); } private int IndexOfKey(object key) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < objectsArray.Count; i++) { DictionaryEntry val = (DictionaryEntry)objectsArray[i]; object key2 = ((DictionaryEntry)(ref val)).Key; if (_comparer != null) { if (_comparer.Equals(key2, key)) { return i; } } else if (key2.Equals(key)) { return i; } } return -1; } public void Insert(int index, object key, object value) { //IL_000d: 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_0041: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (index > Count || index < 0) { throw new ArgumentOutOfRangeException("index"); } objectsTable.Add(key, value); objectsArray.Insert(index, (object)new DictionaryEntry(key, value)); } public void RemoveAt(int index) { //IL_000d: 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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (index >= Count || index < 0) { throw new ArgumentOutOfRangeException("index"); } DictionaryEntry val = (DictionaryEntry)objectsArray[index]; object key = ((DictionaryEntry)(ref val)).Key; objectsArray.RemoveAt(index); objectsTable.Remove(key); } public void Remove(object key) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (key == null) { throw new ArgumentNullException("key"); } int num = IndexOfKey(key); if (num >= 0) { objectsTable.Remove(key); objectsArray.RemoveAt(num); } } public virtual IDictionaryEnumerator GetEnumerator() { return (IDictionaryEnumerator)(object)new OrderedDictionaryEnumerator(objectsArray, 3); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new OrderedDictionaryEnumerator(objectsArray, 3); } } [DefaultMember("Item")] public class StringCollection : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private readonly ArrayList _data = new ArrayList(); public string this[int index] { get { return (string)_data[index]; } set { _data[index] = value; } } public int Count => _data.Count; bool System.Collections.IList.IsReadOnly => false; bool System.Collections.IList.IsFixedSize => false; public bool IsReadOnly => false; public bool IsSynchronized => false; public object SyncRoot => _data.SyncRoot; object System.Collections.IList.this[int index] { get { return this[index]; } set { this[index] = (string)value; } } public int Add(string value) { return _data.Add((object)value); } public void AddRange(string[] value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (value == null) { throw new ArgumentNullException("value"); } _data.AddRange((System.Collections.ICollection)(object)value); } public void Clear() { _data.Clear(); } public bool Contains(string value) { return _data.Contains((object)value); } public void CopyTo(string[] array, int index) { _data.CopyTo((System.Array)array, index); } public StringEnumerator GetEnumerator() { return new StringEnumerator(this); } public int IndexOf(string value) { return _data.IndexOf((object)value); } public void Insert(int index, string value) { _data.Insert(index, (object)value); } public void Remove(string value) { _data.Remove((object)value); } public void RemoveAt(int index) { _data.RemoveAt(index); } int System.Collections.IList.Add(object value) { return Add((string)value); } bool System.Collections.IList.Contains(object value) { return Contains((string)value); } int System.Collections.IList.IndexOf(object value) { return IndexOf((string)value); } void System.Collections.IList.Insert(int index, object value) { Insert(index, (string)value); } void System.Collections.IList.Remove(object value) { Remove((string)value); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { _data.CopyTo(array, index); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _data.GetEnumerator(); } } public class StringEnumerator { private System.Collections.IEnumerator _baseEnumerator; private System.Collections.IEnumerable _temp; public string Current => (string)_baseEnumerator.Current; internal StringEnumerator(StringCollection mappings) { _temp = mappings; _baseEnumerator = _temp.GetEnumerator(); } public bool MoveNext() { return _baseEnumerator.MoveNext(); } public void Reset() { _baseEnumerator.Reset(); } } [DefaultMember("Item")] public class StringDictionary : System.Collections.IEnumerable { private readonly Hashtable _contents = new Hashtable(); public virtual int Count => _contents.Count; public virtual bool IsSynchronized => _contents.IsSynchronized; public virtual string this[string key] { get { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } return (string)_contents[(object)key.ToLowerInvariant()]; } set { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _contents[(object)key.ToLowerInvariant()] = value; } } public virtual System.Collections.ICollection Keys => _contents.Keys; public virtual object SyncRoot => _contents.SyncRoot; public virtual System.Collections.ICollection Values => _contents.Values; public virtual void Add(string key, string value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _contents.Add((object)key.ToLowerInvariant(), (object)value); } public virtual void Clear() { _contents.Clear(); } public virtual bool ContainsKey(string key) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } return _contents.ContainsKey((object)key.ToLowerInvariant()); } public virtual bool ContainsValue(string value) { return _contents.ContainsValue((object)value); } public virtual void CopyTo(System.Array array, int index) { _contents.CopyTo(array, index); } public virtual System.Collections.IEnumerator GetEnumerator() { return (System.Collections.IEnumerator)_contents.GetEnumerator(); } public virtual void Remove(string key) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _contents.Remove((object)key.ToLowerInvariant()); } } }
BepInEx/plugins/VNyanCommands/System.ComponentModel.dll
Decompiled 2 years agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: AssemblyTitle("System.ComponentModel")] [assembly: AssemblyDescription("System.ComponentModel")] [assembly: AssemblyDefaultAlias("System.ComponentModel")] [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 System { public interface IServiceProvider { object GetService(System.Type serviceType); } } namespace System.ComponentModel { public class CancelEventArgs : EventArgs { [field: CompilerGenerated] public bool Cancel { [CompilerGenerated] get; [CompilerGenerated] set; } public CancelEventArgs() { } public CancelEventArgs(bool cancel) { Cancel = cancel; } } public interface IChangeTracking { bool IsChanged { get; } void AcceptChanges(); } public interface IEditableObject { void BeginEdit(); void EndEdit(); void CancelEdit(); } public interface IRevertibleChangeTracking : IChangeTracking { void RejectChanges(); } }
BepInEx/plugins/VNyanCommands/System.ComponentModel.Primitives.dll
Decompiled 2 years agousing System; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using FxResources.System.ComponentModel.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.ComponentModel.Primitives")] [assembly: AssemblyDescription("System.ComponentModel.Primitives")] [assembly: AssemblyDefaultAlias("System.ComponentModel.Primitives")] [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.1.1.0")] namespace FxResources.System.ComponentModel.Primitives { internal static class SR : Object { } } namespace System { internal static class SR : Object { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.ComponentModel.Primitives.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 PropertyCategoryAction => GetResourceString("PropertyCategoryAction", null); internal static string PropertyCategoryAppearance => GetResourceString("PropertyCategoryAppearance", null); internal static string PropertyCategoryAsynchronous => GetResourceString("PropertyCategoryAsynchronous", null); internal static string PropertyCategoryBehavior => GetResourceString("PropertyCategoryBehavior", null); internal static string PropertyCategoryConfig => GetResourceString("PropertyCategoryConfig", null); internal static string PropertyCategoryData => GetResourceString("PropertyCategoryData", null); internal static string PropertyCategoryDDE => GetResourceString("PropertyCategoryDDE", null); internal static string PropertyCategoryDefault => GetResourceString("PropertyCategoryDefault", null); internal static string PropertyCategoryDesign => GetResourceString("PropertyCategoryDesign", null); internal static string PropertyCategoryDragDrop => GetResourceString("PropertyCategoryDragDrop", null); internal static string PropertyCategoryFocus => GetResourceString("PropertyCategoryFocus", null); internal static string PropertyCategoryFont => GetResourceString("PropertyCategoryFont", null); internal static string PropertyCategoryFormat => GetResourceString("PropertyCategoryFormat", null); internal static string PropertyCategoryKey => GetResourceString("PropertyCategoryKey", null); internal static string PropertyCategoryLayout => GetResourceString("PropertyCategoryLayout", null); internal static string PropertyCategoryList => GetResourceString("PropertyCategoryList", null); internal static string PropertyCategoryMouse => GetResourceString("PropertyCategoryMouse", null); internal static string PropertyCategoryPosition => GetResourceString("PropertyCategoryPosition", null); internal static string PropertyCategoryScale => GetResourceString("PropertyCategoryScale", null); internal static string PropertyCategoryText => GetResourceString("PropertyCategoryText", null); internal static string PropertyCategoryWindowStyle => GetResourceString("PropertyCategoryWindowStyle", null); internal static Type ResourceType => typeof(FxResources.System.ComponentModel.Primitives.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 String.Concat(resourceFormat, String.Join(", ", args)); } return String.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return String.Join(", ", (object[])(object)new Object[2] { (Object)resourceFormat, p1 }); } return String.Format(resourceFormat, (object[])(object)new Object[1] { p1 }); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return String.Join(", ", (object[])(object)new Object[3] { (Object)resourceFormat, p1, p2 }); } return String.Format(resourceFormat, (object[])(object)new Object[2] { p1, p2 }); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return String.Join(", ", (object[])(object)new Object[4] { (Object)resourceFormat, p1, p2, p3 }); } return String.Format(resourceFormat, (object[])(object)new Object[3] { p1, p2, p3 }); } } } namespace System.ComponentModel { [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class BrowsableAttribute : Attribute { public static readonly BrowsableAttribute Yes = new BrowsableAttribute(browsable: true); public static readonly BrowsableAttribute No = new BrowsableAttribute(browsable: false); public static readonly BrowsableAttribute Default = Yes; private bool _browsable; public bool Browsable => _browsable; public BrowsableAttribute(bool browsable) { _browsable = browsable; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is BrowsableAttribute browsableAttribute) { return browsableAttribute.Browsable == _browsable; } return false; } public override int GetHashCode() { return ((Boolean)(ref _browsable)).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class CategoryAttribute : Attribute { private static volatile CategoryAttribute s_action; private static volatile CategoryAttribute s_appearance; private static volatile CategoryAttribute s_asynchronous; private static volatile CategoryAttribute s_behavior; private static volatile CategoryAttribute s_data; private static volatile CategoryAttribute s_design; private static volatile CategoryAttribute s_dragDrop; private static volatile CategoryAttribute s_defAttr; private static volatile CategoryAttribute s_focus; private static volatile CategoryAttribute s_format; private static volatile CategoryAttribute s_key; private static volatile CategoryAttribute s_layout; private static volatile CategoryAttribute s_mouse; private static volatile CategoryAttribute s_windowStyle; private bool _localized; private string _categoryValue; public static CategoryAttribute Action { get { if (s_action == null) { s_action = new CategoryAttribute("Action"); } return s_action; } } public static CategoryAttribute Appearance { get { if (s_appearance == null) { s_appearance = new CategoryAttribute("Appearance"); } return s_appearance; } } public static CategoryAttribute Asynchronous { get { if (s_asynchronous == null) { s_asynchronous = new CategoryAttribute("Asynchronous"); } return s_asynchronous; } } public static CategoryAttribute Behavior { get { if (s_behavior == null) { s_behavior = new CategoryAttribute("Behavior"); } return s_behavior; } } public static CategoryAttribute Data { get { if (s_data == null) { s_data = new CategoryAttribute("Data"); } return s_data; } } public static CategoryAttribute Default { get { if (s_defAttr == null) { s_defAttr = new CategoryAttribute(); } return s_defAttr; } } public static CategoryAttribute Design { get { if (s_design == null) { s_design = new CategoryAttribute("Design"); } return s_design; } } public static CategoryAttribute DragDrop { get { if (s_dragDrop == null) { s_dragDrop = new CategoryAttribute("DragDrop"); } return s_dragDrop; } } public static CategoryAttribute Focus { get { if (s_focus == null) { s_focus = new CategoryAttribute("Focus"); } return s_focus; } } public static CategoryAttribute Format { get { if (s_format == null) { s_format = new CategoryAttribute("Format"); } return s_format; } } public static CategoryAttribute Key { get { if (s_key == null) { s_key = new CategoryAttribute("Key"); } return s_key; } } public static CategoryAttribute Layout { get { if (s_layout == null) { s_layout = new CategoryAttribute("Layout"); } return s_layout; } } public static CategoryAttribute Mouse { get { if (s_mouse == null) { s_mouse = new CategoryAttribute("Mouse"); } return s_mouse; } } public static CategoryAttribute WindowStyle { get { if (s_windowStyle == null) { s_windowStyle = new CategoryAttribute("WindowStyle"); } return s_windowStyle; } } public string Category { get { if (!_localized) { _localized = true; string localizedString = GetLocalizedString(_categoryValue); if (localizedString != null) { _categoryValue = localizedString; } } return _categoryValue; } } public CategoryAttribute() : this("Default") { } public CategoryAttribute(string category) { _categoryValue = category; _localized = false; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is CategoryAttribute categoryAttribute) { return Category.Equals(categoryAttribute.Category); } return false; } public override int GetHashCode() { return ((Object)Category).GetHashCode(); } protected virtual string GetLocalizedString(string value) { return SR.GetResourceString(String.Concat("PropertyCategory", value), null); } } public class ComponentCollection : Object { private ComponentCollection() { } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class DescriptionAttribute : Attribute { public static readonly DescriptionAttribute Default = new DescriptionAttribute(); public virtual string Description => DescriptionValue; [field: CompilerGenerated] protected string DescriptionValue { [CompilerGenerated] get; [CompilerGenerated] set; } public DescriptionAttribute() : this(String.Empty) { } public DescriptionAttribute(string description) { DescriptionValue = description; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DescriptionAttribute descriptionAttribute) { return descriptionAttribute.Description == Description; } return false; } public override int GetHashCode() { return ((Object)Description).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DesignerCategoryAttribute : Attribute { public static readonly DesignerCategoryAttribute Component = new DesignerCategoryAttribute("Component"); public static readonly DesignerCategoryAttribute Default = new DesignerCategoryAttribute(); public static readonly DesignerCategoryAttribute Form = new DesignerCategoryAttribute("Form"); public static readonly DesignerCategoryAttribute Generic = new DesignerCategoryAttribute("Designer"); [field: CompilerGenerated] public string Category { [CompilerGenerated] get; } public DesignerCategoryAttribute() { Category = String.Empty; } public DesignerCategoryAttribute(string category) { Category = category; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DesignerCategoryAttribute designerCategoryAttribute) { return designerCategoryAttribute.Category == Category; } return false; } public override int GetHashCode() { return ((Object)Category).GetHashCode(); } } public enum DesignerSerializationVisibility : Enum { Hidden, Visible, Content } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DesignerSerializationVisibilityAttribute : Attribute { public static readonly DesignerSerializationVisibilityAttribute Content = new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content); public static readonly DesignerSerializationVisibilityAttribute Hidden = new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden); public static readonly DesignerSerializationVisibilityAttribute Visible = new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible); public static readonly DesignerSerializationVisibilityAttribute Default = Visible; private readonly DesignerSerializationVisibility _visibility; public DesignerSerializationVisibility Visibility => _visibility; public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility visibility) { _visibility = visibility; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DesignerSerializationVisibilityAttribute designerSerializationVisibilityAttribute) { return designerSerializationVisibilityAttribute.Visibility == _visibility; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DesignOnlyAttribute : Attribute { public static readonly DesignOnlyAttribute Yes = new DesignOnlyAttribute(isDesignOnly: true); public static readonly DesignOnlyAttribute No = new DesignOnlyAttribute(isDesignOnly: false); public static readonly DesignOnlyAttribute Default = No; [field: CompilerGenerated] public bool IsDesignOnly { [CompilerGenerated] get; } public DesignOnlyAttribute(bool isDesignOnly) { IsDesignOnly = isDesignOnly; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DesignOnlyAttribute designOnlyAttribute) { return designOnlyAttribute.IsDesignOnly == IsDesignOnly; } return false; } public override int GetHashCode() { bool isDesignOnly = IsDesignOnly; return ((Boolean)(ref isDesignOnly)).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class DisplayNameAttribute : Attribute { public static readonly DisplayNameAttribute Default = new DisplayNameAttribute(); public virtual string DisplayName => DisplayNameValue; [field: CompilerGenerated] protected string DisplayNameValue { [CompilerGenerated] get; [CompilerGenerated] set; } public DisplayNameAttribute() : this(String.Empty) { } public DisplayNameAttribute(string displayName) { DisplayNameValue = displayName; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DisplayNameAttribute displayNameAttribute) { return displayNameAttribute.DisplayName == DisplayName; } return false; } public override int GetHashCode() { return ((Object)DisplayName).GetHashCode(); } } [DefaultMember("Item")] public sealed class EventHandlerList : Object, IDisposable { private sealed class ListEntry : Object { internal ListEntry next; internal object key; internal Delegate handler; public ListEntry(object key, Delegate handler, ListEntry next) { this.next = next; this.key = key; this.handler = handler; } } private ListEntry _head; public Delegate this[object key] { get { return Find(key)?.handler; } set { ListEntry listEntry = Find(key); if (listEntry != null) { listEntry.handler = value; } else { _head = new ListEntry(key, value, _head); } } } public void AddHandler(object key, Delegate value) { ListEntry listEntry = Find(key); if (listEntry != null) { listEntry.handler = Delegate.Combine(listEntry.handler, value); } else { _head = new ListEntry(key, value, _head); } } public void AddHandlers(EventHandlerList listToAddFrom) { for (ListEntry listEntry = listToAddFrom._head; listEntry != null; listEntry = listEntry.next) { AddHandler(listEntry.key, listEntry.handler); } } public void Dispose() { _head = null; } private ListEntry Find(object key) { ListEntry listEntry = _head; while (listEntry != null && listEntry.key != key) { listEntry = listEntry.next; } return listEntry; } public void RemoveHandler(object key, Delegate value) { ListEntry listEntry = Find(key); if (listEntry != null) { listEntry.handler = Delegate.Remove(listEntry.handler, value); } } } public interface IComponent : IDisposable { ISite Site { get; set; } event EventHandler Disposed; } public interface IContainer : IDisposable { ComponentCollection Components { get; } void Add(IComponent component); void Add(IComponent component, string name); void Remove(IComponent component); } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class ImmutableObjectAttribute : Attribute { public static readonly ImmutableObjectAttribute Yes = new ImmutableObjectAttribute(immutable: true); public static readonly ImmutableObjectAttribute No = new ImmutableObjectAttribute(immutable: false); public static readonly ImmutableObjectAttribute Default = No; [field: CompilerGenerated] public bool Immutable { [CompilerGenerated] get; } public ImmutableObjectAttribute(bool immutable) { Immutable = immutable; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is ImmutableObjectAttribute immutableObjectAttribute) { return immutableObjectAttribute.Immutable == Immutable; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class InitializationEventAttribute : Attribute { [field: CompilerGenerated] public string EventName { [CompilerGenerated] get; } public InitializationEventAttribute(string eventName) { EventName = eventName; } } public interface ISite : IServiceProvider { IComponent Component { get; } IContainer Container { get; } bool DesignMode { get; } string Name { get; set; } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class LocalizableAttribute : Attribute { public static readonly LocalizableAttribute Yes = new LocalizableAttribute(isLocalizable: true); public static readonly LocalizableAttribute No = new LocalizableAttribute(isLocalizable: false); public static readonly LocalizableAttribute Default = No; [field: CompilerGenerated] public bool IsLocalizable { [CompilerGenerated] get; } public LocalizableAttribute(bool isLocalizable) { IsLocalizable = isLocalizable; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is LocalizableAttribute localizableAttribute) { return localizableAttribute.IsLocalizable == IsLocalizable; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class MergablePropertyAttribute : Attribute { public static readonly MergablePropertyAttribute Yes = new MergablePropertyAttribute(allowMerge: true); public static readonly MergablePropertyAttribute No = new MergablePropertyAttribute(allowMerge: false); public static readonly MergablePropertyAttribute Default = Yes; [field: CompilerGenerated] public bool AllowMerge { [CompilerGenerated] get; } public MergablePropertyAttribute(bool allowMerge) { AllowMerge = allowMerge; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is MergablePropertyAttribute mergablePropertyAttribute) { return mergablePropertyAttribute.AllowMerge == AllowMerge; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class NotifyParentPropertyAttribute : Attribute { public static readonly NotifyParentPropertyAttribute Yes = new NotifyParentPropertyAttribute(notifyParent: true); public static readonly NotifyParentPropertyAttribute No = new NotifyParentPropertyAttribute(notifyParent: false); public static readonly NotifyParentPropertyAttribute Default = No; [field: CompilerGenerated] public bool NotifyParent { [CompilerGenerated] get; } public NotifyParentPropertyAttribute(bool notifyParent) { NotifyParent = notifyParent; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is NotifyParentPropertyAttribute notifyParentPropertyAttribute) { return notifyParentPropertyAttribute.NotifyParent == NotifyParent; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class ParenthesizePropertyNameAttribute : Attribute { public static readonly ParenthesizePropertyNameAttribute Default = new ParenthesizePropertyNameAttribute(); [field: CompilerGenerated] public bool NeedParenthesis { [CompilerGenerated] get; } public ParenthesizePropertyNameAttribute() : this(needParenthesis: false) { } public ParenthesizePropertyNameAttribute(bool needParenthesis) { NeedParenthesis = needParenthesis; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is ParenthesizePropertyNameAttribute parenthesizePropertyNameAttribute) { return parenthesizePropertyNameAttribute.NeedParenthesis == NeedParenthesis; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class ReadOnlyAttribute : Attribute { public static readonly ReadOnlyAttribute Yes = new ReadOnlyAttribute(isReadOnly: true); public static readonly ReadOnlyAttribute No = new ReadOnlyAttribute(isReadOnly: false); public static readonly ReadOnlyAttribute Default = No; [field: CompilerGenerated] public bool IsReadOnly { [CompilerGenerated] get; } public ReadOnlyAttribute(bool isReadOnly) { IsReadOnly = isReadOnly; } public override bool Equals(object value) { if (this == value) { return true; } if (value is ReadOnlyAttribute readOnlyAttribute) { return readOnlyAttribute.IsReadOnly == IsReadOnly; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } public enum RefreshProperties : Enum { None, All, Repaint } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class RefreshPropertiesAttribute : Attribute { public static readonly RefreshPropertiesAttribute All = new RefreshPropertiesAttribute(RefreshProperties.All); public static readonly RefreshPropertiesAttribute Repaint = new RefreshPropertiesAttribute(RefreshProperties.Repaint); public static readonly RefreshPropertiesAttribute Default = new RefreshPropertiesAttribute(RefreshProperties.None); [field: CompilerGenerated] public RefreshProperties RefreshProperties { [CompilerGenerated] get; } public RefreshPropertiesAttribute(RefreshProperties refresh) { RefreshProperties = refresh; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is RefreshPropertiesAttribute refreshPropertiesAttribute) { return refreshPropertiesAttribute.RefreshProperties == RefreshProperties; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } }
BepInEx/plugins/VNyanCommands/System.ComponentModel.TypeConverter.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using FxResources.System.ComponentModel.TypeConverter; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.ComponentModel.TypeConverter")] [assembly: AssemblyDescription("System.ComponentModel.TypeConverter")] [assembly: AssemblyDefaultAlias("System.ComponentModel.TypeConverter")] [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.1.1.0")] namespace FxResources.System.ComponentModel.TypeConverter { internal static class SR { } } namespace System { public class UriTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (sourceType == null) { throw new ArgumentNullException("sourceType"); } if (sourceType != typeof(string)) { return sourceType == typeof(Uri); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType != typeof(string)) { return destinationType == typeof(Uri); } return true; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if (value is string text) { if (string.IsNullOrEmpty(text)) { return null; } return (object)new Uri(text, (UriKind)0); } Uri val = (Uri)((value is Uri) ? value : null); if (val != (Uri)null) { return (object)new Uri(val.OriginalString); } throw GetConvertFromException(value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: 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_004f: Expected O, but got Unknown if (destinationType == null) { throw new ArgumentNullException("destinationType"); } Uri val = (Uri)((value is Uri) ? value : null); if (val != (Uri)null) { if (destinationType == typeof(string)) { return val.OriginalString; } if (destinationType == typeof(Uri)) { return (object)new Uri(val.OriginalString, (UriKind)0); } } throw GetConvertToException(value, destinationType); } } internal class InvariantComparer : IComparer { private readonly CompareInfo _compareInfo; internal static readonly InvariantComparer Default = new InvariantComparer(); internal InvariantComparer() { _compareInfo = CultureInfo.InvariantCulture.CompareInfo; } public int Compare(object a, object b) { string text = a as string; string text2 = b as string; if (text != null && text2 != null) { return _compareInfo.Compare(text, text2); } return Comparer.Default.Compare(a, b); } } internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.ComponentModel.TypeConverter.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 Array => GetResourceString("Array", null); internal static string Collection => GetResourceString("Collection", null); internal static string ConvertFromException => GetResourceString("ConvertFromException", null); internal static string ConvertInvalidPrimitive => GetResourceString("ConvertInvalidPrimitive", null); internal static string ConvertToException => GetResourceString("ConvertToException", null); internal static string EnumConverterInvalidValue => GetResourceString("EnumConverterInvalidValue", null); internal static string ErrorInvalidEventHandler => GetResourceString("ErrorInvalidEventHandler", null); internal static string ErrorInvalidEventType => GetResourceString("ErrorInvalidEventType", null); internal static string ErrorInvalidPropertyType => GetResourceString("ErrorInvalidPropertyType", null); internal static string ErrorMissingEventAccessors => GetResourceString("ErrorMissingEventAccessors", null); internal static string ErrorMissingPropertyAccessors => GetResourceString("ErrorMissingPropertyAccessors", null); internal static string ErrorPropertyAccessorException => GetResourceString("ErrorPropertyAccessorException", null); internal static string InvalidMemberName => GetResourceString("InvalidMemberName", null); internal static string InvalidNullArgument => GetResourceString("InvalidNullArgument", null); internal static string MetaExtenderName => GetResourceString("MetaExtenderName", null); internal static string none => GetResourceString("none", null); internal static string Null => GetResourceString("Null", null); internal static string NullableConverterBadCtorArg => GetResourceString("NullableConverterBadCtorArg", null); internal static string Text => GetResourceString("Text", null); internal static string TypeDescriptorAlreadyAssociated => GetResourceString("TypeDescriptorAlreadyAssociated", null); internal static string TypeDescriptorArgsCountMismatch => GetResourceString("TypeDescriptorArgsCountMismatch", null); internal static string TypeDescriptorProviderError => GetResourceString("TypeDescriptorProviderError", null); internal static string TypeDescriptorUnsupportedRemoteObject => GetResourceString("TypeDescriptorUnsupportedRemoteObject", null); internal static string TypeDescriptorExpectedElementType => GetResourceString("TypeDescriptorExpectedElementType", null); internal static string TypeDescriptorSameAssociation => GetResourceString("TypeDescriptorSameAssociation", null); internal static System.Type ResourceType => typeof(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.ComponentModel { public class ArrayConverter : CollectionConverter { private class ArrayPropertyDescriptor : SimplePropertyDescriptor { private readonly int _index; public ArrayPropertyDescriptor(System.Type arrayType, System.Type elementType, int index) : base(arrayType, string.Concat((object)"[", (object)index, (object)"]"), elementType, null) { _index = index; } public override object GetValue(object instance) { if (instance is System.Array array && array.GetLength(0) > _index) { return array.GetValue(_index); } return null; } public override void SetValue(object instance, object value) { if (instance is System.Array) { System.Array array = (System.Array)instance; if (array.GetLength(0) > _index) { array.SetValue(value, _index); } OnValueChanged(instance, EventArgs.Empty); } } } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value is System.Array) { return System.SR.Format(System.SR.Array, value.GetType().Name); } return base.ConvertTo(context, culture, value, destinationType); } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { if (value == null) { return null; } PropertyDescriptor[] array = null; if (value.GetType().IsArray) { System.Array array2 = (System.Array)value; int length = array2.GetLength(0); array = new PropertyDescriptor[length]; System.Type type = value.GetType(); System.Type elementType = type.GetElementType(); for (int i = 0; i < length; i++) { array[i] = new ArrayPropertyDescriptor(type, elementType, i); } } return new PropertyDescriptorCollection(array); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } } public abstract class BaseNumberConverter : TypeConverter { internal virtual bool AllowHex => true; internal abstract System.Type TargetType { get; } internal abstract object FromString(string value, int radix); internal abstract object FromString(string value, NumberFormatInfo formatInfo); internal abstract object FromString(string value, CultureInfo culture); internal virtual System.Exception FromStringError(string failedText, System.Exception innerException) { return new System.Exception(System.SR.Format(System.SR.ConvertInvalidPrimitive, failedText, TargetType.Name), innerException); } internal abstract string ToString(object value, NumberFormatInfo formatInfo); public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown if (value is string text) { string text2 = text.Trim(); try { if (AllowHex && text2[0] == '#') { return FromString(text2.Substring(1), 16); } if ((AllowHex && text2.StartsWith("0x", (StringComparison)5)) || text2.StartsWith("&h", (StringComparison)5)) { return FromString(text2.Substring(2), 16); } if (culture == null) { culture = CultureInfo.CurrentCulture; } NumberFormatInfo formatInfo = (NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)); return FromString(text2, formatInfo); } catch (System.Exception innerException) { throw FromStringError(text2, innerException); } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: 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: Expected O, but got Unknown if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value != null && IntrospectionExtensions.GetTypeInfo(TargetType).IsAssignableFrom(IntrospectionExtensions.GetTypeInfo(value.GetType()))) { if (culture == null) { culture = CultureInfo.CurrentCulture; } NumberFormatInfo val = (NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)); return ToString(value, val); } if (IntrospectionExtensions.GetTypeInfo(destinationType).IsPrimitive) { return Convert.ChangeType(value, destinationType, (IFormatProvider)(object)culture); } return base.ConvertTo(context, culture, value, destinationType); } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (!base.CanConvertTo(context, destinationType)) { return IntrospectionExtensions.GetTypeInfo(destinationType).IsPrimitive; } return true; } } public class BooleanConverter : TypeConverter { private static volatile StandardValuesCollection s_values; public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0020: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (value is string text) { string text2 = text.Trim(); try { return bool.Parse(text2); } catch (FormatException val) { FormatException val2 = val; throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, "Boolean"), (System.Exception)(object)val2); } } return base.ConvertFrom(context, culture, value); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (s_values == null) { s_values = new StandardValuesCollection((System.Collections.ICollection)(object)new object[2] { true, false }); } return s_values; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } } public class ByteConverter : BaseNumberConverter { internal override System.Type TargetType => typeof(byte); internal override object FromString(string value, int radix) { return Convert.ToByte(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return byte.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return byte.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((byte)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class CharConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { if (destinationType == typeof(string) && value is char && (char)value == '\0') { return ""; } return base.ConvertTo(context, culture, value, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) string text = value as string; if (text != null) { if (text.Length > 1) { text = text.Trim(); } if (text.Length > 0) { if (text.Length != 1) { throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, text, "Char")); } return text[0]; } return '\0'; } return base.ConvertFrom(context, culture, value); } } public class CollectionConverter : TypeConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value is System.Collections.ICollection) { return System.SR.Collection; } return base.ConvertTo(context, culture, value, destinationType); } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { return new PropertyDescriptorCollection(null); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return false; } } public class DateTimeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0062: Expected O, but got Unknown //IL_0078: 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_0040: Expected O, but got Unknown if (value is string text) { string text2 = text.Trim(); if (text2.Length == 0) { return System.DateTime.MinValue; } try { DateTimeFormatInfo val = null; if (culture != null) { val = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); } if (val != null) { return System.DateTime.Parse(text2, (IFormatProvider)(object)val); } return System.DateTime.Parse(text2, (IFormatProvider)(object)culture); } catch (FormatException val2) { FormatException val3 = val2; throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, "DateTime"), (System.Exception)(object)val3); } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_0093: 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) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (destinationType == typeof(string) && value is System.DateTime dateTime) { if (dateTime == System.DateTime.MinValue) { return string.Empty; } if (culture == null) { culture = CultureInfo.CurrentCulture; } DateTimeFormatInfo val = null; val = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); TimeSpan timeOfDay; if (culture == CultureInfo.InvariantCulture) { timeOfDay = dateTime.TimeOfDay; if (((TimeSpan)(ref timeOfDay)).TotalSeconds == 0.0) { return dateTime.ToString("yyyy-MM-dd", (IFormatProvider)(object)culture); } return dateTime.ToString((IFormatProvider)(object)culture); } timeOfDay = dateTime.TimeOfDay; string text = ((((TimeSpan)(ref timeOfDay)).TotalSeconds != 0.0) ? (val.ShortDatePattern + " " + val.ShortTimePattern) : val.ShortDatePattern); return dateTime.ToString(text, (IFormatProvider)(object)CultureInfo.CurrentCulture); } return base.ConvertTo(context, culture, value, destinationType); } } public class DateTimeOffsetConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0062: Expected O, but got Unknown //IL_0078: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0054: 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) if (value is string text) { string text2 = text.Trim(); if (text2.Length == 0) { return DateTimeOffset.MinValue; } try { DateTimeFormatInfo val = null; if (culture != null) { val = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); } if (val != null) { return DateTimeOffset.Parse(text2, (IFormatProvider)(object)val); } return DateTimeOffset.Parse(text2, (IFormatProvider)(object)culture); } catch (FormatException val2) { FormatException val3 = val2; throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, "DateTimeOffset"), (System.Exception)(object)val3); } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_001d: 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_0024: 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_0058: Expected O, but got Unknown //IL_0093: 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) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (destinationType == typeof(string) && value is DateTimeOffset val) { if (val == DateTimeOffset.MinValue) { return string.Empty; } if (culture == null) { culture = CultureInfo.CurrentCulture; } DateTimeFormatInfo val2 = null; val2 = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); TimeSpan timeOfDay; if (culture == CultureInfo.InvariantCulture) { timeOfDay = ((DateTimeOffset)(ref val)).TimeOfDay; if (((TimeSpan)(ref timeOfDay)).TotalSeconds == 0.0) { return ((DateTimeOffset)(ref val)).ToString("yyyy-MM-dd zzz", (IFormatProvider)(object)culture); } return ((DateTimeOffset)(ref val)).ToString((IFormatProvider)(object)culture); } timeOfDay = ((DateTimeOffset)(ref val)).TimeOfDay; string text = ((((TimeSpan)(ref timeOfDay)).TotalSeconds != 0.0) ? (val2.ShortDatePattern + " " + val2.ShortTimePattern + " zzz") : (val2.ShortDatePattern + " zzz")); return ((DateTimeOffset)(ref val)).ToString(text, (IFormatProvider)(object)CultureInfo.CurrentCulture); } return base.ConvertTo(context, culture, value, destinationType); } } public class DecimalConverter : BaseNumberConverter { internal override bool AllowHex => false; internal override System.Type TargetType => typeof(decimal); public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } return base.ConvertTo(context, culture, value, destinationType); } internal override object FromString(string value, int radix) { return Convert.ToDecimal(value, (IFormatProvider)(object)CultureInfo.CurrentCulture); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return decimal.Parse(value, (NumberStyles)167, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return decimal.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((decimal)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class DoubleConverter : BaseNumberConverter { internal override bool AllowHex => false; internal override System.Type TargetType => typeof(double); internal override object FromString(string value, int radix) { return Convert.ToDouble(value, (IFormatProvider)(object)CultureInfo.CurrentCulture); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return double.Parse(value, (NumberStyles)167, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return double.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((double)value).ToString("R", (IFormatProvider)(object)formatInfo); } } public class EnumConverter : TypeConverter { private StandardValuesCollection _values; private readonly System.Type _type; protected System.Type EnumType => _type; protected StandardValuesCollection Values { get { return _values; } set { _values = value; } } protected virtual IComparer Comparer => (IComparer)(object)InvariantComparer.Default; public EnumConverter(System.Type type) { _type = type; } public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == typeof(string) || sourceType == typeof(System.Enum[])) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(System.Enum[])) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) if (value is string text) { try { if (text.IndexOf(',') != -1) { long num = 0L; string[] array = text.Split(new char[1] { ',' }); string[] array2 = array; foreach (string text2 in array2) { num |= Convert.ToInt64((object)(System.Enum)System.Enum.Parse(_type, text2, true), (IFormatProvider)(object)culture); } return System.Enum.ToObject(_type, (object)num); } return System.Enum.Parse(_type, text, true); } catch (System.Exception ex) { throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, _type.Name), ex); } } if (value is System.Enum[]) { long num2 = 0L; System.Enum[] array3 = (System.Enum[])value; foreach (System.Enum @enum in array3) { num2 |= Convert.ToInt64((object)@enum, (IFormatProvider)(object)culture); } return System.Enum.ToObject(_type, (object)num2); } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value != null) { if (!CustomAttributeExtensions.IsDefined((MemberInfo)(object)IntrospectionExtensions.GetTypeInfo(_type), typeof(FlagsAttribute), false) && !System.Enum.IsDefined(_type, value)) { throw new ArgumentException(System.SR.Format(System.SR.EnumConverterInvalidValue, value.ToString(), _type.Name)); } return System.Enum.Format(_type, value, "G"); } if (destinationType == typeof(System.Enum[]) && value != null) { if (CustomAttributeExtensions.IsDefined((MemberInfo)(object)IntrospectionExtensions.GetTypeInfo(_type), typeof(FlagsAttribute), false)) { List<System.Enum> val = new List<System.Enum>(); System.Array values = System.Enum.GetValues(_type); long[] array = new long[values.Length]; for (int i = 0; i < values.Length; i++) { array[i] = Convert.ToInt64((object)(System.Enum)values.GetValue(i), (IFormatProvider)(object)culture); } long num = Convert.ToInt64((object)(System.Enum)value, (IFormatProvider)(object)culture); bool flag = true; while (flag) { flag = false; long[] array2 = array; foreach (long num2 in array2) { if ((num2 != 0L && (num2 & num) == num2) || num2 == num) { val.Add((System.Enum)System.Enum.ToObject(_type, (object)num2)); flag = true; num &= ~num2; break; } } if (num == 0L) { break; } } if (!flag && num != 0L) { val.Add((System.Enum)System.Enum.ToObject(_type, (object)num)); } return val.ToArray(); } return new System.Enum[1] { (System.Enum)System.Enum.ToObject(_type, value) }; } return base.ConvertTo(context, culture, value, destinationType); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown if (_values == null) { System.Type type = TypeDescriptor.GetReflectionType(_type); if (type == null) { type = _type; } FieldInfo[] fields = TypeExtensions.GetFields(type, (BindingFlags)24); ArrayList val = null; if (fields != null && fields.Length != 0) { val = new ArrayList(fields.Length); } if (val != null) { FieldInfo[] array = fields; foreach (FieldInfo val2 in array) { BrowsableAttribute val3 = null; System.Collections.Generic.IEnumerator<System.Attribute> enumerator = CustomAttributeExtensions.GetCustomAttributes((MemberInfo)(object)val2, typeof(BrowsableAttribute), false).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { System.Attribute current = enumerator.Current; val3 = (BrowsableAttribute)(object)((current is BrowsableAttribute) ? current : null); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } if (val3 != null && !val3.Browsable) { continue; } object obj = null; try { if (((MemberInfo)val2).Name != null) { obj = System.Enum.Parse(_type, ((MemberInfo)val2).Name); } } catch (ArgumentException) { } if (obj != null) { val.Add(obj); } } IComparer comparer = Comparer; if (comparer != null) { val.Sort(comparer); } } System.Array values = ((val != null) ? val.ToArray() : null); _values = new StandardValuesCollection((System.Collections.ICollection)values); } return _values; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return !CustomAttributeExtensions.IsDefined((MemberInfo)(object)IntrospectionExtensions.GetTypeInfo(_type), typeof(FlagsAttribute), false); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool IsValid(ITypeDescriptorContext context, object value) { return System.Enum.IsDefined(_type, value); } } public class GuidConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (value is string text) { string text2 = text.Trim(); return (object)new Guid(text2); } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } return base.ConvertTo(context, culture, value, destinationType); } } public class Int16Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(short); internal override object FromString(string value, int radix) { return Convert.ToInt16(value, radix); } internal override object FromString(string value, CultureInfo culture) { return short.Parse(value, (IFormatProvider)(object)culture); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return short.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((short)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class Int32Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(int); internal override object FromString(string value, int radix) { return Convert.ToInt32(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return int.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return int.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((int)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class Int64Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(long); internal override object FromString(string value, int radix) { return Convert.ToInt64(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return long.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return long.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((long)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public interface ITypeDescriptorContext : IServiceProvider { IContainer Container { get; } object Instance { get; } PropertyDescriptor PropertyDescriptor { get; } bool OnComponentChanging(); void OnComponentChanged(); } public class MultilineStringConverter : TypeConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value is string) { return System.SR.Text; } return base.ConvertTo(context, culture, value, destinationType); } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { return null; } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return false; } } public class NullableConverter : TypeConverter { private readonly System.Type _nullableType; private readonly System.Type _simpleType; private readonly TypeConverter _simpleTypeConverter; public System.Type NullableType => _nullableType; public System.Type UnderlyingType => _simpleType; public TypeConverter UnderlyingTypeConverter => _simpleTypeConverter; public NullableConverter(System.Type type) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) _nullableType = type; _simpleType = Nullable.GetUnderlyingType(type); if (_simpleType == null) { throw new ArgumentException(System.SR.NullableConverterBadCtorArg, "type"); } _simpleTypeConverter = TypeDescriptor.GetConverter(_simpleType); } public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == _simpleType) { return true; } if (_simpleTypeConverter != null) { return _simpleTypeConverter.CanConvertFrom(context, sourceType); } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value == null || value.GetType() == _simpleType) { return value; } if (value is string && string.IsNullOrEmpty(value as string)) { return null; } if (_simpleTypeConverter != null) { return _simpleTypeConverter.ConvertFrom(context, culture, value); } return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == _simpleType) { return true; } if (_simpleTypeConverter != null) { return _simpleTypeConverter.CanConvertTo(context, destinationType); } return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == _simpleType && value != null && IntrospectionExtensions.GetTypeInfo(_nullableType).IsAssignableFrom(IntrospectionExtensions.GetTypeInfo(value.GetType()))) { return value; } if (value == null) { if (destinationType == typeof(string)) { return string.Empty; } } else if (_simpleTypeConverter != null) { return _simpleTypeConverter.ConvertTo(context, culture, value, destinationType); } return base.ConvertTo(context, culture, value, destinationType); } public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.CreateInstance(context, propertyValues); } return base.CreateInstance(context, propertyValues); } public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetCreateInstanceSupported(context); } return base.GetCreateInstanceSupported(context); } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetProperties(context, value, attributes); } return base.GetProperties(context, value, attributes); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetPropertiesSupported(context); } return base.GetPropertiesSupported(context); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { StandardValuesCollection standardValues = _simpleTypeConverter.GetStandardValues(context); if (GetStandardValuesSupported(context) && standardValues != null) { object[] array = new object[standardValues.Count + 1]; int num = 0; array[num++] = null; foreach (object item in standardValues) { array[num++] = item; } return new StandardValuesCollection((System.Collections.ICollection)(object)array); } } return base.GetStandardValues(context); } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetStandardValuesExclusive(context); } return base.GetStandardValuesExclusive(context); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetStandardValuesSupported(context); } return base.GetStandardValuesSupported(context); } public override bool IsValid(ITypeDescriptorContext context, object value) { if (_simpleTypeConverter != null) { if (value == null) { return true; } return _simpleTypeConverter.IsValid(context, value); } return base.IsValid(context, value); } } public abstract class PropertyDescriptor : MemberDescriptor { private TypeConverter _converter; private Hashtable _valueChangedHandlers; private object[] _editors; private System.Type[] _editorTypes; private int _editorCount; public abstract System.Type ComponentType { get; } public virtual TypeConverter Converter { get { AttributeCollection attributes = Attributes; if (_converter == null) { TypeConverterAttribute typeConverterAttribute = (TypeConverterAttribute)attributes[typeof(TypeConverterAttribute)]; if (typeConverterAttribute.ConverterTypeName != null && typeConverterAttribute.ConverterTypeName.Length > 0) { System.Type typeFromName = GetTypeFromName(typeConverterAttribute.ConverterTypeName); if (typeFromName != null && IntrospectionExtensions.GetTypeInfo(typeof(TypeConverter)).IsAssignableFrom(typeFromName)) { _converter = (TypeConverter)CreateInstance(typeFromName); } } if (_converter == null) { _converter = TypeDescriptor.GetConverter(PropertyType); } } return _converter; } } public virtual bool IsLocalizable => ((object)LocalizableAttribute.Yes).Equals((object)Attributes[typeof(LocalizableAttribute)]); public abstract bool IsReadOnly { get; } public DesignerSerializationVisibility SerializationVisibility { get { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_001c: Unknown result type (might be due to invalid IL or missing references) DesignerSerializationVisibilityAttribute val = (DesignerSerializationVisibilityAttribute)Attributes[typeof(DesignerSerializationVisibilityAttribute)]; return val.Visibility; } } public abstract System.Type PropertyType { get; } public virtual bool SupportsChangeEvents => false; protected PropertyDescriptor(string name, System.Attribute[] attrs) : base(name, attrs) { } protected PropertyDescriptor(MemberDescriptor descr) : base(descr) { } protected PropertyDescriptor(MemberDescriptor descr, System.Attribute[] attrs) : base(descr, attrs) { } public virtual void AddValueChanged(object component, EventHandler handler) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown if (component == null) { throw new ArgumentNullException("component"); } if (handler == null) { throw new ArgumentNullException("handler"); } if (_valueChangedHandlers == null) { _valueChangedHandlers = new Hashtable(); } EventHandler val = (EventHandler)_valueChangedHandlers[component]; _valueChangedHandlers[component] = System.Delegate.Combine((System.Delegate)(object)val, (System.Delegate)(object)handler); } public abstract bool CanResetValue(object component); public override bool Equals(object obj) { try { if (obj == this) { return true; } if (obj == null) { return false; } if (obj is PropertyDescriptor propertyDescriptor && propertyDescriptor.NameHashCode == NameHashCode && propertyDescriptor.PropertyType == PropertyType && propertyDescriptor.Name.Equals(Name)) { return true; } } catch { } return false; } protected object CreateInstance(System.Type type) { System.Type[] array = new System.Type[1] { typeof(System.Type) }; ConstructorInfo constructor = IntrospectionExtensions.GetTypeInfo(type).GetConstructor(array); if (constructor != null) { return TypeDescriptor.CreateInstance(null, type, array, new object[1] { PropertyType }); } return TypeDescriptor.CreateInstance(null, type, null, null); } protected override void FillAttributes(System.Collections.IList attributeList) { _converter = null; _editors = null; _editorTypes = null; _editorCount = 0; base.FillAttributes(attributeList); } public PropertyDescriptorCollection GetChildProperties() { return GetChildProperties(null, null); } public PropertyDescriptorCollection GetChildProperties(System.Attribute[] filter) { return GetChildProperties(null, filter); } public PropertyDescriptorCollection GetChildProperties(object instance) { return GetChildProperties(instance, null); } public virtual PropertyDescriptorCollection GetChildProperties(object instance, System.Attribute[] filter) { if (instance == null) { return TypeDescriptor.GetProperties(PropertyType, filter); } return TypeDescriptor.GetProperties(instance, filter); } public virtual object GetEditor(System.Type editorBaseType) { object obj = null; AttributeCollection attributes = Attributes; if (_editorTypes != null) { for (int i = 0; i < _editorCount; i++) { if (_editorTypes[i] == editorBaseType) { return _editors[i]; } } } if (obj == null) { if (obj == null) { obj = TypeDescriptor.GetEditor(PropertyType, editorBaseType); } if (_editorTypes == null) { _editorTypes = new System.Type[5]; _editors = new object[5]; } if (_editorCount >= _editorTypes.Length) { System.Type[] array = new System.Type[_editorTypes.Length * 2]; object[] array2 = new object[_editors.Length * 2]; System.Array.Copy((System.Array)_editorTypes, (System.Array)array, _editorTypes.Length); System.Array.Copy((System.Array)_editors, (System.Array)array2, _editors.Length); _editorTypes = array; _editors = array2; } _editorTypes[_editorCount] = editorBaseType; _editors[_editorCount++] = obj; } return obj; } public override int GetHashCode() { return NameHashCode ^ ((object)PropertyType).GetHashCode(); } protected override object GetInvocationTarget(System.Type type, object instance) { object obj = base.GetInvocationTarget(type, instance); if (obj is ICustomTypeDescriptor customTypeDescriptor) { obj = customTypeDescriptor.GetPropertyOwner(this); } return obj; } protected System.Type GetTypeFromName(string typeName) { if (typeName == null || typeName.Length == 0) { return null; } System.Type type = System.Type.GetType(typeName); System.Type type2 = null; if (ComponentType != null && (type == null || IntrospectionExtensions.GetTypeInfo(ComponentType).Assembly.FullName.Equals(IntrospectionExtensions.GetTypeInfo(type).Assembly.FullName))) { int num = typeName.IndexOf(','); if (num != -1) { typeName = typeName.Substring(0, num); } type2 = IntrospectionExtensions.GetTypeInfo(ComponentType).Assembly.GetType(typeName); } return type2 ?? type; } public abstract object GetValue(object component); protected virtual void OnValueChanged(object component, EventArgs e) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (component != null && _valueChangedHandlers != null) { EventHandler val = (EventHandler)_valueChangedHandlers[component]; if ((int)val != 0) { val.Invoke(component, e); } } } public virtual void RemoveValueChanged(object component, EventHandler handler) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown if (component == null) { throw new ArgumentNullException("component"); } if (handler == null) { throw new ArgumentNullException("handler"); } if (_valueChangedHandlers != null) { EventHandler val = (EventHandler)_valueChangedHandlers[component]; val = (EventHandler)System.Delegate.Remove((System.Delegate)(object)val, (System.Delegate)(object)handler); if (val != null) { _valueChangedHandlers[component] = val; } else { _valueChangedHandlers.Remove(component); } } } protected internal EventHandler GetValueChangedHandler(object component) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown if (component != null && _valueChangedHandlers != null) { return (EventHandler)_valueChangedHandlers[component]; } return null; } public abstract void ResetValue(object component); public abstract void SetValue(object component, object value); public abstract bool ShouldSerializeValue(object component); } public class SByteConverter : BaseNumberConverter { internal override System.Type TargetType => typeof(sbyte); internal override object FromString(string value, int radix) { return Convert.ToSByte(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return sbyte.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return sbyte.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((sbyte)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class SingleConverter : BaseNumberConverter { internal override bool AllowHex => false; internal override System.Type TargetType => typeof(float); internal override object FromString(string value, int radix) { return Convert.ToSingle(value, (IFormatProvider)(object)CultureInfo.CurrentCulture); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return float.Parse(value, (NumberStyles)167, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return float.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((float)value).ToString("R", (IFormatProvider)(object)formatInfo); } } public class StringConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { return (string)value; } if (value == null) { return string.Empty; } return base.ConvertFrom(context, culture, value); } } public class TimeSpanConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0021: Expected O, but got Unknown //IL_0037: 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) if (value is string text) { string text2 = text.Trim(); try { return TimeSpan.Parse(text2, (IFormatProvider)(object)culture); } catch (FormatException val) { FormatException val2 = val; throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, "TimeSpan"), (System.Exception)(object)val2); } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } return base.ConvertTo(context, culture, value, destinationType); } } public class TypeConverter { protected abstract class SimplePropertyDescriptor : PropertyDescriptor { private System.Type _componentType; private System.Type _propertyType; public override System.Type ComponentType => _componentType; public override bool IsReadOnly => Attributes.Contains((System.Attribute)(object)ReadOnlyAttribute.Yes); public override System.Type PropertyType => _propertyType; protected SimplePropertyDescriptor(System.Type componentType, string name, System.Type propertyType) : this(componentType, name, propertyType, new System.Attribute[0]) { } protected SimplePropertyDescriptor(System.Type componentType, string name, System.Type propertyType, System.Attribute[] attributes) : base(name, attributes) { _componentType = componentType; _propertyType = propertyType; } public override bool CanResetValue(object component) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown DefaultValueAttribute val = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)]; if (val == null) { return false; } return val.Value.Equals(GetValue(component)); } public override void ResetValue(object component) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown DefaultValueAttribute val = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)]; if (val != null) { SetValue(component, val.Value); } } public override bool ShouldSerializeValue(object component) { return false; } } [DefaultMember("Item")] public class StandardValuesCollection : System.Collections.ICollection, System.Collections.IEnumerable { private System.Collections.ICollection _values; private System.Array _valueArray; public int Count { get { if (_valueArray != null) { return _valueArray.Length; } return _values.Count; } } public object this[int index] { get { if (_valueArray != null) { return _valueArray.GetValue(index); } if (_values is System.Collections.IList list) { return list[index]; } _valueArray = new object[_values.Count]; _values.CopyTo(_valueArray, 0); return _valueArray.GetValue(index); } } bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => null; public StandardValuesCollection(System.Collections.ICollection values) { if (values == null) { values = (System.Collections.ICollection)(object)new object[0]; } if (values is System.Array valueArray) { _valueArray = valueArray; } _values = values; } public void CopyTo(System.Array array, int index) { _values.CopyTo(array, index); } public System.Collections.IEnumerator GetEnumerator() { return ((System.Collections.IEnumerable)_values).GetEnumerator(); } } public bool CanConvertFrom(System.Type sourceType) { return CanConvertFrom(null, sourceType); } public virtual bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { return false; } public bool CanConvertTo(System.Type destinationType) { return CanConvertTo(null, destinationType); } public virtual bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return destinationType == typeof(string); } public object ConvertFrom(object value) { return ConvertFrom(null, CultureInfo.CurrentCulture, value); } public virtual object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { throw GetConvertFromException(value); } public object ConvertFromInvariantString(string text) { return ConvertFromString(null, CultureInfo.InvariantCulture, text); } public object ConvertFromInvariantString(ITypeDescriptorContext context, string text) { return ConvertFromString(context, CultureInfo.InvariantCulture, text); } public object ConvertFromString(string text) { return ConvertFrom(null, null, text); } public object ConvertFromString(ITypeDescriptorContext context, string text) { return ConvertFrom(context, CultureInfo.CurrentCulture, text); } public object ConvertFromString(ITypeDescriptorContext context, CultureInfo culture, string text) { return ConvertFrom(context, culture, text); } public object ConvertTo(object value, System.Type destinationType) { return ConvertTo(null, null, value, destinationType); } public virtual object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string)) { if (value == null) { return string.Empty; } if (culture != null && culture != CultureInfo.CurrentCulture && value is System.IFormattable formattable) { return formattable.ToString((string)null, (IFormatProvider)(object)culture); } return value.ToString(); } throw GetConvertToException(value, destinationType); } public string ConvertToInvariantString(object value) { return ConvertToString(null, CultureInfo.InvariantCulture, value); } public string ConvertToInvariantString(ITypeDescriptorContext context, object value) { return ConvertToString(context, CultureInfo.InvariantCulture, value); } public string ConvertToString(object value) { return (string)ConvertTo(null, CultureInfo.CurrentCulture, value, typeof(string)); } public string ConvertToString(ITypeDescriptorContext context, object value) { return (string)ConvertTo(context, CultureInfo.CurrentCulture, value, typeof(string)); } public string ConvertToString(ITypeDescriptorContext context, CultureInfo culture, object value) { return (string)ConvertTo(context, culture, value, typeof(string)); } public object CreateInstance(IDictionary propertyValues) { return CreateInstance(null, propertyValues); } public virtual object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { return null; } protected System.Exception GetConvertFromException(object value) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(System.SR.Format(p2: (value != null) ? value.GetType().FullName : System.SR.Null, resourceFormat: System.SR.ConvertFromException, p1: base.GetType().Name)); } protected System.Exception GetConvertToException(object value, System.Type destinationType) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(System.SR.Format(p2: (value != null) ? value.GetType().FullName : System.SR.Null, resourceFormat: System.SR.ConvertToException, p1: base.GetType().Name, p3: destinationType.FullName)); } public bool GetCreateInstanceSupported() { return GetCreateInstanceSupported(null); } public virtual bool GetCreateInstanceSupported(ITypeDescriptorContext context) { return false; } public PropertyDescriptorCollection GetProperties(object value) { return GetProperties(null, value); } public PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value) { return GetProperties(context, value, new System.Attribute[1] { (System.Attribute)(object)BrowsableAttribute.Yes }); } public virtual PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { return null; } public bool GetPropertiesSupported() { return GetPropertiesSupported(null); } public virtual bool GetPropertiesSupported(ITypeDescriptorContext context) { return false; } public System.Collections.ICollection GetStandardValues() { return GetStandardValues(null); } public virtual StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return null; } public bool GetStandardValuesExclusive() { return GetStandardValuesExclusive(null); } public virtual bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public bool GetStandardValuesSupported() { return GetStandardValuesSupported(null); } public virtual bool GetStandardValuesSupported(ITypeDescriptorContext context) { return false; } public bool IsValid(object value) { return IsValid(null, value); } public virtual bool IsValid(ITypeDescriptorContext context, object value) { bool result = true; try { if (value == null || CanConvertFrom(context, value.GetType())) { ConvertFrom(context, CultureInfo.InvariantCulture, value); } else { result = false; } } catch { result = false; } return result; } protected PropertyDescriptorCollection SortProperties(PropertyDescriptorCollection props, string[] names) { props.Sort(names); return props; } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class TypeConverterAttribute : System.Attribute { private readonly string _typeName; public static readonly TypeConverterAttribute Default = new TypeConverterAttribute(); public string ConverterTypeName => _typeName; public TypeConverterAttribute() { _typeName = string.Empty; } public TypeConverterAttribute(System.Type type) { _typeName = type.AssemblyQualifiedName; } public TypeConverterAttribute(string typeName) { _typeName = typeName; } public bool Equals(object obj) { if (obj is TypeConverterAttribute typeConverterAttribute) { return typeConverterAttribute.ConverterTypeName == _typeName; } return false; } public int GetHashCode() { return ((object)_typeName).GetHashCode(); } } public abstract class TypeListConverter : TypeConverter { private readonly System.Type[] _types; private StandardValuesCollection _values; protected TypeListConverter(System.Type[] types) { _types = types; } public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { System.Type[] types = _types; foreach (System.Type type in types) { if (value.Equals((object)type.FullName)) { return type; } } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string)) { if (value == null) { return System.SR.none; } return ((System.Type)value).FullName; } return base.ConvertTo(context, culture, value, destinationType); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (_values == null) { object[] array; if (_types != null) { array = new object[_types.Length]; System.Array.Copy((System.Array)_types, (System.Array)array, _types.Length); } else { array = null; } _values = new StandardValuesCollection((System.Collections.ICollection)(object)array); } return _values; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } } public class UInt16Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(ushort); internal override object FromString(string value, int radix) { return Convert.ToUInt16(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return ushort.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return ushort.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((ushort)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class UInt32Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(uint); internal override object FromString(string value, int radix) { return Convert.ToUInt32(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return uint.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return uint.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((uint)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class UInt64Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(ulong); internal override object FromString(string value, int radix) { return Convert.ToUInt64(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return ulong.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return ulong.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((ulong)value).ToString("G", (IFormatProvider)(object)formatInfo); } } [DefaultMember("Item")] public class AttributeCollection : System.Collections.ICollection, System.Collections.IEnumerable { private struct AttributeEntry { public System.Type type; public int index; } public static readonly AttributeCollection Empty = new AttributeCollection((System.Attribute[])null); private static Hashtable s_defaultAttributes; private readonly System.Attribute[] _attributes; private static readonly object s_internalSyncObject = new object(); private const int FOUND_TYPES_LIMIT = 5; private AttributeEntry[] _foundAttributeTypes; private int _index; protected virtual System.Attribute[] Attributes => _attributes; public int Count => Attributes.Length; public virtual System.Attribute this[int index] => Attributes[index]; public virtual System.Attribute this[System.Type attributeType] { get { lock (s_internalSyncObject) { if (_foundAttributeTypes == null) { _foundAttributeTypes = new AttributeEntry[5]; } int i; for (i = 0; i < 5; i++) { if (_foundAttributeTypes[i].type == attributeType) { int index = _foundAttributeTypes[i].index; if (index != -1) { return Attributes[index]; } return GetDefaultAttribute(attributeType); } if (_foundAttributeTypes[i].type == null) { break; } } i = _index++; if (_index >= 5) { _index = 0; } _foundAttributeTypes[i].type = attributeType; int num = Attributes.Length; for (int j = 0; j < num; j++) { System.Attribute attribute = Attributes[j]; System.Type type = ((object)attribute).GetType(); if (type == attributeType) { _foundAttributeTypes[i].index = j; return attribute; } } for (int k = 0; k < num; k++) { System.Attribute attribute2 = Attributes[k]; System.Type type2 = ((object)attribute2).GetType(); if (IntrospectionExtensions.GetTypeInfo(attributeType).IsAssignableFrom(IntrospectionExtensions.GetTypeInfo(type2))) { _foundAttributeTypes[i].index = k; return attribute2; } } _foundAttributeTypes[i].index = -1; return GetDefaultAttribute(attributeType); } } } bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => null; public AttributeCollection(params System.Attribute[] attributes) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) _attributes = attributes ?? new System.Attribute[0]; for (int i = 0; i < _attributes.Length; i++) { if (_attributes[i] == null) { throw new ArgumentNullException("attributes"); } } } protected AttributeCollection() { } public static AttributeCollection FromExisting(AttributeCollection existing, params System.Attribute[] newAttributes) { //IL_0008: 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) if (existing == null) { throw new ArgumentNullException("existing"); } if (newAttributes == null) { newAttributes = new System.Attribute[0]; } System.Attribute[] array = new System.Attribute[existing.Count + newAttributes.Length]; int count = existing.Count; existing.CopyTo(array, 0); for (int i = 0; i < newAttributes.Length; i++) { if (newAttributes[i] == null) { throw new ArgumentNullException("newAttributes"); } bool flag = false; for (int j = 0; j < existing.Count; j++) { if (array[j].GetTypeId().Equals(newAttributes[i].GetTypeId())) { flag = true; array[j] = newAttributes[i]; break; } } if (!flag) { array[count++] = newAttributes[i]; } } System.Attribute[] array2 = null; if (count < array.Length) { array2 = new System.Attribute[count]; System.Array.Copy((System.Array)array, 0, (System.Array)array2, 0, count); } else { array2 = array; } return new AttributeCollection(array2); } public bool Contains(System.Attribute attribute) { return ((object)this[((object)attribute).GetType()])?.Equals((object)attribute) ?? false; } public bool Contains(System.Attribute[] attributes) { if (attributes == null) { return true; } for (int i = 0; i < attributes.Length; i++) { if (!Contains(attributes[i])) { return false; } } return true; } protected System.Attribute GetDefaultAttribute(System.Type attributeType) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown lock (s_internalSyncObject) { if (s_defaultAttributes == null) { s_defaultAttributes = new Hashtable(); } if (s_defaultAttributes.ContainsKey((object)attributeType)) { return (System.Attribute)s_defaultAttributes[(object)attributeType]; } System.Attribute attribute = null; System.Type reflectionType = TypeDescriptor.GetReflectionType(attributeType); FieldInfo field = IntrospectionExtensions.GetTypeInfo(reflectionType).GetField("Default", (BindingFlags)1048); if (field != null && field.IsStatic) { attribute = (System.Attribute)field.GetValue((object)null); } else { ConstructorInfo constructor = IntrospectionExtensions.GetTypeInfo(IntrospectionExtensions.GetTypeInfo(reflectionType).UnderlyingSystemType).GetConstructor(new System.Type[0]); if (constructor != null) { attribute = (System.Attribute)constructor.Invoke(new object[0]); if (!attribute.IsDefaultAttribute()) { attribute = null; } } } s_defaultAttributes[(object)attributeType] = attribute; return attribute; } } public System.Collections.IEnumerator GetEnumerator() { return ((System.Array)Attributes).GetEnumerator(); } public bool Matches(System.Attribute attribute) { for (int i = 0; i < Attributes.Length; i++) { if (Attributes[i].Match(attribute)) { return true; } } return false; } public bool Matches(System.Attribute[] attributes) { for (int i = 0; i < attributes.Length; i++) { if (!Matches(attributes[i])) { return false; } } return true; } public void CopyTo(System.Array array, int index) { System.Array.Copy((System.Array)Attributes, 0, array, index, Attributes.Length); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class AttributeProviderAttribute : System.Attribute { private readonly string _typeName; private readonly string _propertyName; public string TypeName => _typeName; public string PropertyName => _propertyName; public AttributeProviderAttribute(string typeName) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (typeName == null) { throw new ArgumentNullException("typeName"); } _typeName = typeName; } public AttributeProviderAttribute(string typeName, string propertyName) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (typeName == null) { throw new ArgumentNullException("typeName"); } if (propertyName == null) { throw new ArgumentNullException("propertyName"); } _typeName = typeName; _propertyName = propertyName; } public AttributeProviderAttribute(System.Type type) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (type == null) { throw new ArgumentNullException("type"); } _typeName = type.AssemblyQualifiedName; } } public delegate void CancelEventHandler(object sender, CancelEventArgs e); public enum CollectionChangeAction { Add = 1, Remove, Refresh } public class CollectionChangeEventArgs : EventArgs { private readonly CollectionChangeAction _action; private readonly object _element; public virtual CollectionChangeAction Action => _action; public virtual object Element => _element; public CollectionChangeEventArgs(CollectionChangeAction action, object element) { _action = action; _element = element; } } public delegate void CollectionChangeEventHandler(object sender, CollectionChangeEventArgs e); internal static class ComponentModelExtensions { private static readonly Dictionary<System.Type, Func<System.Attribute, object>> s_typeId; private static readonly Dictionary<System.Type, Func<System.Attribute, bool>> s_defaultAttributes; public static bool IsDefaultAttribute(this System.Attribute attribute) { Func<System.Attribute, bool> val = default(Func<System.Attribute, bool>); if (s_defaultAttributes.TryGetValue(((object)attribute).GetType(), ref val)) { return val.Invoke(attribute); } return false; } public static object GetTypeId(this System.Attribute attribute) { Func<System.Attribute, object> val = default(Func<System.Attribute, object>); if (!s_typeId.TryGetValue(((object)attribute).GetType(), ref val)) { return ((object)attribute).GetType(); } return val.Invoke(attribute); } public static bool Match(this System.Attribute attribute, object obj) { return ((object)attribute).Equals(obj); } static ComponentModelExtensions() { Dictionary<System.Type, Func<System.Attribute, object>> val = new Dictionary<System.Type, Func<System.Attribute, object>>(); val.Add(typeof(DesignerCategoryAttribute), (Func<System.Attribute, object>)((System.Attribute attr) => ((object)attr).GetType().FullName + ((DesignerCategoryAttribute)attr).Category)); val.Add(typeof(ProvidePropertyAttribute), (Func<System.Attribute, object>)((System.Attribute attr) => ((object)attr).GetType().FullName + ((ProvidePropertyAttribute)attr).PropertyName)); s_typeId = val; Dictionary<System.Type, Func<System.Attribute, bool>> val2 = new Dictionary<System.Type, Func<System.Attribute, bool>>(); val2.Add(typeof(BrowsableAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)BrowsableAttribute.Default))); val2.Add(typeof(CategoryAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((CategoryAttribute)attr).Category.Equals(CategoryAttribute.Default.Category))); val2.Add(typeof(DescriptionAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)DescriptionAttribute.Default))); val2.Add(typeof(DesignOnlyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((DesignOnlyAttribute)attr).IsDesignOnly == DesignOnlyAttribute.Default.IsDesignOnly)); val2.Add(typeof(DisplayNameAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)DisplayNameAttribute.Default))); val2.Add(typeof(ImmutableObjectAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)ImmutableObjectAttribute.Default))); val2.Add(typeof(LocalizableAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((LocalizableAttribute)attr).IsLocalizable == LocalizableAttribute.Default.IsLocalizable)); val2.Add(typeof(MergablePropertyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)MergablePropertyAttribute.Default))); val2.Add(typeof(NotifyParentPropertyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)NotifyParentPropertyAttribute.Default))); val2.Add(typeof(ParenthesizePropertyNameAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)ParenthesizePropertyNameAttribute.Default))); val2.Add(typeof(ReadOnlyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((ReadOnlyAttribute)attr).IsReadOnly == ReadOnlyAttribute.Default.IsReadOnly)); val2.Add(typeof(RefreshPropertiesAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)RefreshPropertiesAttribute.Default))); val2.Add(typeof(DesignerSerializationVisibilityAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)DesignerSerializationVisibilityAttribute.Default))); val2.Add(typeof(ExtenderProvidedPropertyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((ExtenderProvidedPropertyAttribute)attr).ReceiverType == null)); val2.Add(typeof(DesignerCategoryAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)DesignerCategoryAttribute.Default.Category))); s_defaultAttributes = val2; } } public abstract class CustomTypeDescriptor : ICustomTypeDescriptor { private readonly ICustomTypeDescriptor _parent; protected CustomTypeDescriptor() { } protected CustomTypeDescriptor(ICustomTypeDescriptor parent) { _parent = parent; } public virtual AttributeCollection GetAttributes() { if (_parent != null) { return _parent.GetAttributes(); } return AttributeCollection.Empty; } public virtual string GetClassName() { if (_parent != null) { return _parent.GetClassName(); } return null; } public virtual string GetComponentName() { if (_parent != null) { return _parent.GetComponentName(); } return null; } public virtual TypeConverter GetConverter() { if (_parent != null) { return _parent.GetConverter(); } return new TypeConverter(); } public virtual EventDescriptor GetDefaultEvent() { if (_parent != null) { return _parent.GetDefaultEvent(); } return null; } public virtual PropertyDescriptor GetDefaultProperty() { if (_parent != null) { return _parent.GetDefaultProperty(); } return null; } public virtual object GetEditor(System.Type editorBaseType) { if (_parent != null) { return _parent.GetEditor(editorBaseType); } return null; } public virtual EventDescriptorCollection GetEvents() { if (_parent != null) { return _parent.GetEvents(); } return EventDescriptorCollection.Empty; } public virtual EventDescriptorCollection GetEvents(System.Attribute[] attributes) { if (_parent != null) { return _parent.GetEvents(attributes); } return EventDescriptorCollection.Empty; } public virtual PropertyDescriptorCollection GetProperties() { if (_parent != null) { return _parent.GetProperties(); } return PropertyDescriptorCollection.Empty; } public virtual PropertyDescriptorCollection GetProperties(System.Attribute[] attributes) { if (_parent != null) { return _parent.GetProperties(attributes); } return PropertyDescriptorCollection.Empty; } public virtual object GetPropertyOwner(PropertyDescriptor pd) { if (_parent != null) { return _parent.GetPropertyOwner(pd); } return null; } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DefaultEventAttribute : System.Attribute { private readonly string _name; public static readonly DefaultEventAttribute Default = new DefaultEventAttribute(null); public string Name => _name; public DefaultEventAttribute(string name) { _name = name; } public bool Equals(object obj) { if (obj is DefaultEventAttribute defaultEventAttribute) { return defaultEventAttribute.Name == _name; } return false; } public int GetHashCode() { return base.GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DefaultPropertyAttribute : System.Attribute { private readonly string _name; public static readonly DefaultPropertyAttribute Default = new DefaultPropertyAttribute(null); public string Name => _name; public DefaultPropertyAttribute(string name) { _name = name; } public bool Equals(object obj) { if (obj is DefaultPropertyAttribute defaultPropertyAttribute) { return defaultPropertyAttribute.Name == _name; } return false; } public int GetHashCode() { return base.GetHashCode(); } } internal sealed class DelegatingTypeDescriptionProvider : TypeDescriptionProvider { private readonly System.Type _type; internal TypeDescriptionProvider Provider => TypeDescriptor.GetProviderRecursive(_type); internal DelegatingTypeDescriptionProvider(System.Type type) { _type = type; } public override object CreateInstance(IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) { return Provider.CreateInstance(provider, objectType, argTypes, args); } public override IDictionary GetCache(object instance) { return Provider.GetCache(instance); } public override string GetFullComponentName(object component) { return Provider.GetFullComponentName(component); } public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) { return Provider.GetExtendedTypeDescriptor(instance); } protected internal override IExtenderProvider[] GetExtenderProviders(object instance) { return Provider.GetExtenderProviders(instance); } public override System.Type GetReflectionType(System.Type objectType, object instance) { return Provider.GetReflectionType(objectType, instance); } public override System.Type GetRuntimeType(System.Type objectType) { return Provider.GetRuntimeType(objectType); } public override ICustomTypeDescriptor GetTypeDescriptor(System.Type objectType, object instance) { return Provider.GetTypeDescriptor(objectType, instance); } public override bool IsSupportedType(System.Type type) { return Provider.IsSupportedType(type); } } public abstract class EventDescriptor : MemberDescriptor { public abstract System.Type ComponentType { get; } public abstract System.Type EventType { get; } public abstract bool IsMulticast { get; } protected EventDescriptor(string name, System.Attribute[] attrs) : base(name, attrs) { } protected EventDescriptor(MemberDescriptor descr) : base(descr) { } protected EventDescriptor(MemberDescriptor descr, System.Attribute[] attrs) : base(descr, attrs) { } public abstract void AddEventHandler(object component, System.Delegate value); public abstract void RemoveEventHandler(object component, System.Delegate value); } [DefaultMember("Item")] public class EventDescriptorCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { private class ArraySubsetEnumerator : System.Collections.IEnumerator { private readonly System.Array _array; private readonly int _total; private int _current; public object Current { get { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (_current == -1) { throw new InvalidOperationException(); } return _array.GetValue(_current); } } public ArraySubsetEnumerator(System.Array array, int count) { _array = array; _total = count; _current = -1; } public bool MoveNext() { if (_current < _total - 1) { _current++; return true; } return false; } public void Reset() { _current = -1; } } private EventDescriptor[] _events; private string[] _namedSort; private readonly IComparer _comparer; private bool _eventsOwned; private bool _needSort; private int _eventCount; private readonly bool _readOnly; public static readonly EventDescriptorCollection Empty = new EventDescriptorCollection(null, readOnly: true); public int Count => _eventCount; public virtual EventDescriptor this[int index] { get { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (index >= _eventCount) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); return _events[index]; } } public virtual EventDescriptor this[string name] => Find(name, ignoreCase: false); bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => null; object System.Collections.IList.this[int index] { get { return this[index]; } set { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } if (index >= _eventCount) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); _events[index] = (EventDescriptor)value; } } bool System.Collections.IList.IsReadOnly => _readOnly; bool System.Collections.IList.IsFixedSize => _readOnly; public EventDescriptorCollection(EventDescriptor[] events) { _events = events; if (events == null) { _events = new EventDescriptor[0]; _eventCount = 0; } else { _eventCount = _events.Length; } _eventsOwned = true; } public EventDescriptorCollection(EventDescriptor[] events, bool readOnly) : this(events) { _readOnly = readOnly; } private EventDescriptorCollection(EventDescriptor[] events, int eventCount, string[] namedSort, IComparer comparer) { _eventsOwned = false; if (namedSort != null) { _namedSort = (string[])((System.Array)namedSort).Clone(); } _comparer = comparer; _events = events; _eventCount = eventCount; _needSort = true; } public int Add(EventDescriptor value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } EnsureSize(_eventCount + 1); _events[_eventCount++] = value; return _eventCount - 1; } public void Clear() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } _eventCount = 0; } public bool Contains(EventDescriptor value) { return IndexOf(value) >= 0; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { EnsureEventsOwned(); System.Array.Copy((System.Array)_events, 0, array, index, Count); } private void EnsureEventsOwned() { if (!_eventsOwned) { _eventsOwned = true; if (_events != null) { EventDescriptor[] array = new EventDescriptor[Count]; System.Array.Copy((System.Array)_events, 0, (System.Array)array, 0, Count); _events = array; } } if (_needSort) { _needSort = false; InternalSort(_namedSort); } } private void EnsureSize(int sizeNeeded) { if (sizeNeeded > _events.Length) { if (_events == null || _events.Length == 0) { _eventCount = 0; _events = new EventDescriptor[sizeNeeded]; return; } EnsureEventsOwned(); int num = Math.Max(sizeNeeded, _events.Length * 2); EventDescriptor[] array = new EventDescriptor[num]; System.Array.Copy((System.Array)_events, 0, (System.Array)array, 0, _eventCount); _events = array; } } public virtual EventDescriptor Find(string name, bool ignoreCase) { EventDescriptor result = null; if (ignoreCase) { for (int i = 0; i < Count; i++) { if (string.Equals(_events[i].Name, name, (StringComparison)5)) { result = _events[i]; break; } } } else { for (int j = 0; j < Count; j++) { if (string.Equals(_events[j].Name, name, (StringComparison)4)) { result = _events[j]; break; } } } return result; } public int IndexOf(EventDescriptor value) { return System.Array.IndexOf<EventDescriptor>(_events, value, 0, _eventCount); } public void Insert(int index, EventDescriptor value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } EnsureSize(_eventCount + 1); if (index < _eventCount) { System.Array.Copy((System.Array)_events, index, (System.Array)_events, index + 1, _eventCount - index); } _events[index] = value; _eventCount++; } public void Remove(EventDescriptor value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } int num = IndexOf(value); if (num != -1) { RemoveAt(num); } } public void RemoveAt(int index) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } if (index < _eventCount - 1) { System.Array.Copy((System.Array)_events, index + 1, (System.Array)_events, index, _eventCount - index - 1); } _events[_eventCount - 1] = null; _eventCount--; } public System.Collections.IEnumerator GetEnumerator() { if (_events.Length == _eventCount) { return ((System.Array)_events).GetEnumerator(); } return new ArraySubsetEnumerator(_events, _eventCount); } public virtual EventDescriptorCollection Sort() { return new EventDescriptorCollection(_events, _eventCount, _namedSort, _comparer); } public virtual EventDescriptorCollection Sort(string[] names) { return new EventDescriptorCollection(_events, _eventCount, names, _comparer); } public virtual EventDescriptorCollection Sort(string[] names, IComparer comparer) { return new EventDescriptorCollection(_events, _eventCount, names, comparer); } public virtual EventDescriptorCollection Sort(IComparer comparer) { return new EventDescriptorCollection(_events, _eventCount, _namedSort, comparer); } protected void InternalSort(string[] names) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown if (_events == null || _events.Length == 0) { return; } InternalSort(_comparer); if (names == null || names.Length == 0) { return; } ArrayList val = new ArrayList((System.Collections.ICollection)(object)_events); int num = 0; int num2 = _events.Length; for (int i = 0; i < names.Length; i++) { for (int j = 0; j < num2; j++) { EventDescriptor eventDescriptor = (EventDescriptor)val[j]; if (eventDescriptor != null && eventDescriptor.Name.Equals(names[i])) { _events[num++] = eventDescriptor; val[j] = null; break; } } } for (int k = 0; k < num2; k++) { if (val[k] != null) { _events[num++] = (EventDescriptor)val[k]; } } } protected void InternalSort(IComparer sorter) { if (sorter == null) { TypeDescriptor.SortDescriptorArray(this); } else { System.Array.Sort((System.Array)_events, sorter); } } int System.Collections.IList.Add(object value) { return Add((EventDescriptor)value); } bool System.Collections.IList.Contains(object value) { return Contains((EventDescriptor)value); } int System.Collections.IList.IndexOf(object value) { return IndexOf((EventDescriptor)value); } void System.Collections.IList.Insert(int index, object value) { Insert(index, (EventDescriptor)value); } void System.Collections.IList.Remove(object value) { Remove((EventDescriptor)value); } } internal sealed class ExtendedPropertyDescriptor : PropertyDescriptor { private readonly ReflectPropertyDescriptor _extenderInfo; private readonly IExtenderProvider _provider; public override System.Type ComponentType => _extenderInfo.ComponentType; public override bool IsReadOnly => ((object)Attributes[typeof(ReadOnlyAttribute)]).Equals((object)ReadOnlyAttribute.Yes); public override System.Type PropertyType => _extenderInfo.ExtenderGetType(_provider); public override string DisplayName { get { string text = base.DisplayName; System.Attribute attribute = Attributes[typeof(DisplayNameAttribute)]; DisplayNameAttribute val = (DisplayNameAttribute)(object)((attribute is DisplayNameAttribute) ? attribute : null); if (val == null || ((System.Attribute)(object)val).IsDefaultAttribute()) { ISite site = MemberDescriptor.GetSite(_provider); if (site != null) { string name = site.Name; if (name != null && name.Length > 0) { text = string.Format(System.SR.MetaExtenderName, (object)text, (object)name); } } } return text; } } public ExtendedPropertyDescriptor(ReflectPropertyDescriptor extenderInfo, System.Type receiverType, IExtenderProvider provider, System.Attribute[] attributes) : base(extenderInfo, attributes) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown ArrayList val = new ArrayList((System.Collections.ICollection)(object)AttributeArray); val.Add((object)ExtenderProvidedPropertyAttribute.Create(extenderInfo, receiverType, provider)); if (extenderInfo.IsReadOnly) { val.Add((object)ReadOnlyAttribute.Yes); } System.Attribute[] array = new System.Attribute[val.Count]; val.CopyTo((System.Array)array, 0); AttributeArray = array; _extenderInfo = extenderInfo; _provider = provider; } public ExtendedPropertyDescriptor(PropertyDescriptor extender, System.Attribute[] attributes) : base(extender, attributes) { ExtenderProvidedPropertyAttribute extenderProvidedPropertyAttribute = extender.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute; ReflectPropertyDescriptor extenderInfo = extenderProvidedPropertyAttribute.ExtenderProperty as ReflectPropertyDescriptor; _extenderInfo = extenderInfo; _provider = extenderProvidedPropertyAttribute.Provider; } public override bool CanResetValue(object comp) { return _extenderInfo.ExtenderCanResetValue(_provider, comp); } public override object GetValue(object comp) { return _extenderInfo.ExtenderGetValue(_provider, comp); } public override void ResetValue(object comp) { _extenderInfo.ExtenderResetValue(_provider, comp, this); } public override void SetValue(object component, object value)
BepInEx/plugins/VNyanCommands/System.IO.FileSystem.Primitives.dll
Decompiled 2 years agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: AssemblyTitle("System.IO.FileSystem.Primitives")] [assembly: AssemblyDescription("System.IO.FileSystem.Primitives")] [assembly: AssemblyDefaultAlias("System.IO.FileSystem.Primitives")] [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 System.IO; [Flags] public enum FileAccess { Read = 1, Write = 2, ReadWrite = 3 } [Flags] public enum FileAttributes { ReadOnly = 1, Hidden = 2, System = 4, Directory = 0x10, Archive = 0x20, Device = 0x40, Normal = 0x80, Temporary = 0x100, SparseFile = 0x200, ReparsePoint = 0x400, Compressed = 0x800, Offline = 0x1000, NotContentIndexed = 0x2000, Encrypted = 0x4000, IntegrityStream = 0x8000, NoScrubData = 0x20000 } public enum FileMode { CreateNew = 1, Create, Open, OpenOrCreate, Truncate, Append } [Flags] public enum FileShare { None = 0, Read = 1, Write = 2, ReadWrite = 3, Delete = 4, Inheritable = 0x10 }
BepInEx/plugins/VNyanCommands/System.Linq.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using FxResources.System.Linq; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Linq")] [assembly: AssemblyDescription("System.Linq")] [assembly: AssemblyDefaultAlias("System.Linq")] [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.1.1.0")] namespace FxResources.System.Linq { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Linq.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 EmptyEnumerable => GetResourceString("EmptyEnumerable", null); internal static string MoreThanOneElement => GetResourceString("MoreThanOneElement", null); internal static string MoreThanOneMatch => GetResourceString("MoreThanOneMatch", null); internal static string NoElements => GetResourceString("NoElements", null); internal static string NoMatch => GetResourceString("NoMatch", null); internal static System.Type ResourceType => typeof(FxResources.System.Linq.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.Linq { public static class Enumerable { private abstract class AppendPrependIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { protected readonly System.Collections.Generic.IEnumerable<TSource> _source; protected System.Collections.Generic.IEnumerator<TSource> _enumerator; protected AppendPrependIterator(System.Collections.Generic.IEnumerable<TSource> source) { _source = source; } protected void GetSourceEnumerator() { _enumerator = _source.GetEnumerator(); } public abstract AppendPrependIterator<TSource> Append(TSource item); public abstract AppendPrependIterator<TSource> Prepend(TSource item); protected bool LoadFromEnumerator() { if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _enumerator.Current; return true; } Dispose(); return false; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public abstract TSource[] ToArray(); public abstract List<TSource> ToList(); public abstract int GetCount(bool onlyIfCheap); } private class AppendPrepend1Iterator<TSource> : AppendPrependIterator<TSource> { private readonly TSource _item; private readonly bool _appending; public AppendPrepend1Iterator(System.Collections.Generic.IEnumerable<TSource> source, TSource item, bool appending) : base(source) { _item = item; _appending = appending; } public override Iterator<TSource> Clone() { return new AppendPrepend1Iterator<TSource>(_source, _item, _appending); } public override bool MoveNext() { switch (_state) { case 1: _state = 2; if (!_appending) { _current = _item; return true; } goto case 2; case 2: GetSourceEnumerator(); _state = 3; goto case 3; case 3: if (LoadFromEnumerator()) { return true; } if (_appending) { _current = _item; return true; } break; } Dispose(); return false; } public override AppendPrependIterator<TSource> Append(TSource item) { if (_appending) { return new AppendPrependN<TSource>(_source, null, new SingleLinkedNode<TSource>(_item, item)); } return new AppendPrependN<TSource>(_source, new SingleLinkedNode<TSource>(_item), new SingleLinkedNode<TSource>(item)); } public override AppendPrependIterator<TSource> Prepend(TSource item) { if (_appending) { return new AppendPrependN<TSource>(_source, new SingleLinkedNode<TSource>(item), new SingleLinkedNode<TSource>(_item)); } return new AppendPrependN<TSource>(_source, new SingleLinkedNode<TSource>(_item, item), null); } public override TSource[] ToArray() { int count = GetCount(onlyIfCheap: true); if (count == -1) { return EnumerableHelpers.ToArray(this); } TSource[] array = new TSource[count]; int num; if (_appending) { num = 0; } else { array[0] = _item; num = 1; } if (_source is System.Collections.Generic.ICollection<TSource> collection) { collection.CopyTo(array, num); } else { System.Collections.Generic.IEnumerator<TSource> enumerator = _source.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; array[num] = current; num++; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } if (_appending) { array[array.Length - 1] = _item; } return array; } public override List<TSource> ToList() { int count = GetCount(onlyIfCheap: true); List<TSource> val = ((count == -1) ? new List<TSource>() : new List<TSource>(count)); if (!_appending) { val.Add(_item); } val.AddRange(_source); if (_appending) { val.Add(_item); } return val; } public override int GetCount(bool onlyIfCheap) { if (_source is IIListProvider<TSource> iIListProvider) { int count = iIListProvider.GetCount(onlyIfCheap); if (count != -1) { return count + 1; } return -1; } if (onlyIfCheap && !(_source is System.Collections.Generic.ICollection<TSource>)) { return -1; } return _source.Count() + 1; } } private sealed class SingleLinkedNode<TSource> { public TSource Item { [CompilerGenerated] get; } public SingleLinkedNode<TSource> Linked { [CompilerGenerated] get; } public int Count { [CompilerGenerated] get; } public SingleLinkedNode(TSource first, TSource second) { Linked = new SingleLinkedNode<TSource>(first); Item = second; Count = 2; } public SingleLinkedNode(TSource item) { Item = item; Count = 1; } private SingleLinkedNode(SingleLinkedNode<TSource> linked, TSource item) { Linked = linked; Item = item; Count = linked.Count + 1; } public SingleLinkedNode<TSource> Add(TSource item) { return new SingleLinkedNode<TSource>(this, item); } public System.Collections.Generic.IEnumerator<TSource> GetEnumerator() { TSource[] array = new TSource[Count]; int num = Count; for (SingleLinkedNode<TSource> singleLinkedNode = this; singleLinkedNode != null; singleLinkedNode = singleLinkedNode.Linked) { num--; array[num] = singleLinkedNode.Item; } return ((System.Collections.Generic.IEnumerable<TSource>)array).GetEnumerator(); } } private class AppendPrependN<TSource> : AppendPrependIterator<TSource> { private readonly SingleLinkedNode<TSource> _prepended; private readonly SingleLinkedNode<TSource> _appended; private SingleLinkedNode<TSource> _node; public AppendPrependN(System.Collections.Generic.IEnumerable<TSource> source, SingleLinkedNode<TSource> prepended, SingleLinkedNode<TSource> appended) : base(source) { _prepended = prepended; _appended = appended; } public override Iterator<TSource> Clone() { return new AppendPrependN<TSource>(_source, _prepended, _appended); } public override bool MoveNext() { switch (_state) { case 1: _node = _prepended; _state = 2; goto case 2; case 2: if (_node != null) { _current = _node.Item; _node = _node.Linked; return true; } GetSourceEnumerator(); _state = 3; goto case 3; case 3: if (LoadFromEnumerator()) { return true; } if (_appended == null) { return false; } _enumerator = _appended.GetEnumerator(); _state = 4; goto case 4; case 4: return LoadFromEnumerator(); default: Dispose(); return false; } } public override AppendPrependIterator<TSource> Append(TSource item) { return new AppendPrependN<TSource>(_source, _prepended, (_appended != null) ? _appended.Add(item) : new SingleLinkedNode<TSource>(item)); } public override AppendPrependIterator<TSource> Prepend(TSource item) { return new AppendPrependN<TSource>(_source, (_prepended != null) ? _prepended.Add(item) : new SingleLinkedNode<TSource>(item), _appended); } public override TSource[] ToArray() { int count = GetCount(onlyIfCheap: true); if (count == -1) { return EnumerableHelpers.ToArray(this); } TSource[] array = new TSource[count]; int num = 0; for (SingleLinkedNode<TSource> singleLinkedNode = _prepended; singleLinkedNode != null; singleLinkedNode = singleLinkedNode.Linked) { array[num] = singleLinkedNode.Item; num++; } if (_source is System.Collections.Generic.ICollection<TSource> collection) { collection.CopyTo(array, num); } else { System.Collections.Generic.IEnumerator<TSource> enumerator = _source.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; array[num] = current; num++; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } num = array.Length; for (SingleLinkedNode<TSource> singleLinkedNode2 = _appended; singleLinkedNode2 != null; singleLinkedNode2 = singleLinkedNode2.Linked) { num--; array[num] = singleLinkedNode2.Item; } return array; } public override List<TSource> ToList() { int count = GetCount(onlyIfCheap: true); List<TSource> val = ((count == -1) ? new List<TSource>() : new List<TSource>(count)); for (SingleLinkedNode<TSource> singleLinkedNode = _prepended; singleLinkedNode != null; singleLinkedNode = singleLinkedNode.Linked) { val.Add(singleLinkedNode.Item); } val.AddRange(_source); if (_appended != null) { System.Collections.Generic.IEnumerator<TSource> enumerator = _appended.GetEnumerator(); while (((System.Collections.IEnumerator)enumerator).MoveNext()) { val.Add(enumerator.Current); } } return val; } public override int GetCount(bool onlyIfCheap) { if (_source is IIListProvider<TSource> iIListProvider) { int count = iIListProvider.GetCount(onlyIfCheap); if (count != -1) { return count + ((_appended != null) ? _appended.Count : 0) + ((_prepended != null) ? _prepended.Count : 0); } return -1; } if (onlyIfCheap && !(_source is System.Collections.Generic.ICollection<TSource>)) { return -1; } return _source.Count() + ((_appended != null) ? _appended.Count : 0) + ((_prepended != null) ? _prepended.Count : 0); } } private sealed class Concat2Iterator<TSource> : ConcatIterator<TSource> { private readonly System.Collections.Generic.IEnumerable<TSource> _first; private readonly System.Collections.Generic.IEnumerable<TSource> _second; internal Concat2Iterator(System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second) { _first = first; _second = second; } public override Iterator<TSource> Clone() { return new Concat2Iterator<TSource>(_first, _second); } internal override ConcatIterator<TSource> Concat(System.Collections.Generic.IEnumerable<TSource> next) { return new ConcatNIterator<TSource>(this, next, 2); } internal override System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index) { return index switch { 0 => _first, 1 => _second, _ => null, }; } } private sealed class ConcatNIterator<TSource> : ConcatIterator<TSource> { private readonly ConcatIterator<TSource> _previousConcat; private readonly System.Collections.Generic.IEnumerable<TSource> _next; private readonly int _nextIndex; internal ConcatNIterator(ConcatIterator<TSource> previousConcat, System.Collections.Generic.IEnumerable<TSource> next, int nextIndex) { _previousConcat = previousConcat; _next = next; _nextIndex = nextIndex; } public override Iterator<TSource> Clone() { return new ConcatNIterator<TSource>(_previousConcat, _next, _nextIndex); } internal override ConcatIterator<TSource> Concat(System.Collections.Generic.IEnumerable<TSource> next) { if (_nextIndex == 2147483645) { return new Concat2Iterator<TSource>(this, next); } return new ConcatNIterator<TSource>(this, next, _nextIndex + 1); } internal override System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index) { if (index > _nextIndex) { return null; } ConcatNIterator<TSource> concatNIterator = this; while (true) { if (index == concatNIterator._nextIndex) { return concatNIterator._next; } if (!(concatNIterator._previousConcat is ConcatNIterator<TSource> concatNIterator2)) { break; } concatNIterator = concatNIterator2; } return concatNIterator._previousConcat.GetEnumerable(index); } } private abstract class ConcatIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private System.Collections.Generic.IEnumerator<TSource> _enumerator; public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } internal abstract System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index); internal abstract ConcatIterator<TSource> Concat(System.Collections.Generic.IEnumerable<TSource> next); public override bool MoveNext() { if (_state == 1) { _enumerator = GetEnumerable(0).GetEnumerator(); _state = 2; } if (_state > 1) { while (true) { if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _enumerator.Current; return true; } System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(_state++ - 1); if (enumerable == null) { break; } ((System.IDisposable)_enumerator).Dispose(); _enumerator = enumerable.GetEnumerator(); } Dispose(); } return false; } public TSource[] ToArray() { return EnumerableHelpers.ToArray(this); } public List<TSource> ToList() { List<TSource> val = new List<TSource>(); int num = 0; while (true) { System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(num); if (enumerable == null) { break; } val.AddRange(enumerable); num++; } return val; } public int GetCount(bool onlyIfCheap) { if (onlyIfCheap) { return -1; } int num = 0; int num2 = 0; while (true) { System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(num2); if (enumerable == null) { break; } num = checked(num + enumerable.Count()); num2++; } return num; } } private sealed class DefaultIfEmptyIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly TSource _default; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public DefaultIfEmptyIterator(System.Collections.Generic.IEnumerable<TSource> source, TSource defaultValue) { _source = source; _default = defaultValue; } public override Iterator<TSource> Clone() { return new DefaultIfEmptyIterator<TSource>(_source, _default); } public override bool MoveNext() { switch (_state) { case 1: _enumerator = _source.GetEnumerator(); if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _enumerator.Current; _state = 2; } else { _current = _default; _state = -1; } return true; case 2: if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _enumerator.Current; return true; } break; } Dispose(); return false; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public TSource[] ToArray() { TSource[] array = _source.ToArray(); if (array.Length != 0) { return array; } return new TSource[1] { _default }; } public List<TSource> ToList() { List<TSource> val = _source.ToList(); if (val.Count == 0) { val.Add(_default); } return val; } public int GetCount(bool onlyIfCheap) { int num = ((onlyIfCheap && !(_source is System.Collections.Generic.ICollection<TSource>) && !(_source is System.Collections.ICollection)) ? ((!(_source is IIListProvider<TSource> iIListProvider)) ? (-1) : iIListProvider.GetCount(onlyIfCheap: true)) : _source.Count()); if (num != 0) { return num; } return 1; } } private sealed class DistinctIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly IEqualityComparer<TSource> _comparer; private Set<TSource> _set; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public DistinctIterator(System.Collections.Generic.IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) { _source = source; _comparer = comparer; } public override Iterator<TSource> Clone() { return new DistinctIterator<TSource>(_source, _comparer); } public override bool MoveNext() { int state = _state; TSource current; if (state != 1) { if (state == 2) { while (((System.Collections.IEnumerator)_enumerator).MoveNext()) { current = _enumerator.Current; if (_set.Add(current)) { _current = current; return true; } } } Dispose(); return false; } _enumerator = _source.GetEnumerator(); if (!((System.Collections.IEnumerator)_enumerator).MoveNext()) { Dispose(); return false; } current = _enumerator.Current; _set = new Set<TSource>(_comparer); _set.Add(current); _current = current; _state = 2; return true; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; _set = null; } base.Dispose(); } private Set<TSource> FillSet() { Set<TSource> set = new Set<TSource>(_comparer); System.Collections.Generic.IEnumerator<TSource> enumerator = _source.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; set.Add(current); } return set; } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public TSource[] ToArray() { return FillSet().ToArray(); } public List<TSource> ToList() { return FillSet().ToList(); } public int GetCount(bool onlyIfCheap) { if (!onlyIfCheap) { return FillSet().Count; } return -1; } } internal abstract class Iterator<TSource> : System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TSource>, System.Collections.IEnumerator, System.IDisposable { private readonly int _threadId; internal int _state; internal TSource _current; public TSource Current => _current; object System.Collections.IEnumerator.Current => Current; protected Iterator() { _threadId = Environment.CurrentManagedThreadId; } public abstract Iterator<TSource> Clone(); public virtual void Dispose() { _current = default(TSource); _state = -1; } public System.Collections.Generic.IEnumerator<TSource> GetEnumerator() { Iterator<TSource> iterator = ((_state == 0 && _threadId == Environment.CurrentManagedThreadId) ? this : Clone()); iterator._state = 1; return iterator; } public abstract bool MoveNext(); public virtual System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new SelectEnumerableIterator<TSource, TResult>(this, selector); } public virtual System.Collections.Generic.IEnumerable<TSource> Where(Func<TSource, bool> predicate) { return new WhereEnumerableIterator<TSource>(this, predicate); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } void System.Collections.IEnumerator.Reset() { throw Error.NotSupported(); } } private sealed class ListPartition<TSource> : Iterator<TSource>, IPartition<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IList<TSource> _source; private readonly int _minIndexInclusive; private readonly int _maxIndexInclusive; private int _index; private int Count { get { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; if (count <= _minIndexInclusive) { return 0; } return Math.Min(count - 1, _maxIndexInclusive) - _minIndexInclusive + 1; } } public ListPartition(System.Collections.Generic.IList<TSource> source, int minIndexInclusive, int maxIndexInclusive) { _source = source; _minIndexInclusive = minIndexInclusive; _maxIndexInclusive = maxIndexInclusive; _index = minIndexInclusive; } public override Iterator<TSource> Clone() { return new ListPartition<TSource>(_source, _minIndexInclusive, _maxIndexInclusive); } public override bool MoveNext() { if (((_state == 1) & (_index <= _maxIndexInclusive)) && _index < ((System.Collections.Generic.ICollection<TSource>)_source).Count) { _current = _source[_index]; _index++; return true; } Dispose(); return false; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new SelectListPartitionIterator<TSource, TResult>(_source, selector, _minIndexInclusive, _maxIndexInclusive); } public IPartition<TSource> Skip(int count) { int num = _minIndexInclusive + count; if ((uint)num <= (uint)_maxIndexInclusive) { return new ListPartition<TSource>(_source, num, _maxIndexInclusive); } return EmptyPartition<TSource>.Instance; } public IPartition<TSource> Take(int count) { int num = _minIndexInclusive + count - 1; if ((uint)num < (uint)_maxIndexInclusive) { return new ListPartition<TSource>(_source, _minIndexInclusive, num); } return this; } public TSource TryGetElementAt(int index, out bool found) { if ((uint)index <= (uint)(_maxIndexInclusive - _minIndexInclusive) && index < ((System.Collections.Generic.ICollection<TSource>)_source).Count - _minIndexInclusive) { found = true; return _source[_minIndexInclusive + index]; } found = false; return default(TSource); } public TSource TryGetFirst(out bool found) { if (((System.Collections.Generic.ICollection<TSource>)_source).Count > _minIndexInclusive) { found = true; return _source[_minIndexInclusive]; } found = false; return default(TSource); } public TSource TryGetLast(out bool found) { int num = ((System.Collections.Generic.ICollection<TSource>)_source).Count - 1; if (num >= _minIndexInclusive) { found = true; return _source[Math.Min(num, _maxIndexInclusive)]; } found = false; return default(TSource); } public TSource[] ToArray() { int count = Count; if (count == 0) { return System.Array.Empty<TSource>(); } TSource[] array = new TSource[count]; int num = 0; int num2 = _minIndexInclusive; while (num != array.Length) { array[num] = _source[num2]; num++; num2++; } return array; } public List<TSource> ToList() { int count = Count; if (count == 0) { return new List<TSource>(); } List<TSource> val = new List<TSource>(count); int num = _minIndexInclusive + count; for (int i = _minIndexInclusive; i != num; i++) { val.Add(_source[i]); } return val; } public int GetCount(bool onlyIfCheap) { return Count; } } private sealed class RangeIterator : Iterator<int>, IPartition<int>, IIListProvider<int>, System.Collections.Generic.IEnumerable<int>, System.Collections.IEnumerable { private readonly int _start; private readonly int _end; public RangeIterator(int start, int count) { _start = start; _end = start + count; } public override Iterator<int> Clone() { return new RangeIterator(_start, _end - _start); } public override bool MoveNext() { switch (_state) { case 1: _current = _start; _state = 2; return true; case 2: if (++_current != _end) { return true; } break; } _state = -1; return false; } public override void Dispose() { _state = -1; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<int, TResult> selector) { return new SelectIPartitionIterator<int, TResult>(this, selector); } public int[] ToArray() { int[] array = new int[_end - _start]; int num = _start; for (int i = 0; i != array.Length; i++) { array[i] = num; num++; } return array; } public List<int> ToList() { List<int> val = new List<int>(_end - _start); for (int i = _start; i != _end; i++) { val.Add(i); } return val; } public int GetCount(bool onlyIfCheap) { return _end - _start; } public IPartition<int> Skip(int count) { if (count >= _end - _start) { return EmptyPartition<int>.Instance; } return new RangeIterator(_start + count, _end - _start - count); } public IPartition<int> Take(int count) { int num = _end - _start; if (count >= num) { return this; } return new RangeIterator(_start, count); } public int TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)(_end - _start)) { found = true; return _start + index; } found = false; return 0; } public int TryGetFirst(out bool found) { found = true; return _start; } public int TryGetLast(out bool found) { found = true; return _end - 1; } } private sealed class RepeatIterator<TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly int _count; private int _sent; public RepeatIterator(TResult element, int count) { _current = element; _count = count; } public override Iterator<TResult> Clone() { return new RepeatIterator<TResult>(_current, _count); } public override void Dispose() { _state = -1; } public override bool MoveNext() { if ((_state == 1) & (_sent != _count)) { _sent++; return true; } _state = -1; return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectIPartitionIterator<TResult, TResult2>(this, selector); } public TResult[] ToArray() { TResult[] array = new TResult[_count]; if (_current != null) { for (int i = 0; i != array.Length; i++) { array[i] = _current; } } return array; } public List<TResult> ToList() { List<TResult> val = new List<TResult>(_count); for (int i = 0; i != _count; i++) { val.Add(_current); } return val; } public int GetCount(bool onlyIfCheap) { return _count; } public IPartition<TResult> Skip(int count) { if (count >= _count) { return EmptyPartition<TResult>.Instance; } return new RepeatIterator<TResult>(_current, _count - count); } public IPartition<TResult> Take(int count) { if (count >= _count) { return this; } return new RepeatIterator<TResult>(_current, count); } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)_count) { found = true; return _current; } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { found = true; return _current; } public TResult TryGetLast(out bool found) { found = true; return _current; } } private sealed class ReverseIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private TSource[] _buffer; private int _index; public ReverseIterator(System.Collections.Generic.IEnumerable<TSource> source) { _source = source; } public override Iterator<TSource> Clone() { return new ReverseIterator<TSource>(_source); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_006f; } } else { Buffer<TSource> buffer = new Buffer<TSource>(_source); _buffer = buffer._items; _index = buffer._count - 1; _state = 2; } if (_index != -1) { _current = _buffer[_index]; _index--; return true; } goto IL_006f; IL_006f: Dispose(); return false; } public override void Dispose() { _buffer = null; base.Dispose(); } public TSource[] ToArray() { TSource[] array = _source.ToArray(); int num = 0; int num2 = array.Length - 1; while (num < num2) { TSource val = array[num]; array[num] = array[num2]; array[num2] = val; num++; num2--; } return array; } public List<TSource> ToList() { List<TSource> val = _source.ToList(); val.Reverse(); return val; } public int GetCount(bool onlyIfCheap) { if (onlyIfCheap) { if (_source is IIListProvider<TSource> iIListProvider) { return iIListProvider.GetCount(onlyIfCheap: true); } if (!(_source is System.Collections.Generic.ICollection<TSource>) && !(_source is System.Collections.ICollection)) { return -1; } } return _source.Count(); } } internal sealed class SelectEnumerableIterator<TSource, TResult> : Iterator<TResult> { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly Func<TSource, TResult> _selector; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public SelectEnumerableIterator(System.Collections.Generic.IEnumerable<TSource> source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectEnumerableIterator<TSource, TResult>(_source, _selector); } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_005a; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _selector.Invoke(_enumerator.Current); return true; } Dispose(); goto IL_005a; IL_005a: return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectEnumerableIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } } internal sealed class SelectArrayIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly TSource[] _source; private readonly Func<TSource, TResult> _selector; private int _index; public SelectArrayIterator(TSource[] source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectArrayIterator<TSource, TResult>(_source, _selector); } public override bool MoveNext() { if (_state == 1 && _index < _source.Length) { _current = _selector.Invoke(_source[_index++]); return true; } Dispose(); return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectArrayIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } public TResult[] ToArray() { if (_source.Length == 0) { return System.Array.Empty<TResult>(); } TResult[] array = new TResult[_source.Length]; for (int i = 0; i < array.Length; i++) { array[i] = _selector.Invoke(_source[i]); } return array; } public List<TResult> ToList() { TSource[] source = _source; List<TResult> val = (List<TResult>)(object)new List<?>(source.Length); for (int i = 0; i < source.Length; i++) { ((List<?>)(object)val).Add(_selector.Invoke(source[i])); } return val; } public int GetCount(bool onlyIfCheap) { return _source.Length; } public IPartition<TResult> Skip(int count) { if (count >= _source.Length) { return EmptyPartition<TResult>.Instance; } return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, count, 2147483647); } public IPartition<TResult> Take(int count) { if (count < _source.Length) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1); } return this; } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)_source.Length) { found = true; return _selector.Invoke(_source[index]); } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { if (_source.Length != 0) { found = true; return _selector.Invoke(_source[0]); } found = false; return default(TResult); } public TResult TryGetLast(out bool found) { int num = _source.Length; if (num != 0) { found = true; return _selector.Invoke(_source[num - 1]); } found = false; return default(TResult); } } internal sealed class SelectListIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly List<TSource> _source; private readonly Func<TSource, TResult> _selector; private Enumerator<TSource> _enumerator; public SelectListIterator(List<TSource> source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectListIterator<TSource, TResult>(_source, _selector); } public override bool MoveNext() { //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) int state = _state; if (state != 1) { if (state != 2) { goto IL_005a; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } if (_enumerator.MoveNext()) { _current = _selector.Invoke(_enumerator.Current); return true; } Dispose(); goto IL_005a; IL_005a: return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectListIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } public TResult[] ToArray() { int count = _source.Count; if (count == 0) { return System.Array.Empty<TResult>(); } TResult[] array = new TResult[count]; for (int i = 0; i < array.Length; i++) { array[i] = _selector.Invoke(_source[i]); } return array; } public List<TResult> ToList() { int count = _source.Count; List<TResult> val = (List<TResult>)(object)new List<?>(count); for (int i = 0; i < count; i++) { ((List<?>)(object)val).Add(_selector.Invoke(_source[i])); } return val; } public int GetCount(bool onlyIfCheap) { return _source.Count; } public IPartition<TResult> Skip(int count) { return new SelectListPartitionIterator<TSource, TResult>((System.Collections.Generic.IList<TSource>)_source, _selector, count, 2147483647); } public IPartition<TResult> Take(int count) { return new SelectListPartitionIterator<TSource, TResult>((System.Collections.Generic.IList<TSource>)_source, _selector, 0, count - 1); } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)_source.Count) { found = true; return _selector.Invoke(_source[index]); } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { if (_source.Count != 0) { found = true; return _selector.Invoke(_source[0]); } found = false; return default(TResult); } public TResult TryGetLast(out bool found) { int count = _source.Count; if (count != 0) { found = true; return _selector.Invoke(_source[count - 1]); } found = false; return default(TResult); } } internal sealed class SelectIListIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IList<TSource> _source; private readonly Func<TSource, TResult> _selector; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public SelectIListIterator(System.Collections.Generic.IList<TSource> source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectIListIterator<TSource, TResult>(_source, _selector); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_005a; } } else { _enumerator = ((System.Collections.Generic.IEnumerable<TSource>)_source).GetEnumerator(); _state = 2; } if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _selector.Invoke(_enumerator.Current); return true; } Dispose(); goto IL_005a; IL_005a: return false; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectIListIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } public TResult[] ToArray() { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; if (count == 0) { return System.Array.Empty<TResult>(); } TResult[] array = new TResult[count]; for (int i = 0; i < array.Length; i++) { array[i] = _selector.Invoke(_source[i]); } return array; } public List<TResult> ToList() { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; List<TResult> val = (List<TResult>)(object)new List<?>(count); for (int i = 0; i < count; i++) { ((List<?>)(object)val).Add(_selector.Invoke(_source[i])); } return val; } public int GetCount(bool onlyIfCheap) { return ((System.Collections.Generic.ICollection<TSource>)_source).Count; } public IPartition<TResult> Skip(int count) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, count, 2147483647); } public IPartition<TResult> Take(int count) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1); } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)((System.Collections.Generic.ICollection<TSource>)_source).Count) { found = true; return _selector.Invoke(_source[index]); } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { if (((System.Collections.Generic.ICollection<TSource>)_source).Count != 0) { found = true; return _selector.Invoke(_source[0]); } found = false; return default(TResult); } public TResult TryGetLast(out bool found) { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; if (count != 0) { found = true; return _selector.Invoke(_source[count - 1]); } found = false; return default(TResult); } } internal sealed class SelectIPartitionIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly IPartition<TSource> _source; private readonly Func<TSource, TResult> _selector; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public SelectIPartitionIterator(IPartition<TSource> source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectIPartitionIterator<TSource, TResult>(_source, _selector); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_005a; } } else { _enumerator = ((System.Collections.Generic.IEnumerable<TSource>)_source).GetEnumerator(); _state = 2; } if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _selector.Invoke(_enumerator.Current); return true; } Dispose(); goto IL_005a; IL_005a: return false; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectIPartitionIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } public IPartition<TResult> Skip(int count) { return new SelectIPartitionIterator<TSource, TResult>(_source.Skip(count), _selector); } public IPartition<TResult> Take(int count) { return new SelectIPartitionIterator<TSource, TResult>(_source.Take(count), _selector); } public TResult TryGetElementAt(int index, out bool found) { bool found2; TSource val = _source.TryGetElementAt(index, out found2); found = found2; if (!found2) { return default(TResult); } return _selector.Invoke(val); } public TResult TryGetFirst(out bool found) { bool found2; TSource val = _source.TryGetFirst(out found2); found = found2; if (!found2) { return default(TResult); } return _selector.Invoke(val); } public TResult TryGetLast(out bool found) { bool found2; TSource val = _source.TryGetLast(out found2); found = found2; if (!found2) { return default(TResult); } return _selector.Invoke(val); } public TResult[] ToArray() { int count = _source.GetCount(onlyIfCheap: true); switch (count) { case -1: return EnumerableHelpers.ToArray(this); case 0: return System.Array.Empty<TResult>(); default: { TResult[] array = new TResult[count]; int num = 0; System.Collections.Generic.IEnumerator<TSource> enumerator = ((System.Collections.Generic.IEnumerable<TSource>)_source).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; array[num] = _selector.Invoke(current); num++; } return array; } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } } public List<TResult> ToList() { int count = _source.GetCount(onlyIfCheap: true); List<TResult> val; switch (count) { case -1: val = (List<TResult>)(object)new List<?>(); break; case 0: return (List<TResult>)(object)new List<?>(); default: val = (List<TResult>)(object)new List<?>(count); break; } System.Collections.Generic.IEnumerator<TSource> enumerator = ((System.Collections.Generic.IEnumerable<TSource>)_source).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; ((List<?>)(object)val).Add(_selector.Invoke(current)); } return val; } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public int GetCount(bool onlyIfCheap) { return _source.GetCount(onlyIfCheap); } } private sealed class SelectListPartitionIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IList<TSource> _source; private readonly Func<TSource, TResult> _selector; private readonly int _minIndexInclusive; private readonly int _maxIndexInclusive; private int _index; private int Count { get { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; if (count <= _minIndexInclusive) { return 0; } return Math.Min(count - 1, _maxIndexInclusive) - _minIndexInclusive + 1; } } public SelectListPartitionIterator(System.Collections.Generic.IList<TSource> source, Func<TSource, TResult> selector, int minIndexInclusive, int maxIndexInclusive) { _source = source; _selector = selector; _minIndexInclusive = minIndexInclusive; _maxIndexInclusive = maxIndexInclusive; _index = minIndexInclusive; } public override Iterator<TResult> Clone() { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, _minIndexInclusive, _maxIndexInclusive); } public override bool MoveNext() { if (((_state == 1) & (_index <= _maxIndexInclusive)) && _index < ((System.Collections.Generic.ICollection<TSource>)_source).Count) { _current = _selector.Invoke(_source[_index]); _index++; return true; } Dispose(); return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectListPartitionIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector), _minIndexInclusive, _maxIndexInclusive); } public IPartition<TResult> Skip(int count) { int num = _minIndexInclusive + count; if ((uint)num <= (uint)_maxIndexInclusive) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, num, _maxIndexInclusive); } return EmptyPartition<TResult>.Instance; } public IPartition<TResult> Take(int count) { int num = _minIndexInclusive + count - 1; if ((uint)num < (uint)_maxIndexInclusive) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, _minIndexInclusive, num); } return this; } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index <= (uint)(_maxIndexInclusive - _minIndexInclusive) && index < ((System.Collections.Generic.ICollection<TSource>)_source).Count - _minIndexInclusive) { found = true; return _selector.Invoke(_source[_minIndexInclusive + index]); } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { if (((System.Collections.Generic.ICollection<TSource>)_source).Count > _minIndexInclusive) { found = true; return _selector.Invoke(_source[_minIndexInclusive]); } found = false; return default(TResult); } public TResult TryGetLast(out bool found) { int num = ((System.Collections.Generic.ICollection<TSource>)_source).Count - 1; if (num >= _minIndexInclusive) { found = true; return _selector.Invoke(_source[Math.Min(num, _maxIndexInclusive)]); } found = false; return default(TResult); } public TResult[] ToArray() { int count = Count; if (count == 0) { return System.Array.Empty<TResult>(); } TResult[] array = new TResult[count]; int num = 0; int num2 = _minIndexInclusive; while (num != array.Length) { array[num] = _selector.Invoke(_source[num2]); num++; num2++; } return array; } public List<TResult> ToList() { int count = Count; if (count == 0) { return (List<TResult>)(object)new List<?>(); } List<TResult> val = (List<TResult>)(object)new List<?>(count); int num = _minIndexInclusive + count; for (int i = _minIndexInclusive; i != num; i++) { ((List<?>)(object)val).Add(_selector.Invoke(_source[i])); } return val; } public int GetCount(bool onlyIfCheap) { return Count; } } private abstract class UnionIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { internal readonly IEqualityComparer<TSource> _comparer; private System.Collections.Generic.IEnumerator<TSource> _enumerator; private Set<TSource> _set; public UnionIterator(IEqualityComparer<TSource> comparer) { _comparer = comparer; } public sealed override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; _set = null; } base.Dispose(); } internal abstract System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index); internal abstract UnionIterator<TSource> Union(System.Collections.Generic.IEnumerable<TSource> next); protected void SetEnumerator(System.Collections.Generic.IEnumerator<TSource> enumerator) { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); } _enumerator = enumerator; } protected void StoreFirst() { Set<TSource> set = new Set<TSource>(_comparer); TSource current = _enumerator.Current; set.Add(current); _current = current; _set = set; } protected bool GetNext() { Set<TSource> set = _set; while (((System.Collections.IEnumerator)_enumerator).MoveNext()) { TSource current = _enumerator.Current; if (set.Add(current)) { _current = current; return true; } } return false; } public sealed override bool MoveNext() { if (_state == 1) { for (System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(0); enumerable != null; enumerable = GetEnumerable(_state - 1)) { System.Collections.Generic.IEnumerator<TSource> enumerator = enumerable.GetEnumerator(); _state++; if (((System.Collections.IEnumerator)enumerator).MoveNext()) { SetEnumerator(enumerator); StoreFirst(); return true; } } } else if (_state > 0) { while (true) { if (GetNext()) { return true; } System.Collections.Generic.IEnumerable<TSource> enumerable2 = GetEnumerable(_state - 1); if (enumerable2 == null) { break; } SetEnumerator(enumerable2.GetEnumerator()); _state++; } } Dispose(); return false; } private Set<TSource> FillSet() { Set<TSource> set = new Set<TSource>(_comparer); int num = 0; while (true) { System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(num); if (enumerable == null) { break; } System.Collections.Generic.IEnumerator<TSource> enumerator = enumerable.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; set.Add(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } num++; } return set; } public TSource[] ToArray() { return FillSet().ToArray(); } public List<TSource> ToList() { return FillSet().ToList(); } public int GetCount(bool onlyIfCheap) { if (!onlyIfCheap) { return FillSet().Count; } return -1; } } private sealed class UnionIterator2<TSource> : UnionIterator<TSource> { private readonly System.Collections.Generic.IEnumerable<TSource> _first; private readonly System.Collections.Generic.IEnumerable<TSource> _second; public UnionIterator2(System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) : base(comparer) { _first = first; _second = second; } public override Iterator<TSource> Clone() { return new UnionIterator2<TSource>(_first, _second, _comparer); } internal override System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index) { return index switch { 0 => _first, 1 => _second, _ => null, }; } internal override UnionIterator<TSource> Union(System.Collections.Generic.IEnumerable<TSource> next) { return new UnionIteratorN<TSource>(this, next, 2); } } private sealed class UnionIteratorN<TSource> : UnionIterator<TSource> { private readonly UnionIterator<TSource> _previous; private readonly System.Collections.Generic.IEnumerable<TSource> _next; private readonly int _nextIndex; public UnionIteratorN(UnionIterator<TSource> previous, System.Collections.Generic.IEnumerable<TSource> next, int nextIndex) : base(previous._comparer) { _previous = previous; _next = next; _nextIndex = nextIndex; } public override Iterator<TSource> Clone() { return new UnionIteratorN<TSource>(_previous, _next, _nextIndex); } internal override System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index) { if (index > _nextIndex) { return null; } UnionIteratorN<TSource> unionIteratorN = this; while (index < unionIteratorN._nextIndex) { UnionIterator<TSource> previous = unionIteratorN._previous; unionIteratorN = previous as UnionIteratorN<TSource>; if (unionIteratorN == null) { return previous.GetEnumerable(index); } } return unionIteratorN._next; } internal override UnionIterator<TSource> Union(System.Collections.Generic.IEnumerable<TSource> next) { if (_nextIndex == 2147483645) { return new UnionIterator2<TSource>(this, next, _comparer); } return new UnionIteratorN<TSource>(this, next, _nextIndex + 1); } } internal sealed class WhereEnumerableIterator<TSource> : Iterator<TSource> { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly Func<TSource, bool> _predicate; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public WhereEnumerableIterator(System.Collections.Generic.IEnumerable<TSource> source, Func<TSource, bool> predicate) { _source = source; _predicate = predicate; } public override Iterator<TSource> Clone() { return new WhereEnumerableIterator<TSource>(_source, _predicate); } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_0061; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } while (((System.Collections.IEnumerator)_enumerator).MoveNext()) { TSource current = _enumerator.Current; if (_predicate.Invoke(current)) { _current = current; return true; } } Dispose(); goto IL_0061; IL_0061: return false; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, selector); } public override System.Collections.Generic.IEnumerable<TSource> Where(Func<TSource, bool> predicate) { return new WhereEnumerableIterator<TSource>(_source, CombinePredicates<TSource>(_predicate, predicate)); } } internal sealed class WhereArrayIterator<TSource> : Iterator<TSource> { private readonly TSource[] _source; private readonly Func<TSource, bool> _predicate; private int _index; public WhereArrayIterator(TSource[] source, Func<TSource, bool> predicate) { _source = source; _predicate = predicate; } public override Iterator<TSource> Clone() { return new WhereArrayIterator<TSource>(_source, _predicate); } public override bool MoveNext() { if (_state == 1) { while (_index < _source.Length) { TSource val = _source[_index]; _index++; if (_predicate.Invoke(val)) { _current = val; return true; } } Dispose(); } return false; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, selector); } public override System.Collections.Generic.IEnumerable<TSource> Where(Func<TSource, bool> predicate) { return new WhereArrayIterator<TSource>(_source, CombinePredicates<TSource>(_predicate, predicate)); } } internal sealed class WhereListIterator<TSource> : Iterator<TSource> { private readonly List<TSource> _source; private readonly Func<TSource, bool> _predicate; private Enumerator<TSource> _enumerator; public WhereListIterator(List<TSource> source, Func<TSource, bool> predicate) { _source = source; _predicate = predicate; } public override Iterator<TSource> Clone() { return new WhereListIterator<TSource>(_source, _predicate); } public override bool MoveNext() { //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) int state = _state; if (state != 1) { if (state != 2) { goto IL_0061; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } while (_enumerator.MoveNext()) { TSource current = _enumerator.Current; if (_predicate.Invoke(current)) { _current = current; return true; } } Dispose(); goto IL_0061; IL_0061: return false; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new WhereSelectListIterator<TSource, TResult>(_source, _predicate, selector); } public override System.Collections.Generic.IEnumerable<TSource> Where(Func<TSource, bool> predicate) { return new WhereListIterator<TSource>(_source, CombinePredicates<TSource>(_predicate, predicate)); } } internal sealed class WhereSelectArrayIterator<TSource, TResult> : Iterator<TResult> { private readonly TSource[] _source; private readonly Func<TSource, bool> _predicate; private readonly Func<TSource, TResult> _selector; private int _index; public WhereSelectArrayIterator(TSource[] source, Func<TSource, bool> predicate, Func<TSource, TResult> selector) { _source = source; _predicate = predicate; _selector = selector; } public override Iterator<TResult> Clone() { return new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, _selector); } public override bool MoveNext() { if (_state == 1) { while (_index < _source.Length) { TSource val = _source[_index]; _index++; if (_predicate.Invoke(val)) { _current = _selector.Invoke(val); return true; } } Dispose(); } return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new WhereSelectArrayIterator<TSource, TResult2>(_source, _predicate, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } } internal sealed class WhereSelectListIterator<TSource, TResult> : Iterator<TResult> { private readonly List<TSource> _source; private readonly Func<TSource, bool> _predicate; private readonly Func<TSource, TResult> _selector; private Enumerator<TSource> _enumerator; public WhereSelectListIterator(List<TSource> source, Func<TSource, bool> predicate, Func<TSource, TResult> selector) { _source = source; _predicate = predicate; _selector = selector; } public override Iterator<TResult> Clone() { return new WhereSelectListIterator<TSource, TResult>(_source, _predicate, _selector); } public override bool MoveNext() { //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) int state = _state; if (state != 1) { if (state != 2) { goto IL_006c; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } while (_enumerator.MoveNext()) { TSource current = _enumerator.Current; if (_predicate.Invoke(current)) { _current = _selector.Invoke(current); return true; } } Dispose(); goto IL_006c; IL_006c: return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new WhereSelectListIterator<TSource, TResult2>(_source, _predicate, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } } internal sealed class WhereSelectEnumerableIterator<TSource, TResult> : Iterator<TResult> { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly Func<TSource, bool> _predicate; private readonly Func<TSource, TResult> _selector; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public WhereSelectEnumerableIterator(System.Collections.Generic.IEnumerable<TSource> source, Func<TSource, bool> predicate, Func<TSource, TResult> selector) { _source = source; _predicate = predicate; _selector = selector; } public override Iterator<TResult> Clone() { return new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, _selector); } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_006c; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } while (((System.Collections.IEnumerator)_enumerator).MoveNext()) { TSource current = _enumerator.Current; if (_predicate.Invoke(current)) { _current = _selector.Invoke(current); return true; } } Dispose(); goto IL_006c; IL_006c: return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new WhereSelectEnumerableIterator<TSource, TResult2>(_source, _predicate, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } } [CompilerGenerated] private sealed class <OfTypeIterator>d__33<TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.IEnumerable source; public System.Collections.IEnumerable <>3__source; private System.Collections.IEnumerator <>7__wrap1; TResult System.Collections.Generic.IEnumerator<TResult>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <OfTypeIterator>d__33(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = source.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } while (<>7__wrap1.MoveNext()) { object current = <>7__wrap1.Current; if (current is TResult) { <>2__current = (TResult)current; <>1__state = 1; return true; } } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 is System.IDisposable disposable) { disposable.Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() { <OfTypeIterator>d__33<TResult> <OfTypeIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <OfTypeIterator>d__ = this; } else { <OfTypeIterator>d__ = new <OfTypeIterator>d__33<TResult>(0); } <OfTypeIterator>d__.source = <>3__source; return <OfTypeIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<TResult>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <CastIterator>d__35<TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.IEnumerable source; public System.Collections.IEnumerable <>3__source; private System.Collections.IEnumerator <>7__wrap1; TResult System.Collections.Generic.IEnumerator<TResult>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <CastIterator>d__35(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = source.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { object current = <>7__wrap1.Current; <>2__current = (TResult)current; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 is System.IDisposable disposable) { disposable.Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() { <CastIterator>d__35<TResult> <CastIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <CastIterator>d__ = this; } else { <CastIterator>d__ = new <CastIterator>d__35<TResult>(0); } <CastIterator>d__.source = <>3__source; return <CastIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<TResult>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <ExceptIterator>d__58<TSource> : System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TSource>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TSource <>2__current; private int <>l__initialThreadId; private IEqualityComparer<TSource> comparer; public IEqualityComparer<TSource> <>3__comparer; private System.Collections.Generic.IEnumerable<TSource> second; public System.Collections.Generic.IEnumerable<TSource> <>3__second; private System.Collections.Generic.IEnumerable<TSource> first; public System.Collections.Generic.IEnumerable<TSource> <>3__first; private Set<TSource> <set>5__1; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; TSource System.Collections.Generic.IEnumerator<TSource>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ExceptIterator>d__58(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: { <>1__state = -1; <set>5__1 = new Set<TSource>(comparer); System.Collections.Generic.IEnumerator<TSource> enumerator = second.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; <set>5__1.Add(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } <>7__wrap1 = first.GetEnumerator(); <>1__state = -3; break; } case 1: <>1__state = -3; break; } while (((System.Collections.IEnumerator)<>7__wrap1).MoveNext()) { TSource current2 = <>7__wrap1.Current; if (<set>5__1.Add(current2)) { <>2__current = current2; <>1__state = 1; return true; } } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { ((System.IDisposable)<>7__wrap1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TSource> System.Collections.Generic.IEnumerable<TSource>.GetEnumerator() { <ExceptIterator>d__58<TSource> <ExceptIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <ExceptIterator>d__ = this; } else { <ExceptIterator>d__ = new <ExceptIterator>d__58<TSource>(0); } <ExceptIterator>d__.first = <>3__first; <ExceptIterator>d__.second = <>3__second; <ExceptIterator>d__.comparer = <>3__comparer; return <ExceptIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<TSource>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <GroupJoinIterator>d__73<TOuter, TInner, TKey, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TOuter> outer; public System.Collections.Generic.IEnumerable<TOuter> <>3__outer; private System.Collections.Generic.IEnumerable<TInner> inner; public System.Collections.Generic.IEnumerable<TInner> <>3__inner; private Func<TInner, TKey> innerKeySelector; public Func<TInner, TKey> <>3__innerKeySelector; private IEqualityComparer<TKey> comparer; public IEqualityComparer<TKey> <>3__comparer; private System.Collections.Generic.IEnumerator<TOuter> <e>5__1; private Func<TOuter, System.Collections.Generic.IEnumerable<TInner>, TResult> resultSelector; public Func<TOuter, System.Collections.Generic.IEnumerable<TInner>, TResult> <>3__resultSelector; private Lookup<TKey, TInner> <lookup>5__2; private Func<TOuter, TKey> outerKeySelector; public Func<TOuter, TKey> <>3__outerKeySelector; TResult System.Collections.Generic.IEnumerator<?>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GroupJoinIterator>d__73(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -3; if (((System.Collections.IEnumerator)<e>5__1).MoveNext()) { goto IL_0062; } <lookup>5__2 = null; } else { <>1__state = -1; <e>5__1 = outer.GetEnumerator(); <>1__state = -3; if (((System.Collections.IEnumerator)<e>5__1).MoveNext()) { <lookup>5__2 = Lookup<TKey, TInner>.CreateForJoin(inner, innerKeySelector, comparer); goto IL_0062; } } <>m__Finally1(); <e>5__1 = null; return false; IL_0062: TOuter current = <e>5__1.Current; <>2__current = ((Func<TOuter, System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<TInner>>, ?>)(object)resultSelector).Invoke(current, (System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<TInner>>)<lookup>5__2[((Func<TOuter, ?>)(object)outerKeySelector).Invoke(current)]); <>1__state = 1; return true; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<e>5__1 != null) { ((System.IDisposable)<e>5__1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<?>.GetEnumerator() { <GroupJoinIterator>d__73<TOuter, TInner, TKey, TResult> <GroupJoinIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <GroupJoinIterator>d__ = this; } else { <GroupJoinIterator>d__ = new <GroupJoinIterator>d__73<TOuter, TInner, TKey, TResult>(0); } <GroupJoinIterator>d__.outer = <>3__outer; <GroupJoinIterator>d__.inner = <>3__inner; <GroupJoinIterator>d__.outerKeySelector = <>3__outerKeySelector; <GroupJoinIterator>d__.innerKeySelector = <>3__innerKeySelector; <GroupJoinIterator>d__.resultSelector = <>3__resultSelector; <GroupJoinIterator>d__.comparer = <>3__comparer; return <GroupJoinIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<?>)(object)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <IntersectIterator>d__76<TSource> : System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TSource>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TSource <>2__current; private int <>l__initialThreadId; private IEqualityComparer<TSource> comparer; public IEqualityComparer<TSource> <>3__comparer; private System.Collections.Generic.IEnumerable<TSource> second; public System.Collections.Generic.IEnumerable<TSource> <>3__second; private System.Collections.Generic.IEnumerable<TSource> first; public System.Collections.Generic.IEnumerable<TSource> <>3__first; private Set<TSource> <set>5__1; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; TSource System.Collections.Generic.IEnumerator<TSource>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <IntersectIterator>d__76(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: { <>1__state = -1; <set>5__1 = new Set<TSource>(comparer); System.Collections.Generic.IEnumerator<TSource> enumerator = second.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; <set>5__1.Add(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } <>7__wrap1 = first.GetEnumerator(); <>1__state = -3; break; } case 1: <>1__state = -3; break; } while (((System.Collections.IEnumerator)<>7__wrap1).MoveNext()) { TSource current2 = <>7__wrap1.Current; if (<set>5__1.Remove(current2)) { <>2__current = current2; <>1__state = 1; return true; } } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { ((System.IDisposable)<>7__wrap1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TSource> System.Collections.Generic.IEnumerable<TSource>.GetEnumerator() { <IntersectIterator>d__76<TSource> <IntersectIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <IntersectIterator>d__ = this; } else { <IntersectIterator>d__ = new <IntersectIterator>d__76<TSource>(0); } <IntersectIterator>d__.first = <>3__first; <IntersectIterator>d__.second = <>3__second; <IntersectIterator>d__.comparer = <>3__comparer; return <IntersectIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<TSource>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <JoinIterator>d__80<TOuter, TInner, TKey, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TOuter> outer; public System.Collections.Generic.IEnumerable<TOuter> <>3__outer; private System.Collections.Generic.IEnumerable<TInner> inner; public System.Collections.Generic.IEnumerable<TInner> <>3__inner; private Func<TInner, TKey> innerKeySelector; public Func<TInner, TKey> <>3__innerKeySelector; private IEqualityComparer<TKey> comparer; public IEqualityComparer<TKey> <>3__comparer; private System.Collections.Generic.IEnumerator<TOuter> <e>5__1; private Lookup<TKey, TInner> <lookup>5__2; private Func<TOuter, TKey> outerKeySelector; public Func<TOuter, TKey> <>3__outerKeySelector; private Func<TOuter, TInner, TResult> resultSelector; public Func<TOuter, TInner, TResult> <>3__resultSelector; private TOuter <item>5__3; private TInner[] <elements>5__4; private int <i>5__5; private int <count>5__6; TResult System.Collections.Generic.IEnumerator<?>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <JoinIterator>d__80(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -3; int num2 = <i>5__5 + 1; <i>5__5 = num2; goto IL_0116; } <>1__state = -1; <e>5__1 = outer.GetEnumerator(); <>1__state = -3; if (((System.Collections.IEnumerator)<e>5__1).MoveNext()) { <lookup>5__2 = Lookup<TKey, TInner>.CreateForJoin(inner, innerKeySelector, comparer); if (<lookup>5__2.Count != 0) { goto IL_0075; } goto IL_0147; } goto IL_014e; IL_0075: <item>5__3 = <e>5__1.Current; Grouping<TKey, TInner> grouping = <lookup>5__2.GetGrouping(((Func<TOuter, ?>)(object)outerKeySelector).Invoke(<item>5__3), create: false); if (grouping != null) { <count>5__6 = grouping._count; <elements>5__4 = grouping._elements; <i>5__5 = 0; goto IL_0116; } goto IL_012b; IL_0116: if (<i>5__5 != <count>5__6) { <>2__current = ((Func<TOuter, TInner, ?>)(object)resultSelector).Invoke(<item>5__3, <elements>5__4[<i>5__5]); <>1__state = 1; return true; } <elements>5__4 = null; goto IL_012b; IL_0147: <lookup>5__2 = null; goto IL_014e; IL_012b: <item>5__3 = default(TOuter); if (((System.Collections.IEnumerator)<e>5__1).MoveNext()) { goto IL_0075; } goto IL_0147; IL_014e: <>m__Finally1(); <e>5__1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<e>5__1 != null) { ((System.IDisposable)<e>5__1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<?>.GetEnumerator() { <JoinIterator>d__80<TOuter, TInner, TKey, TResult> <JoinIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <JoinIterator>d__ = this; } else { <JoinIterator>d__ = new <JoinIterator>d__80<TOuter, TInner, TKey, TResult>(0); } <JoinIterator>d__.outer = <>3__outer; <JoinIterator>d__.inner = <>3__inner; <JoinIterator>d__.outerKeySelector = <>3__outerKeySelector; <JoinIterator>d__.innerKeySelector = <>3__innerKeySelector; <JoinIterator>d__.resultSelector = <>3__resultSelector; <JoinIterator>d__.comparer = <>3__comparer; return <JoinIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<?>)(object)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <SelectIterator>d__150<TSource, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TSource> source; public System.Collections.Generic.IEnumerable<TSource> <>3__source; private int <index>5__1; private Func<TSource, int, TResult> selector; public Func<TSource, int, TResult> <>3__selector; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; TResult System.Collections.Generic.IEnumerator<?>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SelectIterator>d__150(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { checked { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <index>5__1 = -1; <>7__wrap1 = source.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (((System.Collections.IEnumerator)<>7__wrap1).MoveNext()) { TSource current = <>7__wrap1.Current; <index>5__1++; <>2__current = ((Func<TSource, int, int>)(object)selector).Invoke(current, <index>5__1); <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { ((System.IDisposable)<>7__wrap1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<?>.GetEnumerator() { <SelectIterator>d__150<TSource, TResult> <SelectIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <SelectIterator>d__ = this; } else { <SelectIterator>d__ = new <SelectIterator>d__150<TSource, TResult>(0); } <SelectIterator>d__.source = <>3__source; <SelectIterator>d__.selector = <>3__selector; return <SelectIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<?>)(object)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <SelectManyIterator>d__159<TSource, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TSource> source; public System.Collections.Generic.IEnumerable<TSource> <>3__source; private Func<TSource, System.Collections.Generic.IEnumerable<TResult>> selector; public Func<TSource, System.Collections.Generic.IEnumerable<TResult>> <>3__selector; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; private System.Collections.Generic.IEnumerator<TResult> <>7__wrap2; TResult System.Collections.Generic.IEnumerator<?>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SelectManyIterator>d__159(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num != -4 && num != -3 && num != 1) { return; } try { if (num != -4 && num != 1) { return; } try { } finally { <>m__Finally2(); } } finally { <>m__Finally1(); } } private bool MoveNext() { try { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -4; goto IL_008a; } <>1__state = -1; <>7__wrap1 = source.GetEnumerator(); <>1__state = -3; goto IL_00a4; IL_008a: if (((System.Collections.IEnumerator)<>7__wrap2).MoveNext()) { TResult current = ((System.Collections.Generic.IEnumerator<?>)<>7__wrap2).Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally2(); <>7__wrap2 = null; goto IL_00a4; IL_00a4: if (((System.Collections.IEnumerator)<>7__wrap1).MoveNext()) { TSource current2 = <>7__wrap1.Current; <>7__wrap2 = ((System.Collections.Generic.IEnumerable<?>)((Func<TSource, System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<TResult>>>)(object)selector).Invoke(current2)).GetEnumerator(); <>1__state = -4; goto IL_008a; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { ((System.IDisposable)<>7__wrap1).Dispose(); } } private void <>m__Finally2() { <>1__state = -3; if (<>7__wrap2 != null) { ((System.IDisposable)<>7__wrap2).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<?>.GetEnumerator() { <SelectManyIterator>d__159<TSource, TResult> <SelectManyIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <SelectManyIterator>d__ = this; } else { <SelectManyIterator>d__ = new <SelectManyIterator>d__159<TSource, TResult>(0); } <SelectManyIterator>d__.source = <>3__source; <SelectManyIterator>d__.selector = <>3__selector; return <SelectManyIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<?>)(object)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <SelectManyIterator>d__161<TSource, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TSource> source; public System.Collections.Generic.IEnumerable<TSource> <>3__source; private int <index>5__1; private Func<TSource, int, System.Collections.Generic.IEnumerable<TResult>> selector; public Func<TSource, int, System.Collections.Generic.IEnumerable<TResult>> <>3__selector; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; private System.Collections.Generic.IEnumerator<TResul
BepInEx/plugins/VNyanCommands/System.Memory.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.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
BepInEx/plugins/VNyanCommands/System.Numerics.Vectors.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
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 = ®ister.byte_0) { return (T)(object)ptr[index]; } } if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { return (T)(object)ptr2[index]; } } if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { return (T)(object)ptr3[index]; } } if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { return (T)(object)ptr4[index]; } } if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { return (T)(object)ptr5[index]; } } if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { return (T)(object)ptr6[index]; } } if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { return (T)(object)ptr7[index]; } } if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { return (T)(object)ptr8[index]; } } if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { return (T)(object)ptr9[index]; } } if (typeof(T) == typeof(double)) { fixed (double* ptr10 = ®ister.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 = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)value; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)value; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)value; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)value; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)value; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)value; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)value; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)value; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)value; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.uint64_0) { *ptr17 = (ulong)(object)values[index]; ptr17[1] = (ulong)(object)values[1 + index]; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = ®ister.int64_0) { *ptr18 = (long)(object)values[index]; ptr18[1] = (long)(object)values[1 + index]; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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 = ®ister.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
BepInEx/plugins/VNyanCommands/System.Reactive.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
#define TRACE using System; using System.CodeDom.Compiler; 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.Linq; using System.Linq.Expressions; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Joins; using System.Reactive.Linq; using System.Reactive.Linq.ObservableImpl; using System.Reactive.PlatformServices; using System.Reactive.Subjects; using System.Reactive.Threading.Tasks; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyFileVersion("6.0.0.1")] [assembly: AssemblyInformationalVersion("6.0.0.1+e29c7a50db")] [assembly: InternalsVisibleTo("Tests.System.Reactive, PublicKey=00240000048000009400000006020000002400005253413100040000010001008f5cff058631087031f8350f30a36fa078027e5df2316b564352dc9eb7af7ce856016d3c5e9d058036fe73bb5c83987bd3fc0793fbe25d633cc4f37c2bd5f1d717cd2a81661bec08f0971dc6078e17bde372b89005e7738a0ebd501b896ca3e8315270ff64df7809dd912c372df61785a5085b3553b7872e39b1b1cc0ff5a6bc")] [assembly: InternalsVisibleTo("Tests.System.Reactive.Uwp.DeviceRunner, PublicKey=00240000048000009400000006020000002400005253413100040000010001008f5cff058631087031f8350f30a36fa078027e5df2316b564352dc9eb7af7ce856016d3c5e9d058036fe73bb5c83987bd3fc0793fbe25d633cc4f37c2bd5f1d717cd2a81661bec08f0971dc6078e17bde372b89005e7738a0ebd501b896ca3e8315270ff64df7809dd912c372df61785a5085b3553b7872e39b1b1cc0ff5a6bc")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("CommitHash", "e29c7a50db88513a87651c366088da8b7f40b1f0")] [assembly: AssemblyCompany(".NET Foundation and Contributors")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (c) .NET Foundation and Contributors.")] [assembly: AssemblyDescription("Reactive Extensions (Rx) for .NET")] [assembly: AssemblyProduct("System.Reactive (netstandard2.0)")] [assembly: AssemblyTitle("System.Reactive")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/reactive")] [assembly: AssemblyVersion("6.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] 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 RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } [GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.6.128.36433")] [ExcludeFromCodeCoverage] internal static class ThisAssembly { internal const string AssemblyConfiguration = "Release"; internal const string AssemblyFileVersion = "6.0.0.1"; internal const string AssemblyInformationalVersion = "6.0.0.1+e29c7a50db"; internal const string AssemblyName = "System.Reactive"; internal const string AssemblyTitle = "System.Reactive"; internal const string AssemblyVersion = "6.0.0.0"; internal static readonly DateTime GitCommitDate = new DateTime(638200702660000000L, DateTimeKind.Utc); internal const string GitCommitId = "e29c7a50db88513a87651c366088da8b7f40b1f0"; internal const bool IsPrerelease = false; internal const bool IsPublicRelease = true; internal const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001008f5cff058631087031f8350f30a36fa078027e5df2316b564352dc9eb7af7ce856016d3c5e9d058036fe73bb5c83987bd3fc0793fbe25d633cc4f37c2bd5f1d717cd2a81661bec08f0971dc6078e17bde372b89005e7738a0ebd501b896ca3e8315270ff64df7809dd912c372df61785a5085b3553b7872e39b1b1cc0ff5a6bc"; internal const string PublicKeyToken = "94bc3704cddfc263"; internal const string RootNamespace = "System.Reactive"; } namespace System { public static class ObservableExtensions { public static IDisposable Subscribe<T>(this IObservable<T> source) { if (source == null) { throw new ArgumentNullException("source"); } return source.Subscribe(new AnonymousObserver<T>(Stubs<T>.Ignore, Stubs.Throw, Stubs.Nop)); } public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext) { if (source == null) { throw new ArgumentNullException("source"); } if (onNext == null) { throw new ArgumentNullException("onNext"); } return source.Subscribe(new AnonymousObserver<T>(onNext, Stubs.Throw, Stubs.Nop)); } public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError) { if (source == null) { throw new ArgumentNullException("source"); } if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } return source.Subscribe(new AnonymousObserver<T>(onNext, onError, Stubs.Nop)); } public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action onCompleted) { if (source == null) { throw new ArgumentNullException("source"); } if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } return source.Subscribe(new AnonymousObserver<T>(onNext, Stubs.Throw, onCompleted)); } public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, Action onCompleted) { if (source == null) { throw new ArgumentNullException("source"); } if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } return source.Subscribe(new AnonymousObserver<T>(onNext, onError, onCompleted)); } public static void Subscribe<T>(this IObservable<T> source, IObserver<T> observer, CancellationToken token) { if (source == null) { throw new ArgumentNullException("source"); } if (observer == null) { throw new ArgumentNullException("observer"); } source.Subscribe_(observer, token); } public static void Subscribe<T>(this IObservable<T> source, CancellationToken token) { if (source == null) { throw new ArgumentNullException("source"); } source.Subscribe_(new AnonymousObserver<T>(Stubs<T>.Ignore, Stubs.Throw, Stubs.Nop), token); } public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, CancellationToken token) { if (source == null) { throw new ArgumentNullException("source"); } if (onNext == null) { throw new ArgumentNullException("onNext"); } source.Subscribe_(new AnonymousObserver<T>(onNext, Stubs.Throw, Stubs.Nop), token); } public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, CancellationToken token) { if (source == null) { throw new ArgumentNullException("source"); } if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } source.Subscribe_(new AnonymousObserver<T>(onNext, onError, Stubs.Nop), token); } public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action onCompleted, CancellationToken token) { if (source == null) { throw new ArgumentNullException("source"); } if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } source.Subscribe_(new AnonymousObserver<T>(onNext, Stubs.Throw, onCompleted), token); } public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, Action onCompleted, CancellationToken token) { if (source == null) { throw new ArgumentNullException("source"); } if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } source.Subscribe_(new AnonymousObserver<T>(onNext, onError, onCompleted), token); } private static void Subscribe_<T>(this IObservable<T> source, IObserver<T> observer, CancellationToken token) { if (token.CanBeCanceled) { if (!token.IsCancellationRequested) { ISafeObserver<T> safeObserver = SafeObserver<T>.Wrap(observer); IDisposable state2 = source.Subscribe(safeObserver); safeObserver.SetResource(token.Register(delegate(object state) { ((IDisposable)state).Dispose(); }, state2)); } } else { source.Subscribe(observer); } } [EditorBrowsable(EditorBrowsableState.Advanced)] public static IDisposable SubscribeSafe<T>(this IObservable<T> source, IObserver<T> observer) { if (source == null) { throw new ArgumentNullException("source"); } if (observer == null) { throw new ArgumentNullException("observer"); } if (source is ObservableBase<T>) { return source.Subscribe(observer); } if (source is IProducer<T> producer) { return producer.SubscribeRaw(observer, enableSafeguard: false); } IDisposable result = Disposable.Empty; try { result = source.Subscribe(observer); } catch (Exception error) { observer.OnError(error); } return result; } } } namespace System.Runtime.CompilerServices { public struct TaskObservableMethodBuilder<T> { internal sealed class TaskObservable : ITaskObservable<T>, IObservable<T>, ITaskObservableAwaiter<T>, INotifyCompletion { private readonly AsyncSubject<T>? _subject; private readonly T? _result; private readonly Exception? _exception; public bool IsCompleted => _subject?.IsCompleted ?? true; public TaskObservable() { _subject = new AsyncSubject<T>(); } public TaskObservable(T result) { _result = result; } public TaskObservable(Exception exception) { _exception = exception; } public void SetResult(T result) { if (IsCompleted) { throw new InvalidOperationException(); } _subject.OnNext(result); _subject.OnCompleted(); } public void SetException(Exception exception) { if (IsCompleted) { throw new InvalidOperationException(); } _subject.OnError(exception); } public IDisposable Subscribe(IObserver<T> observer) { if (_subject != null) { return _subject.Subscribe(observer); } if (_exception != null) { observer.OnError(_exception); return Disposable.Empty; } observer.OnNext(_result); return Disposable.Empty; } public ITaskObservableAwaiter<T> GetAwaiter() { return this; } public T GetResult() { if (_subject != null) { return _subject.GetResult(); } _exception?.Throw(); return _result; } public void OnCompleted(Action continuation) { if (_subject != null) { _subject.OnCompleted(continuation); } else { continuation(); } } } private IAsyncStateMachine _stateMachine; private TaskObservable _inner; public ITaskObservable<T> Task => _inner ?? (_inner = new TaskObservable()); public static TaskObservableMethodBuilder<T> Create() { return default(TaskObservableMethodBuilder<T>); } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { if (stateMachine == null) { throw new ArgumentNullException("stateMachine"); } stateMachine.MoveNext(); } public void SetStateMachine(IAsyncStateMachine stateMachine) { if (_stateMachine != null) { throw new InvalidOperationException(); } _stateMachine = stateMachine ?? throw new ArgumentNullException("stateMachine"); } public void SetResult(T result) { if (_inner == null) { _inner = new TaskObservable(result); } else { _inner.SetResult(result); } } public void SetException(Exception exception) { if (exception == null) { throw new ArgumentNullException("exception"); } if (_inner == null) { _inner = new TaskObservable(exception); } else { _inner.SetException(exception); } } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { try { if (_stateMachine == null) { _ = Task; _stateMachine = stateMachine; _stateMachine.SetStateMachine(_stateMachine); } ref TAwaiter reference = ref awaiter; TAwaiter val = default(TAwaiter); if (val == null) { val = reference; reference = ref val; } reference.OnCompleted(_stateMachine.MoveNext); } catch (Exception exception) { Rethrow(exception); } } [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { try { if (_stateMachine == null) { _ = Task; _stateMachine = stateMachine; _stateMachine.SetStateMachine(_stateMachine); } ref TAwaiter reference = ref awaiter; TAwaiter val = default(TAwaiter); if (val == null) { val = reference; reference = ref val; } reference.UnsafeOnCompleted(_stateMachine.MoveNext); } catch (Exception exception) { Rethrow(exception); } } private static void Rethrow(Exception exception) { Scheduler.Default.Schedule(exception, delegate(Exception ex, Action<Exception> recurse) { ex.Throw(); }); } } } namespace System.Threading.Tasks { internal static class TaskExtensions { public static Task ContinueWithState<TState>(this Task task, Action<Task, TState> continuationAction, TState state, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken) { return task.ContinueWith(delegate(Task t, object tupleObject) { var (action, arg) = ((Action<Task, TState>, TState))tupleObject; action(t, arg); }, (continuationAction, state), cancellationToken, continuationOptions, TaskScheduler.Default); } public static Task ContinueWithState<TResult, TState>(this Task<TResult> task, Action<Task<TResult>, TState> continuationAction, TState state, CancellationToken cancellationToken) { return task.ContinueWith(delegate(Task<TResult> t, object tupleObject) { var (action, arg) = ((Action<Task<TResult>, TState>, TState))tupleObject; action(t, arg); }, (continuationAction, state), cancellationToken); } public static Task ContinueWithState<TResult, TState>(this Task<TResult> task, Action<Task<TResult>, TState> continuationAction, TState state, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken) { return task.ContinueWith(delegate(Task<TResult> t, object tupleObject) { var (action, arg) = ((Action<Task<TResult>, TState>, TState))tupleObject; action(t, arg); }, (continuationAction, state), cancellationToken, continuationOptions, TaskScheduler.Default); } } } 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.Reactive { public sealed class AnonymousObservable<T> : ObservableBase<T> { private readonly Func<IObserver<T>, IDisposable> _subscribe; public AnonymousObservable(Func<IObserver<T>, IDisposable> subscribe) { _subscribe = subscribe ?? throw new ArgumentNullException("subscribe"); } protected override IDisposable SubscribeCore(IObserver<T> observer) { return _subscribe(observer) ?? Disposable.Empty; } } public sealed class AnonymousObserver<T> : ObserverBase<T> { private readonly Action<T> _onNext; private readonly Action<Exception> _onError; private readonly Action _onCompleted; public AnonymousObserver(Action<T> onNext, Action<Exception> onError, Action onCompleted) { _onNext = onNext ?? throw new ArgumentNullException("onNext"); _onError = onError ?? throw new ArgumentNullException("onError"); _onCompleted = onCompleted ?? throw new ArgumentNullException("onCompleted"); } public AnonymousObserver(Action<T> onNext) : this(onNext, Stubs.Throw, Stubs.Nop) { } public AnonymousObserver(Action<T> onNext, Action<Exception> onError) : this(onNext, onError, Stubs.Nop) { } public AnonymousObserver(Action<T> onNext, Action onCompleted) : this(onNext, Stubs.Throw, onCompleted) { } protected override void OnNextCore(T value) { _onNext(value); } protected override void OnErrorCore(Exception error) { _onError(error); } protected override void OnCompletedCore() { _onCompleted(); } internal ISafeObserver<T> MakeSafe() { return new AnonymousSafeObserver<T>(_onNext, _onError, _onCompleted); } } internal sealed class AnonymousSafeObserver<T> : SafeObserver<T> { private readonly Action<T> _onNext; private readonly Action<Exception> _onError; private readonly Action _onCompleted; private int _isStopped; public AnonymousSafeObserver(Action<T> onNext, Action<Exception> onError, Action onCompleted) { _onNext = onNext; _onError = onError; _onCompleted = onCompleted; } public override void OnNext(T value) { if (_isStopped != 0) { return; } bool flag = false; try { _onNext(value); flag = true; } finally { if (!flag) { Dispose(); } } } public override void OnError(Exception error) { if (Interlocked.Exchange(ref _isStopped, 1) == 0) { using (this) { _onError(error); } } } public override void OnCompleted() { if (Interlocked.Exchange(ref _isStopped, 1) == 0) { using (this) { _onCompleted(); } } } } public class EventPattern<TEventArgs> : EventPattern<object, TEventArgs> { public EventPattern(object? sender, TEventArgs e) : base(sender, e) { } } public class EventPattern<TSender, TEventArgs> : IEquatable<EventPattern<TSender, TEventArgs>>, IEventPattern<TSender, TEventArgs> { public TSender? Sender { get; } public TEventArgs EventArgs { get; } public EventPattern(TSender? sender, TEventArgs e) { Sender = sender; EventArgs = e; } public void Deconstruct(out TSender? sender, out TEventArgs e) { TSender sender2 = Sender; TEventArgs eventArgs = EventArgs; sender = sender2; e = eventArgs; } public bool Equals(EventPattern<TSender, TEventArgs>? other) { if ((object)other == null) { return false; } if ((object)this == other) { return true; } if (EqualityComparer<TSender>.Default.Equals(Sender, other.Sender)) { return EqualityComparer<TEventArgs>.Default.Equals(EventArgs, other.EventArgs); } return false; } public override bool Equals(object? obj) { return Equals(obj as EventPattern<TSender, TEventArgs>); } public override int GetHashCode() { TSender sender = Sender; int num = ((sender != null) ? sender.GetHashCode() : 0); TEventArgs eventArgs = EventArgs; int num2 = ((eventArgs != null) ? eventArgs.GetHashCode() : 0); return (num << 5) + (num ^ num2); } public static bool operator ==(EventPattern<TSender, TEventArgs> first, EventPattern<TSender, TEventArgs> second) { return object.Equals(first, second); } public static bool operator !=(EventPattern<TSender, TEventArgs> first, EventPattern<TSender, TEventArgs> second) { return !object.Equals(first, second); } } internal sealed class EventPatternSource<TEventArgs> : EventPatternSourceBase<object, TEventArgs>, IEventPatternSource<TEventArgs> { event EventHandler<TEventArgs> IEventPatternSource<TEventArgs>.OnNext { add { EventHandler<TEventArgs> value2 = value; Add(value2, delegate(object? o, TEventArgs e) { value2(o, e); }); } remove { Remove(value); } } public EventPatternSource(IObservable<EventPattern<object, TEventArgs>> source, Action<Action<object?, TEventArgs>, EventPattern<object, TEventArgs>> invokeHandler) : base(source, invokeHandler) { } } public abstract class EventPatternSourceBase<TSender, TEventArgs> { private sealed class Observer : ObserverBase<EventPattern<TSender, TEventArgs>>, ISafeObserver<EventPattern<TSender, TEventArgs>>, IObserver<EventPattern<TSender, TEventArgs>>, IDisposable { private bool _isDone; private bool _isAdded; private readonly Delegate _handler; private readonly object _gate = new object(); private readonly Action<TSender?, TEventArgs> _invoke; private readonly EventPatternSourceBase<TSender, TEventArgs> _sourceBase; public Observer(EventPatternSourceBase<TSender, TEventArgs> sourceBase, Delegate handler, Action<TSender?, TEventArgs> invoke) { _handler = handler; _invoke = invoke; _sourceBase = sourceBase; } protected override void OnNextCore(EventPattern<TSender, TEventArgs> value) { _sourceBase._invokeHandler(_invoke, value); } protected override void OnErrorCore(Exception error) { Remove(); error.Throw(); } protected override void OnCompletedCore() { Remove(); } private void Remove() { lock (_gate) { if (_isAdded) { _sourceBase.Remove(_handler); } else { _isDone = true; } } } public void SetResource(IDisposable resource) { lock (_gate) { if (!_isDone) { _sourceBase.Add(_handler, resource); _isAdded = true; } } } } private readonly IObservable<EventPattern<TSender, TEventArgs>> _source; private readonly Dictionary<Delegate, Stack<IDisposable>> _subscriptions; private readonly Action<Action<TSender?, TEventArgs>, EventPattern<TSender, TEventArgs>> _invokeHandler; protected EventPatternSourceBase(IObservable<EventPattern<TSender, TEventArgs>> source, Action<Action<TSender?, TEventArgs>, EventPattern<TSender, TEventArgs>> invokeHandler) { _source = source ?? throw new ArgumentNullException("source"); _invokeHandler = invokeHandler ?? throw new ArgumentNullException("invokeHandler"); _subscriptions = new Dictionary<Delegate, Stack<IDisposable>>(); } protected void Add(Delegate handler, Action<TSender?, TEventArgs> invoke) { if ((object)handler == null) { throw new ArgumentNullException("handler"); } if (invoke == null) { throw new ArgumentNullException("invoke"); } Observer observer = new Observer(this, handler, invoke); observer.SetResource(_source.Subscribe(observer)); } private void Add(Delegate handler, IDisposable disposable) { lock (_subscriptions) { if (!_subscriptions.TryGetValue(handler, out Stack<IDisposable> value)) { value = (_subscriptions[handler] = new Stack<IDisposable>()); } value.Push(disposable); } } protected void Remove(Delegate handler) { if ((object)handler == null) { throw new ArgumentNullException("handler"); } IDisposable disposable = null; lock (_subscriptions) { if (_subscriptions.TryGetValue(handler, out Stack<IDisposable> value)) { disposable = value.Pop(); if (value.Count == 0) { _subscriptions.Remove(handler); } } } disposable?.Dispose(); } } internal sealed class EventSource<T> : IEventSource<T> { private readonly IObservable<T> _source; private readonly Dictionary<Delegate, Stack<IDisposable>> _subscriptions; private readonly Action<Action<T>, T> _invokeHandler; public event Action<T> OnNext { add { Action<T> value2 = value; object gate = new object(); bool isAdded = false; bool isDone = false; Action remove = delegate { lock (gate) { if (isAdded) { Remove(value2); } else { isDone = true; } } }; IDisposable disposable = _source.Subscribe(delegate(T x) { _invokeHandler(value2, x); }, delegate(Exception ex) { remove(); ex.Throw(); }, remove); lock (gate) { if (!isDone) { Add(value2, disposable); isAdded = true; } } } remove { Remove(value); } } public EventSource(IObservable<T> source, Action<Action<T>, T> invokeHandler) { _source = source; _invokeHandler = invokeHandler; _subscriptions = new Dictionary<Delegate, Stack<IDisposable>>(); } private void Add(Delegate handler, IDisposable disposable) { lock (_subscriptions) { if (!_subscriptions.TryGetValue(handler, out Stack<IDisposable> value)) { value = (_subscriptions[handler] = new Stack<IDisposable>()); } value.Push(disposable); } } private void Remove(Delegate handler) { IDisposable disposable = null; lock (_subscriptions) { Stack<IDisposable> value = new Stack<IDisposable>(); if (_subscriptions.TryGetValue(handler, out value)) { disposable = value.Pop(); if (value.Count == 0) { _subscriptions.Remove(handler); } } } disposable?.Dispose(); } } [Experimental] [AttributeUsage(AttributeTargets.All)] public sealed class ExperimentalAttribute : Attribute { } public interface IEventPattern<out TSender, out TEventArgs> { TSender? Sender { get; } TEventArgs EventArgs { get; } } public interface IEventPatternSource<TEventArgs> { event EventHandler<TEventArgs> OnNext; } public interface IEventSource<out T> { event Action<T> OnNext; } internal sealed class AnonymousEnumerable<T> : IEnumerable<T>, IEnumerable { private readonly Func<IEnumerator<T>> _getEnumerator; public AnonymousEnumerable(Func<IEnumerator<T>> getEnumerator) { _getEnumerator = getEnumerator; } public IEnumerator<T> GetEnumerator() { return _getEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _getEnumerator(); } } internal sealed class AsyncLockObserver<T> : ObserverBase<T> { private readonly AsyncLock _gate; private readonly IObserver<T> _observer; public AsyncLockObserver(IObserver<T> observer, AsyncLock gate) { _gate = gate; _observer = observer; } protected override void OnNextCore(T value) { _gate.Wait((_observer, value), delegate((IObserver<T> _observer, T value) tuple) { tuple._observer.OnNext(tuple.value); }); } protected override void OnErrorCore(Exception exception) { _gate.Wait((_observer, exception), delegate((IObserver<T> _observer, Exception exception) tuple) { tuple._observer.OnError(tuple.exception); }); } protected override void OnCompletedCore() { _gate.Wait(_observer, delegate(IObserver<T> closureObserver) { closureObserver.OnCompleted(); }); } } internal sealed class AutoDetachObserver<T> : ObserverBase<T>, ISafeObserver<T>, IObserver<T>, IDisposable { private readonly IObserver<T> _observer; private SingleAssignmentDisposableValue _disposable; public AutoDetachObserver(IObserver<T> observer) { _observer = observer; } public void SetResource(IDisposable resource) { _disposable.Disposable = resource; } protected override void OnNextCore(T value) { bool flag = false; try { _observer.OnNext(value); flag = true; } finally { if (!flag) { Dispose(); } } } protected override void OnErrorCore(Exception exception) { try { _observer.OnError(exception); } finally { Dispose(); } } protected override void OnCompletedCore() { try { _observer.OnCompleted(); } finally { Dispose(); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _disposable.Dispose(); } } } internal sealed class BinaryObserver<TLeft, TRight> : IObserver<Either<Notification<TLeft>, Notification<TRight>>> { public IObserver<TLeft> LeftObserver { get; } public IObserver<TRight> RightObserver { get; } public BinaryObserver(IObserver<TLeft> leftObserver, IObserver<TRight> rightObserver) { LeftObserver = leftObserver; RightObserver = rightObserver; } public BinaryObserver(Action<Notification<TLeft>> left, Action<Notification<TRight>> right) : this(left.ToObserver(), right.ToObserver()) { } void IObserver<Either<Notification<TLeft>, Notification<TRight>>>.OnNext(Either<Notification<TLeft>, Notification<TRight>> value) { value.Switch(delegate(Notification<TLeft> left) { left.Accept(LeftObserver); }, delegate(Notification<TRight> right) { right.Accept(RightObserver); }); } void IObserver<Either<Notification<TLeft>, Notification<TRight>>>.OnError(Exception exception) { } void IObserver<Either<Notification<TLeft>, Notification<TRight>>>.OnCompleted() { } } internal sealed class CheckedObserver<T> : IObserver<T> { private readonly IObserver<T> _observer; private int _state; private const int Idle = 0; private const int Busy = 1; private const int Done = 2; public CheckedObserver(IObserver<T> observer) { _observer = observer; } public void OnNext(T value) { CheckAccess(); try { _observer.OnNext(value); } finally { Interlocked.Exchange(ref _state, 0); } } public void OnError(Exception error) { CheckAccess(); try { _observer.OnError(error); } finally { Interlocked.Exchange(ref _state, 2); } } public void OnCompleted() { CheckAccess(); try { _observer.OnCompleted(); } finally { Interlocked.Exchange(ref _state, 2); } } private void CheckAccess() { switch (Interlocked.CompareExchange(ref _state, 1, 0)) { case 1: throw new InvalidOperationException(Strings_Core.REENTRANCY_DETECTED); case 2: throw new InvalidOperationException(Strings_Core.OBSERVER_TERMINATED); } } } internal abstract class ConcatSink<TSource> : TailRecursiveSink<TSource> { protected ConcatSink(IObserver<TSource> observer) : base(observer) { } protected override IEnumerable<IObservable<TSource>>? Extract(IObservable<TSource> source) { return (source as IConcatenatable<TSource>)?.GetSources(); } public override void OnCompleted() { Recurse(); } } internal static class Constants_Core { private const string ObsoleteRefactoring = "This property is no longer supported due to refactoring of the API surface and elimination of platform-specific dependencies."; public const string ObsoleteSchedulerNewthread = "This property is no longer supported due to refactoring of the API surface and elimination of platform-specific dependencies. Please use NewThreadScheduler.Default to obtain an instance of this scheduler type."; public const string ObsoleteSchedulerTaskpool = "This property is no longer supported due to refactoring of the API surface and elimination of platform-specific dependencies. Please use TaskPoolScheduler.Default to obtain an instance of this scheduler type."; public const string ObsoleteSchedulerThreadpool = "This property is no longer supported due to refactoring of the API surface and elimination of platform-specific dependencies. Consider using Scheduler.Default to obtain the platform's most appropriate pool-based scheduler. In order to access a specific pool-based scheduler, please add a reference to the System.Reactive.PlatformServices assembly for your target platform and use the appropriate scheduler in the System.Reactive.Concurrency namespace."; public const string ObsoleteSchedulerequired = "This instance property is no longer supported. Use CurrentThreadScheduler.IsScheduleRequired instead."; internal const string AsQueryableTrimIncompatibilityMessage = "This type uses Queryable.AsQueryable, which is not compatible with trimming because expressions referencing IQueryable extension methods can get rebound to IEnumerable extension methods, and those IEnumerable methods might be trimmed."; internal const string EventReflectionTrimIncompatibilityMessage = "This member uses reflection to discover event members and associated delegate types."; } internal static class Constants_Linq { public const string UseAsync = "This blocking operation is no longer supported. Instead, use the async version in combination with C# and Visual Basic async/await support. In case you need a blocking operation, use Wait or convert the resulting observable sequence to a Task object and block."; public const string UseTaskFromAsyncPattern = "This conversion is no longer supported. Replace use of the Begin/End asynchronous method pair with a new Task-based async method, and convert the result using ToObservable. If no Task-based async method is available, use Task.Factory.FromAsync to obtain a Task object."; } internal abstract class Either<TLeft, TRight> { public sealed class Left : Either<TLeft, TRight>, IEquatable<Left> { public TLeft Value { get; } public Left(TLeft value) { Value = value; } public override TResult Switch<TResult>(Func<TLeft, TResult> caseLeft, Func<TRight, TResult> caseRight) { return caseLeft(Value); } public override void Switch(Action<TLeft> caseLeft, Action<TRight> caseRight) { caseLeft(Value); } public bool Equals(Left? other) { if (other == this) { return true; } if (other == null) { return false; } return EqualityComparer<TLeft>.Default.Equals(Value, other.Value); } public override bool Equals(object? obj) { return Equals(obj as Either<TLeft, TRight>.Left); } public override int GetHashCode() { TLeft value = Value; if (value == null) { return 0; } return value.GetHashCode(); } public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "Left({0})", Value); } } public sealed class Right : Either<TLeft, TRight>, IEquatable<Right> { public TRight Value { get; } public Right(TRight value) { Value = value; } public override TResult Switch<TResult>(Func<TLeft, TResult> caseLeft, Func<TRight, TResult> caseRight) { return caseRight(Value); } public override void Switch(Action<TLeft> caseLeft, Action<TRight> caseRight) { caseRight(Value); } public bool Equals(Right? other) { if (other == this) { return true; } if (other == null) { return false; } return EqualityComparer<TRight>.Default.Equals(Value, other.Value); } public override bool Equals(object? obj) { return Equals(obj as Either<TLeft, TRight>.Right); } public override int GetHashCode() { TRight value = Value; if (value == null) { return 0; } return value.GetHashCode(); } public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "Right({0})", Value); } } private Either() { } public static Either<TLeft, TRight> CreateLeft(TLeft value) { return new Left(value); } public static Either<TLeft, TRight> CreateRight(TRight value) { return new Right(value); } public abstract TResult Switch<TResult>(Func<TLeft, TResult> caseLeft, Func<TRight, TResult> caseRight); public abstract void Switch(Action<TLeft> caseLeft, Action<TRight> caseRight); } internal static class ExceptionHelper { public static Exception Terminated { get; } = new EndOfStreamException("On[Error|Completed]"); public static bool TrySetException(ref Exception? field, Exception ex) { return Interlocked.CompareExchange(ref field, ex, null) == null; } } internal static class ExceptionHelpers { private static readonly Lazy<IExceptionServices> Services = new Lazy<IExceptionServices>(Initialize); [DoesNotReturn] public static void Throw(this Exception exception) { Services.Value.Rethrow(exception); } private static IExceptionServices Initialize() { return PlatformEnlightenmentProvider.Current.GetService<IExceptionServices>(Array.Empty<object>()) ?? new DefaultExceptionServices(); } } internal sealed class Grouping<TKey, TElement> : Dictionary<TKey, Subject<TElement>> { public Grouping(IEqualityComparer<TKey> comparer) : base(comparer) { } public Grouping(int capacity, IEqualityComparer<TKey> comparer) : base(capacity, comparer) { } } internal static class HalfSerializer { public static void ForwardOnNext<T>(ISink<T> sink, T item, ref int wip, ref Exception? error) { if (Interlocked.CompareExchange(ref wip, 1, 0) == 0) { sink.ForwardOnNext(item); if (Interlocked.Decrement(ref wip) != 0) { Exception ex = error; if (ex != ExceptionHelper.Terminated) { error = ExceptionHelper.Terminated; sink.ForwardOnError(ex); } else { sink.ForwardOnCompleted(); } } } else if (error == null) { Trace.TraceWarning("OnNext called while another OnNext call was in progress on the same Observer."); } } public static void ForwardOnError<T>(ISink<T> sink, Exception ex, ref int wip, ref Exception? error) { if (ExceptionHelper.TrySetException(ref error, ex) && Interlocked.Increment(ref wip) == 1) { error = ExceptionHelper.Terminated; sink.ForwardOnError(ex); } } public static void ForwardOnCompleted<T>(ISink<T> sink, ref int wip, ref Exception? error) { if (ExceptionHelper.TrySetException(ref error, ExceptionHelper.Terminated) && Interlocked.Increment(ref wip) == 1) { sink.ForwardOnCompleted(); } } } internal static class Helpers { public static bool All(this bool[] values) { for (int i = 0; i < values.Length; i++) { if (!values[i]) { return false; } } return true; } public static bool AllExcept(this bool[] values, int index) { for (int i = 0; i < values.Length; i++) { if (i != index && !values[i]) { return false; } } return true; } } internal interface IConcatenatable<out TSource> { IEnumerable<IObservable<TSource>> GetSources(); } internal abstract class IdentitySink<T> : Sink<T, T> { protected IdentitySink(IObserver<T> observer) : base(observer) { } public override void OnNext(T value) { ForwardOnNext(value); } } internal interface IEvaluatableObservable<out T> { IObservable<T> Eval(); } internal sealed class ImmutableList<T> { public static readonly ImmutableList<T> Empty = new ImmutableList<T>(); private readonly T[] _data; public T[] Data => _data; private ImmutableList() { _data = Array.Empty<T>(); } public ImmutableList(T[] data) { _data = data; } public ImmutableList<T> Add(T value) { T[] array = new T[_data.Length + 1]; Array.Copy(_data, array, _data.Length); array[_data.Length] = value; return new ImmutableList<T>(array); } public ImmutableList<T> Remove(T value) { int num = Array.IndexOf(_data, value); if (num < 0) { return this; } int num2 = _data.Length; if (num2 == 1) { return Empty; } T[] array = new T[num2 - 1]; Array.Copy(_data, 0, array, 0, num); Array.Copy(_data, num + 1, array, num, num2 - num - 1); return new ImmutableList<T>(array); } } internal interface ISafeObserver<in T> : IObserver<T>, IDisposable { void SetResource(IDisposable resource); } internal sealed class Lookup<K, E> : ILookup<K, E>, IEnumerable<IGrouping<K, E>>, IEnumerable { private sealed class Grouping : IGrouping<K, E>, IEnumerable<E>, IEnumerable { private readonly KeyValuePair<K, List<E>> _keyValuePair; public K Key { get { KeyValuePair<K, List<E>> keyValuePair = _keyValuePair; return keyValuePair.Key; } } public Grouping(KeyValuePair<K, List<E>> keyValuePair) { _keyValuePair = keyValuePair; } public IEnumerator<E> GetEnumerator() { KeyValuePair<K, List<E>> keyValuePair = _keyValuePair; return keyValuePair.Value.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly Dictionary<K, List<E>> _dictionary; public int Count => _dictionary.Count; public IEnumerable<E> this[K key] { get { if (!_dictionary.TryGetValue(key, out var value)) { return Enumerable.Empty<E>(); } return Hide(value); } } public Lookup(IEqualityComparer<K> comparer) { _dictionary = new Dictionary<K, List<E>>(comparer); } public void Add(K key, E element) { if (!_dictionary.TryGetValue(key, out var value)) { value = (_dictionary[key] = new List<E>()); } value.Add(element); } public bool Contains(K key) { return _dictionary.ContainsKey(key); } private static IEnumerable<E> Hide(List<E> elements) { return elements.Skip(0); } public IEnumerator<IGrouping<K, E>> GetEnumerator() { foreach (KeyValuePair<K, List<E>> item in _dictionary) { yield return new Grouping(item); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal sealed class Map<TKey, TValue> { private const int DefaultConcurrencyMultiplier = 4; private readonly ConcurrentDictionary<TKey, TValue> _map; private static int DefaultConcurrencyLevel => 4 * Environment.ProcessorCount; public IEnumerable<TValue> Values => _map.Values.ToArray(); public Map(int? capacity, IEqualityComparer<TKey> comparer) { if (capacity.HasValue) { _map = new ConcurrentDictionary<TKey, TValue>(DefaultConcurrencyLevel, capacity.Value, comparer); } else { _map = new ConcurrentDictionary<TKey, TValue>(comparer); } } public TValue GetOrAdd(TKey key, Func<TValue> valueFactory, out bool added) { added = false; TValue val = default(TValue); bool flag = false; TValue value; while (!_map.TryGetValue(key, out value)) { if (!flag) { val = valueFactory(); flag = true; } if (_map.TryAdd(key, val)) { added = true; return val; } } return value; } public bool Remove(TKey key) { TValue value; return _map.TryRemove(key, out value); } } internal sealed class NopObserver<T> : IObserver<T> { public static readonly IObserver<T> Instance = new NopObserver<T>(); public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(T value) { } } internal sealed class PriorityQueue<T> where T : IComparable<T> { private struct IndexedItem : IComparable<IndexedItem> { public T Value; public long Id; public int CompareTo(IndexedItem other) { int num = Value.CompareTo(other.Value); if (num == 0) { num = Id.CompareTo(other.Id); } return num; } } private long _count = long.MinValue; private IndexedItem[] _items; private int _size; public int Count => _size; public PriorityQueue() : this(16) { } public PriorityQueue(int capacity) { _items = new IndexedItem[capacity]; _size = 0; } private bool IsHigherPriority(int left, int right) { return _items[left].CompareTo(_items[right]) < 0; } private int Percolate(int index) { if (index >= _size || index < 0) { return index; } int num = (index - 1) / 2; while (num >= 0 && num != index && IsHigherPriority(index, num)) { ref IndexedItem reference = ref _items[num]; ref IndexedItem reference2 = ref _items[index]; IndexedItem indexedItem = _items[index]; IndexedItem indexedItem2 = _items[num]; reference = indexedItem; reference2 = indexedItem2; index = num; num = (index - 1) / 2; } return index; } private void Heapify(int index) { if (index >= _size || index < 0) { return; } while (true) { int num = 2 * index + 1; int num2 = 2 * index + 2; int num3 = index; if (num < _size && IsHigherPriority(num, num3)) { num3 = num; } if (num2 < _size && IsHigherPriority(num2, num3)) { num3 = num2; } if (num3 != index) { ref IndexedItem reference = ref _items[num3]; ref IndexedItem reference2 = ref _items[index]; IndexedItem indexedItem = _items[index]; IndexedItem indexedItem2 = _items[num3]; reference = indexedItem; reference2 = indexedItem2; index = num3; continue; } break; } } public T Peek() { if (_size == 0) { throw new InvalidOperationException(Strings_Core.HEAP_EMPTY); } return _items[0].Value; } private void RemoveAt(int index) { _items[index] = _items[--_size]; _items[_size] = default(IndexedItem); if (Percolate(index) == index) { Heapify(index); } if (_size < _items.Length / 4) { IndexedItem[] items = _items; _items = new IndexedItem[_items.Length / 2]; Array.Copy(items, 0, _items, 0, _size); } } public T Dequeue() { T result = Peek(); RemoveAt(0); return result; } public void Enqueue(T item) { if (_size >= _items.Length) { IndexedItem[] items = _items; _items = new IndexedItem[_items.Length * 2]; Array.Copy(items, _items, items.Length); } int num = _size++; _items[num] = new IndexedItem { Value = item, Id = ++_count }; Percolate(num); } public bool Remove(T item) { for (int i = 0; i < _size; i++) { if (EqualityComparer<T>.Default.Equals(_items[i].Value, item)) { RemoveAt(i); return true; } } return false; } } internal interface IProducer<out TSource> : IObservable<TSource> { IDisposable SubscribeRaw(IObserver<TSource> observer, bool enableSafeguard); } internal abstract class BasicProducer<TSource> : IProducer<TSource>, IObservable<TSource> { public IDisposable Subscribe(IObserver<TSource> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } return SubscribeRaw(observer, enableSafeguard: true); } public IDisposable SubscribeRaw(IObserver<TSource> observer, bool enableSafeguard) { ISafeObserver<TSource> safeObserver = null; if (enableSafeguard) { observer = (safeObserver = SafeObserver<TSource>.Wrap(observer)); } IDisposable disposable; if (CurrentThreadScheduler.IsScheduleRequired) { SingleAssignmentDisposable singleAssignmentDisposable = new SingleAssignmentDisposable(); CurrentThreadScheduler.Instance.ScheduleAction((this, singleAssignmentDisposable, observer), ((BasicProducer<TSource> @this, SingleAssignmentDisposable runAssignable, IObserver<TSource> observer) tuple) => tuple.runAssignable.Disposable = tuple.@this.Run(tuple.observer)); disposable = singleAssignmentDisposable; } else { disposable = Run(observer); } safeObserver?.SetResource(disposable); return disposable; } protected abstract IDisposable Run(IObserver<TSource> observer); } internal abstract class Producer<TTarget, TSink> : IProducer<TTarget>, IObservable<TTarget> where TSink : IDisposable { public IDisposable Subscribe(IObserver<TTarget> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } return SubscribeRaw(observer, enableSafeguard: true); } public IDisposable SubscribeRaw(IObserver<TTarget> observer, bool enableSafeguard) { ISafeObserver<TTarget> safeObserver = null; if (enableSafeguard) { observer = (safeObserver = SafeObserver<TTarget>.Wrap(observer)); } TSink val = CreateSink(observer); safeObserver?.SetResource(val); if (CurrentThreadScheduler.IsScheduleRequired) { CurrentThreadScheduler.Instance.ScheduleAction((this, val), delegate((Producer<TTarget, TSink> @this, TSink sink) tuple) { tuple.@this.Run(tuple.sink); }); } else { Run(val); } return val; } protected abstract void Run(TSink sink); protected abstract TSink CreateSink(IObserver<TTarget> observer); } internal static class ReflectionUtils { public static TDelegate CreateDelegate<TDelegate>(object o, MethodInfo method) { return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), o); } public static Delegate CreateDelegate(Type delegateType, object o, MethodInfo method) { return method.CreateDelegate(delegateType, o); } public static void GetEventMethods<TSender, TEventArgs>(Type targetType, object? target, string eventName, out MethodInfo addMethod, out MethodInfo removeMethod, out Type delegateType, out bool isWinRT) { EventInfo @event; if (target == null) { @event = targetType.GetEvent(eventName, BindingFlags.Static | BindingFlags.Public); if (@event == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.COULD_NOT_FIND_STATIC_EVENT, eventName, targetType.FullName)); } } else { @event = targetType.GetEvent(eventName, BindingFlags.Instance | BindingFlags.Public); if (@event == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.COULD_NOT_FIND_INSTANCE_EVENT, eventName, targetType.FullName)); } } addMethod = @event.GetAddMethod() ?? throw new InvalidOperationException(Strings_Linq.EVENT_MISSING_ADD_METHOD); removeMethod = @event.GetRemoveMethod() ?? throw new InvalidOperationException(Strings_Linq.EVENT_MISSING_REMOVE_METHOD); ParameterInfo[] parameters = addMethod.GetParameters(); if (parameters.Length != 1) { throw new InvalidOperationException(Strings_Linq.EVENT_ADD_METHOD_SHOULD_TAKE_ONE_PARAMETER); } ParameterInfo[] parameters2 = removeMethod.GetParameters(); if (parameters2.Length != 1) { throw new InvalidOperationException(Strings_Linq.EVENT_REMOVE_METHOD_SHOULD_TAKE_ONE_PARAMETER); } isWinRT = false; if (IsWinRTEventRegistrationTokenType(addMethod.ReturnType)) { isWinRT = true; if (IsWinRTEventRegistrationTokenType(parameters2[0].ParameterType)) { throw new InvalidOperationException(Strings_Linq.EVENT_WINRT_REMOVE_METHOD_SHOULD_TAKE_ERT); } } delegateType = parameters[0].ParameterType; MethodInfo? method = delegateType.GetMethod("Invoke"); ParameterInfo[] parameters3 = method.GetParameters(); if (parameters3.Length != 2) { throw new InvalidOperationException(Strings_Linq.EVENT_PATTERN_REQUIRES_TWO_PARAMETERS); } if (!typeof(TSender).IsAssignableFrom(parameters3[0].ParameterType)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.EVENT_SENDER_NOT_ASSIGNABLE, typeof(TSender).FullName)); } if (!typeof(TEventArgs).IsAssignableFrom(parameters3[1].ParameterType)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.EVENT_ARGS_NOT_ASSIGNABLE, typeof(TEventArgs).FullName)); } if (method.ReturnType != typeof(void)) { throw new InvalidOperationException(Strings_Linq.EVENT_MUST_RETURN_VOID); } } private static bool IsWinRTEventRegistrationTokenType(Type t) { if (t.Name == "EventRegistrationToken") { if (!(t.Namespace == "System.Runtime.InteropServices.WindowsRuntime")) { return t.Namespace == "WinRT"; } return true; } return false; } } internal abstract class SafeObserver<TSource> : ISafeObserver<TSource>, IObserver<TSource>, IDisposable { private sealed class WrappingSafeObserver : SafeObserver<TSource> { private readonly IObserver<TSource> _observer; public WrappingSafeObserver(IObserver<TSource> observer) { _observer = observer; } public override void OnNext(TSource value) { bool flag = false; try { _observer.OnNext(value); flag = true; } finally { if (!flag) { Dispose(); } } } public override void OnError(Exception error) { using (this) { _observer.OnError(error); } } public override void OnCompleted() { using (this) { _observer.OnCompleted(); } } } private SingleAssignmentDisposableValue _disposable; public static ISafeObserver<TSource> Wrap(IObserver<TSource> observer) { if (observer is AnonymousObserver<TSource> anonymousObserver) { return anonymousObserver.MakeSafe(); } return new WrappingSafeObserver(observer); } public abstract void OnNext(TSource value); public abstract void OnError(Exception error); public abstract void OnCompleted(); public void SetResource(IDisposable resource) { _disposable.Disposable = resource; } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { if (disposing) { _disposable.Dispose(); } } } internal class ScheduledObserver<T> : ObserverBase<T>, IScheduledObserver<T>, IObserver<T>, IDisposable { private sealed class SemaphoreSlimRelease : IDisposable { private volatile SemaphoreSlim? _dispatcherEvent; public SemaphoreSlimRelease(SemaphoreSlim dispatcherEvent) { _dispatcherEvent = dispatcherEvent; } public void Dispose() { Interlocked.Exchange(ref _dispatcherEvent, null)?.Release(); } } private int _state; private const int Stopped = 0; private const int Running = 1; private const int Pending = 2; private const int Faulted = 9; private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>(); private bool _failed; private Exception? _error; private bool _completed; private readonly IObserver<T> _observer; private readonly IScheduler _scheduler; private readonly ISchedulerLongRunning? _longRunning; private SerialDisposableValue _disposable; private readonly object _dispatcherInitGate = new object(); private readonly SemaphoreSlim? _dispatcherEvent; private readonly IDisposable? _dispatcherEventRelease; private IDisposable? _dispatcherJob; public ScheduledObserver(IScheduler scheduler, IObserver<T> observer) { _scheduler = scheduler; _observer = observer; _longRunning = _scheduler.AsLongRunning(); if (_longRunning != null) { _dispatcherEvent = new SemaphoreSlim(0); _dispatcherEventRelease = new SemaphoreSlimRelease(_dispatcherEvent); } } private void EnsureDispatcher() { if (_dispatcherJob != null) { return; } lock (_dispatcherInitGate) { if (_dispatcherJob == null) { _dispatcherJob = _longRunning.ScheduleLongRunning(Dispatch); _disposable.Disposable = StableCompositeDisposable.Create(_dispatcherJob, _dispatcherEventRelease); } } } private void Dispatch(ICancelable cancel) { do { _dispatcherEvent.Wait(); if (cancel.IsDisposed) { return; } T result; while (_queue.TryDequeue(out result)) { try { _observer.OnNext(result); } catch { T result2; while (_queue.TryDequeue(out result2)) { } throw; } _dispatcherEvent.Wait(); if (cancel.IsDisposed) { return; } } if (_failed) { _observer.OnError(_error); Dispose(); return; } } while (!_completed); _observer.OnCompleted(); Dispose(); } public void EnsureActive() { EnsureActive(1); } public void EnsureActive(int n) { if (_longRunning != null) { if (n > 0) { _dispatcherEvent.Release(n); } EnsureDispatcher(); } else { EnsureActiveSlow(); } } private void EnsureActiveSlow() { bool flag = false; do { IL_0002: switch (Interlocked.CompareExchange(ref _state, 1, 0)) { default: goto IL_0002; case 0: flag = true; break; case 9: return; case 1: continue; case 2: break; } break; } while (Interlocked.CompareExchange(ref _state, 2, 1) != 1); if (flag) { _disposable.Disposable = _scheduler.Schedule<object>(null, Run); } } private void Run(object? state, Action<object?> recurse) { T result; while (!_queue.TryDequeue(out result)) { if (_failed) { if (_queue.IsEmpty) { Interlocked.Exchange(ref _state, 0); _observer.OnError(_error); Dispose(); return; } } else if (_completed) { if (_queue.IsEmpty) { Interlocked.Exchange(ref _state, 0); _observer.OnCompleted(); Dispose(); return; } } else { int num = Interlocked.CompareExchange(ref _state, 0, 1); if (num == 1 || num == 9) { return; } _state = 1; } } Interlocked.Exchange(ref _state, 1); try { _observer.OnNext(result); } catch { Interlocked.Exchange(ref _state, 9); T result2; while (_queue.TryDequeue(out result2)) { } throw; } recurse(state); } protected override void OnNextCore(T value) { _queue.Enqueue(value); } protected override void OnErrorCore(Exception exception) { _error = exception; _failed = true; } protected override void OnCompletedCore() { _completed = true; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _disposable.Dispose(); } } } internal sealed class ObserveOnObserver<T> : ScheduledObserver<T> { private SingleAssignmentDisposableValue _run; public ObserveOnObserver(IScheduler scheduler, IObserver<T> observer) : base(scheduler, observer) { } public void Run(IObservable<T> source) { _run.Disposable = source.SubscribeSafe(this); } protected override void OnNextCore(T value) { base.OnNextCore(value); EnsureActive(); } protected override void OnErrorCore(Exception exception) { base.OnErrorCore(exception); EnsureActive(); } protected override void OnCompletedCore() { base.OnCompletedCore(); EnsureActive(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _run.Dispose(); } } } internal interface IScheduledObserver<T> : IObserver<T>, IDisposable { void EnsureActive(); void EnsureActive(int count); } internal sealed class ObserveOnObserverNew<T> : IdentitySink<T> { private readonly IScheduler _scheduler; private readonly ConcurrentQueue<T> _queue; private IDisposable? _task; private int _wip; private bool _done; private Exception? _error; private bool _disposed; private static readonly Func<IScheduler, ObserveOnObserverNew<T>, IDisposable> DrainShortRunningFunc = (IScheduler scheduler, ObserveOnObserverNew<T> self) => self.DrainShortRunning(scheduler); public ObserveOnObserverNew(IScheduler scheduler, IObserver<T> downstream) : base(downstream) { _scheduler = scheduler; _queue = new ConcurrentQueue<T>(); } protected override void Dispose(bool disposing) { Volatile.Write(ref _disposed, value: true); base.Dispose(disposing); if (disposing) { Disposable.Dispose(ref _task); Clear(_queue); } } private static void Clear(ConcurrentQueue<T> q) { T result; while (q.TryDequeue(out result)) { } } public override void OnCompleted() { Volatile.Write(ref _done, value: true); Schedule(); } public override void OnError(Exception error) { _error = error; Volatile.Write(ref _done, value: true); Schedule(); } public override void OnNext(T value) { _queue.Enqueue(value); Schedule(); } private void Schedule() { if (Interlocked.Increment(ref _wip) == 1) { SingleAssignmentDisposable singleAssignmentDisposable = new SingleAssignmentDisposable(); if (Disposable.TrySetMultiple(ref _task, singleAssignmentDisposable)) { singleAssignmentDisposable.Disposable = _scheduler.Schedule(this, DrainShortRunningFunc); } if (Volatile.Read(ref _disposed)) { Clear(_queue); } } } private IDisposable DrainShortRunning(IScheduler recursiveScheduler) { DrainStep(_queue); if (Interlocked.Decrement(ref _wip) != 0) { IDisposable value = recursiveScheduler.Schedule(this, DrainShortRunningFunc); Disposable.TrySetMultiple(ref _task, value); } return Disposable.Empty; } private void DrainStep(ConcurrentQueue<T> q) { if (Volatile.Read(ref _disposed)) { Clear(q); return; } bool flag = Volatile.Read(ref _done); if (flag) { Exception error = _error; if (error != null) { Volatile.Write(ref _disposed, value: true); ForwardOnError(error); return; } } if (q.TryDequeue(out T result)) { ForwardOnNext(result); } else if (flag) { Volatile.Write(ref _disposed, value: true); ForwardOnCompleted(); } } } internal sealed class ObserveOnObserverLongRunning<TSource> : IdentitySink<TSource> { private readonly ISchedulerLongRunning _scheduler; private readonly ConcurrentQueue<TSource> _queue; private readonly object _suspendGuard; private long _wip; private bool _done; private Exception? _error; private bool _disposed; private int _runDrainOnce; private SingleAssignmentDisposableValue _drainTask; private static readonly Action<ObserveOnObserverLongRunning<TSource>, ICancelable> DrainLongRunning = delegate(ObserveOnObserverLongRunning<TSource> self, ICancelable cancelable) { self.Drain(); }; public ObserveOnObserverLongRunning(ISchedulerLongRunning scheduler, IObserver<TSource> observer) : base(observer) { _scheduler = scheduler; _queue = new ConcurrentQueue<TSource>(); _suspendGuard = new object(); } public override void OnCompleted() { Volatile.Write(ref _done, value: true); Schedule(); } public override void OnError(Exception error) { _error = error; Volatile.Write(ref _done, value: true); Schedule(); } public override void OnNext(TSource value) { _queue.Enqueue(value); Schedule(); } private void Schedule() { if (Volatile.Read(ref _runDrainOnce) == 0 && Interlocked.CompareExchange(ref _runDrainOnce, 1, 0) == 0) { _drainTask.Disposable = _scheduler.ScheduleLongRunning(this, DrainLongRunning); } if (Interlocked.Increment(ref _wip) == 1) { lock (_suspendGuard) { Monitor.Pulse(_suspendGuard); } } } protected override void Dispose(bool disposing) { Volatile.Write(ref _disposed, value: true); lock (_suspendGuard) { Monitor.Pulse(_suspendGuard); } _drainTask.Dispose(); base.Dispose(disposing); } private void Drain() { ConcurrentQueue<TSource> queue = _queue; while (true) { if (Volatile.Read(ref _disposed)) { TSource result; while (queue.TryDequeue(out result)) { } return; } bool num = Volatile.Read(ref _done); TSource result2; bool flag = queue.TryDequeue(out result2); if (num && !flag) { break; } if (flag) { ForwardOnNext(result2); if (Interlocked.Decrement(ref _wip) != 0L) { continue; } } if (Volatile.Read(ref _wip) != 0L || Volatile.Read(ref _disposed)) { continue; } object suspendGuard = _suspendGuard; if (Monitor.TryEnter(suspendGuard)) { if (Volatile.Read(ref _wip) == 0L && !Volatile.Read(ref _disposed)) { Monitor.Wait(suspendGuard); } Monitor.Exit(suspendGuard); } } Exception error = _error; if (error != null) { ForwardOnError(error); } else { ForwardOnCompleted(); } } } internal interface ISink<in TTarget> { void ForwardOnNext(TTarget value); void ForwardOnCompleted(); void ForwardOnError(Exception error); } internal abstract class Sink<TTarget> : ISink<TTarget>, IDisposable { private SingleAssignmentDisposableValue _upstream; private volatile IObserver<TTarget> _observer; protected Sink(IObserver<TTarget> observer) { _observer = observer; } public void Dispose() { if (Interlocked.Exchange(ref _observer, NopObserver<TTarget>.Instance) != NopObserver<TTarget>.Instance) { Dispose(disposing: true); } } protected virtual void Dispose(bool disposing) { _upstream.Dispose(); } public void ForwardOnNext(TTarget value) { _observer.OnNext(value); } public void ForwardOnCompleted() { _observer.OnCompleted(); Dispose(); } public void ForwardOnError(Exception error) { _observer.OnError(error); Dispose(); } protected void SetUpstream(IDisposable upstream) { _upstream.Disposable = upstream; } protected void DisposeUpstream() { _upstream.Dispose(); } } internal abstract class Sink<TSource, TTarget> : Sink<TTarget>, IObserver<TSource> { private sealed class @_ : IObserver<TTarget> { private readonly Sink<TSource, TTarget> _forward; public _(Sink<TSource, TTarget> forward) { _forward = forward; } public void OnNext(TTarget value) { _forward.ForwardOnNext(value); } public void OnError(Exception error) { _forward.ForwardOnError(error); } public void OnCompleted() { _forward.ForwardOnCompleted(); } } protected Sink(IObserver<TTarget> observer) : base(observer) { } public virtual void Run(IObservable<TSource> source) { SetUpstream(source.SubscribeSafe(this)); } public abstract void OnNext(TSource value); public virtual void OnError(Exception error) { ForwardOnError(error); } public virtual void OnCompleted() { ForwardOnCompleted(); } public IObserver<TTarget> GetForwarder() { return new @_(this); } } internal static class Stubs<T> { public static readonly Action<T> Ignore = delegate { }; public static readonly Func<T, T> I = (T _) => _; } internal static class Stubs { public static readonly Action Nop = delegate { }; public static readonly Action<Exception> Throw = delegate(Exception ex) { ex.Throw(); }; } internal static class TimerStubs { public static readonly System.Threading.Timer Never = new System.Threading.Timer(delegate { }); } internal sealed class SynchronizedObserver<T> : ObserverBase<T> { private readonly object _gate; private readonly IObserver<T> _observer; public SynchronizedObserver(IObserver<T> observer, object gate) { _gate = gate; _observer = observer; } protected override void OnNextCore(T value) { lock (_gate) { _observer.OnNext(value); } } protected override void OnErrorCore(Exception exception) { lock (_gate) { _observer.OnError(exception); } } protected override void OnCompletedCore() { lock (_gate) { _observer.OnCompleted(); } } } internal abstract class TailRecursiveSink<TSource> : IdentitySink<TSource> { private readonly Stack<IEnumerator<IObservable<TSource>>> _stack = new Stack<IEnumerator<IObservable<TSource>>>(); private bool _isDisposed; private int _trampoline; private IDisposable? _currentSubscription; protected TailRecursiveSink(IObserver<TSource> observer) : base(observer) { } public void Run(IEnumerable<IObservable<TSource>> sources) { if (TryGetEnumerator(sources, out IEnumerator<IObservable<TSource>> result)) { _stack.Push(result); Drain(); } } protected override void Dispose(bool disposing) { if (disposing) { DisposeAll(); } base.Dispose(disposing); } private void Drain() { if (Interlocked.Increment(ref _trampoline) != 1) { return; } do { IL_000f: if (Volatile.Read(ref _isDisposed)) { while (_stack.Count != 0) { _stack.Pop().Dispose(); } Disposable.Dispose(ref _currentSubscription); } else if (_stack.Count != 0) { IEnumerator<IObservable<TSource>> enumerator = _stack.Peek(); IObservable<TSource> source2 = null; try { if (enumerator.MoveNext()) { source2 = enumerator.Current; } } catch (Exception error) { enumerator.Dispose(); ForwardOnError(error); Volatile.Write(ref _isDisposed, value: true); goto IL_000f; } IObservable<TSource> observable; try { observable = Unpack<TSource>(source2); } catch (Exception error2) { if (!Fail(error2)) { Volatile.Write(ref _isDisposed, value: true); } goto IL_000f; } if (observable == null) { _stack.Pop(); enumerator.Dispose(); goto IL_000f; } IEnumerable<IObservable<TSource>> enumerable = Extract(observable); if (enumerable != null) { if (TryGetEnumerator(enumerable, out IEnumerator<IObservable<TSource>> result)) { _stack.Push(result); } else { Volatile.Write(ref _isDisposed, value: true); } goto IL_000f; } IDisposable ready = ReadyToken.Ready; if (Disposable.TrySetSingle(ref _currentSubscription, ready) != 0) { goto IL_000f; } IDisposable disposable = observable.SubscribeSafe(this); IDisposable disposable2 = Interlocked.CompareExchange(ref _currentSubscription, disposable, ready); if (disposable2 != ready) { disposable.Dispose(); if (disposable2 == BooleanDisposable.True) { goto IL_000f; } } } else { Volatile.Write(ref _isDisposed, value: true); Done(); } } while (Interlocked.Decrement(ref _trampoline) != 0); static IObservable<T>? Unpack<T>(IObservable<T>? source) where T : notnull { bool flag; do { flag = false; if (source is IEvaluatableObservable<T> evaluatableObservable) { source = evaluatableObservable.Eval(); flag = true; } } while (flag); return source; } } private void DisposeAll() { Volatile.Write(ref _isDisposed, value: true); Drain(); } protected void Recurse() { if (Disposable.TrySetSerial(ref _currentSubscription, null)) { Drain(); } } protected abstract IEnumerable<IObservable<TSource>>? Extract(IObservable<TSource> source); private bool TryGetEnumerator(IEnumerable<IObservable<TSource>> sources, [NotNullWhen(true)] out IEnumerator<IObservable<TSource>>? result) { try { result = sources.GetEnumerator(); return true; } catch (Exception error) { ForwardOnError(error); result = null; return false; } } protected virtual void Done() { ForwardOnCompleted(); } protected virtual bool Fail(Exception error) { ForwardOnError(error); return false; } } internal static class ReadyToken { private sealed class ReadyDisposable : IDisposable { public void Dispose() { } } internal static readonly IDisposable Ready = new ReadyDisposable(); } public interface IObserver<in TValue, out TResult> { TResult OnNext(TValue value); TResult OnError(Exception exception); TResult OnCompleted(); } [Experimental] public class ListObservable<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IObservable<object> { private readonly IDisposable _subscription; private readonly AsyncSubject<object> _subject = new AsyncSubject<object>(); private readonly List<T> _results = new List<T>(); public T Value { get { Wait(); if (_results.Count == 0) { throw new InvalidOperationException(Strings_Linq.NO_ELEMENTS); } return _results[_results.Count - 1]; } } public T this[int index] { get { Wait(); return _results[index]; } set { Wait(); _results[index] = value; } } public int Count { get { Wait(); return _results.Count; } } public bool IsReadOnly => false; public ListObservable(IObservable<T> source) { if (source == null) { throw new ArgumentNullException("source"); } _subscription = source.Subscribe(_results.Add, _subject.OnError, _subject.OnCompleted); } private void Wait() { _subject.DefaultIfEmpty().Wait(); } public int IndexOf(T item) { Wait(); return _results.IndexOf(item); } public void Insert(int index, T item) { Wait(); _results.Insert(index, item); } public void RemoveAt(int index) { Wait(); _results.RemoveAt(index); } public void Add(T item) { Wait(); _results.Add(item); } public void Clear() { Wait(); _results.Clear(); } public bool Contains(T item) { Wait(); return _results.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { Wait(); _results.CopyTo(array, arrayIndex); } public bool Remove(T item) { Wait(); return _results.Remove(item); } public IEnumerator<T> GetEnumerator() { Wait(); return _results.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IDisposable Subscribe(IObserver<object> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } return StableCompositeDisposable.Create(_subscription, _subject.Subscribe(observer)); } } [CompilerGenerated] internal class NamespaceDoc { } public enum NotificationKind { OnNext, OnError, OnCompleted } [Serializable] public abstract class Notification<T> : IEquatable<Notification<T>> { [Serializable] [DebuggerDisplay("OnNext({Value})")] internal sealed class OnNextNotification : Notification<T> { public override T Value { get; } public override Exception? Exception => null; public override bool HasValue => true; public override NotificationKind Kind => NotificationKind.OnNext; public OnNextNotification(T value) { Value = value; } public override int GetHashCode() { T value = Value; if (value == null) { return 0; } return value.GetHashCode(); } public override bool Equals(Notification<T>? other) { if ((object)this == other) { return true; } if ((object)other == null) { return false; } if (other.Kind != 0) { return false; } return EqualityComparer<T>.Default.Equals(Value, other.Value); } public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "OnNext({0})", Value); } public override void Accept(IObserver<T> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } observer.OnNext(Value); } public override TResult Accept<TResult>(IObserver<T, TResult> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } return observer.OnNext(Value); } public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted) { if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } onNext(Value); } public override TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted) { if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } return onNext(Value); } } [Serializable] [DebuggerDisplay("OnError({Exception})")] internal sealed class OnErrorNotification : Notification<T> { public override T Value { get { Exception.Throw(); return default(T); } } public override Exception Exception { get; } public override bool HasValue => false; public override NotificationKind Kind => NotificationKind.OnError; public OnErrorNotification(Exception exception) { Exception = exception; } public override int GetHashCode() { return Exception.GetHashCode(); } public override bool Equals(Notification<T>? other) { if ((object)this == other) { return true; } if ((object)other == null) { return false; } if (other.Kind != NotificationKind.OnError) { return false; } return object.Equals(Exception, other.Exception); } public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "OnError({0})", Exception.GetType().FullName); } public override void Accept(IObserver<T> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } observer.OnError(Exception); } public override TResult Accept<TResult>(IObserver<T, TResult> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } return observer.OnError(Exception); } public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted) { if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } onError(Exception); } public override TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted) { if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } return onError(Exception); } } [Serializable] [DebuggerDisplay("OnCompleted()")] internal sealed class OnCompletedNotification : Notification<T> { internal static readonly Notification<T> Instance = new Notification<T>.OnCompletedNotification(); public override T Value { get { throw new InvalidOperationException(Strings_Core.COMPLETED_NO_VALUE); } } public override Exception? Exception => null; public override bool HasValue => false; public override NotificationKind Kind => NotificationKind.OnCompleted; private OnCompletedNotification() { } public override int GetHashCode() { return typeof(T).GetHashCode() ^ 0x213E; } public override bool Equals(Notification<T>? other) { if ((object)this == other) { return true; } if ((object)other == null) { return false; } return other.Kind == NotificationKind.OnCompleted; } public override string ToString() { return "OnCompleted()"; } public override void Accept(IObserver<T> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } observer.OnCompleted(); } public override TResult Accept<TResult>(IObserver<T, TResult> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } return observer.OnCompleted(); } public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted) { if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } onCompleted(); } public override TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted) { if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } return onCompleted(); } } private sealed class NotificationToObservable : ObservableBase<T> { private readonly IScheduler _scheduler; private readonly Notification<T> _parent; public NotificationToObservable(IScheduler scheduler, Notification<T> parent) { _scheduler = scheduler; _parent = parent; } protected override IDisposable SubscribeCore(IObserver<T> observer) { return _scheduler.ScheduleAction((_parent, observer), delegate((Notification<T> _parent, IObserver<T> observer) state) { var (notification, observer2) = state; notification.Accept(observer2); if (notification.Kind == NotificationKind.OnNext) { observer2.OnCompleted(); } }); } } public abstract T Value { get; } public abstract bool HasValue { get; } public abstract Exception? Exception { get; } public abstract NotificationKind Kind { get; } protected internal Notification() { } public abstract bool Equals(Notification<T>? other); public static bool operator ==(Notification<T> left, Notification<T> right) { if ((object)left == right) { return true; } if ((object)left == null || (object)right == null) { return false; } return left.Equals(right); } public static bool operator !=(Notification<T> left, Notification<T> right) { return !(left == right); } public override bool Equals(object? obj) { return Equals(obj as Notification<T>); } public abstract void Accept(IObserver<T> observer); public abstract TResult Accept<TResult>(IObserver<T, TResult> observer); public abstract void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted); public abstract TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted); public IObservable<T> ToObservable() { return ToObservable(ImmediateScheduler.Instance); } public IObservable<T> ToObservable(IScheduler scheduler) { if (scheduler == null) { throw new ArgumentNullException("scheduler"); } return new NotificationToObservable(scheduler, this); } } public static class Notification { public static Notification<T> CreateOnNext<T>(T value) { return new Notification<T>.OnNextNotification(value); } public static Notification<T> CreateOnError<T>(Exception error) { if (error == null) { throw new ArgumentNullException("error"); } return new Notification<T>.OnErrorNotification(error); } public static Notification<T> CreateOnCompleted<T>() { return Notification<T>.OnCompletedNotification.Instance; } } public abstract class ObservableBase<T> : IObservable<T> { public IDisposable Subscribe(IObserver<T> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } AutoDetachObserver<T> autoDetachObserver = new AutoDetachObserver<T>(observer); if (CurrentThreadScheduler.IsScheduleRequired) { ((IScheduler)CurrentThreadScheduler.Instance).ScheduleAction(autoDetachObserver, (Action<AutoDetachObserver<T>>)ScheduledSubscribe); } else { try { autoDetachObserver.SetResource(SubscribeCore(autoDetachObserver)); } catch (Exception error) { if (!autoDetachObserver.Fail(error)) { throw; } } } return autoDetachObserver; } private void ScheduledSubscribe(AutoDetachObserver<T> autoDetachObserver) { try { autoDetachObserver.SetResource(SubscribeCore(autoDetachObserver)); } catch (Exception error) { if (!autoDetachObserver.Fail(error)) { throw; } } } protected abstract IDisposable SubscribeCore(IObserver<T> observer); } internal class ObservableQueryProvider : IQbservableProvider, IQueryProvider { private static MethodInfo? _staticAsQueryable; private static MethodInfo AsQueryable => _staticAsQueryable ?? (_staticAsQueryable = Qbservable.InfoOf((Expression<Func<object>>)(() => ((IEnumerable<object>)null).AsQueryable())).GetGenericMethodDefinition()); public IQbservable<TResult> CreateQuery<TResult>(Expression expression) { if (expression == null) { throw new ArgumentNullException("expression"); } if (!typeof(IObservable<TResult>).IsAssignableFrom(expression.Type)) { throw new ArgumentException(Strings_Providers.INVALID_TREE_TYPE, "expression"); } return new ObservableQuery<TResult>(expression); } IQueryable<TElement> IQueryProvider.CreateQuery<TElement>(Expression expression) { if (!(expression is MethodCallExpression methodCallExpression) || methodCallExpression.Method.DeclaringType != typeof(Qbservable) || methodCallExpression.Method.Name != "ToQueryable") { throw new ArgumentException(Strings_Providers.EXPECTED_TOQUERYABLE_METHODCALL, "expression"); } Expression arg = methodCallExpression.Arguments[0]; return Expression.Lambda<Func<IQueryable<TElement>>>(Expression.Call(AsQueryable.MakeGenericMethod(typeof(TElement)), Expression.Call(typeof(Observable).GetMethod("ToEnumerable").MakeGenericMethod(typeof(TElement)), arg)), Array.Empty<ParameterExpression>()).Compile()(); } IQueryable IQueryProvider.CreateQuery(Expression expression) { throw new NotImplementedException(); } TResult IQueryProvider.Execute<TResult>(Expression expression) { throw new NotImplementedException(); } object IQueryProvider.Execute(Expression expression) { throw new NotImplementedException(); } } internal class ObservableQuery { protected object? _source; protected Expression _expression; public object? Source => _source; public Expression Expression => _expression; public ObservableQuery(object source) { _source = source; _expression = System.Linq.Expressions.Expression.Constant(this); } public ObservableQuery(Expression expression) { _expression = expression; } } internal class ObservableQuery<TSource> : ObservableQuery, IQbservable<TSource>, IQbservable, IObservable<TSource> { private class ObservableRewriter : ExpressionVisitor { private class Lazy<T> { private readonly Func<T> _factory; private T? _value; private bool _initialized; public T Value { get { lock (_factory) { if (!_initialized) { _value = _factory(); _initialized = true; } } return _value; } } public Lazy(Func<T> factory) { _factory = factory; } } private static readonly Lazy<ILookup<string, MethodInfo>> ObservableMethods = new Lazy<ILookup<string, MethodInfo>>(() => GetMethods(typeof(Observable))); protected override Expression VisitConstant(ConstantExpression node) { if (node.Value is ObservableQuery observableQuery) { object source = observableQuery.Source; if (source != null) { return System.Linq.Expressions.Expression.Constant(source); } return Visit(observableQuery.Expression); } return node; } protected override Expression VisitMethodCall(MethodCallExpression node) { MethodInfo method = node.Method; if (method.DeclaringType?.BaseType == typeof(QueryablePattern)) { if (method.Name == "Then") { return System.Linq.Expressions.Expression.Call(Visit(node.Object), arguments: node.Arguments.Select((Expression arg) => Unquote(Visit(arg))).ToArray(), methodName: method.Name, typeArguments: method.GetGenericArguments()); } if (method.Name == "And") { return System.Linq.Expressions.Expression.Call(Visit(node.Object), arguments: node.Arguments.Select((Expression arg) => Visit(arg)).ToArray(), methodName: method.Name, typeArguments: method.GetGenericArguments()); } } else { IEnumerable<Expression> enumerable = node.Arguments.AsEnumerable(); bool flag = false; ParameterInfo parameterInfo = method.GetParameters().FirstOrDefault(); if (parameterInfo != null) { Type parameterType = parameterInfo.ParameterType; if (parameterType == typeof(IQbservableProvider)) { flag = true; if (!(System.Linq.Expressions.Expression.Lambda<Func<IQbservableProvider>>(Visit(node.Arguments[0]), Array.Empty<ParameterExpression>()).Compile()() is ObservableQueryProvider)) { return node; } enumerable = enumerable.Skip(1); } else if (typeof(IQbservable).IsAssignableFrom(parameterType)) { flag = true; } } if (flag) { IList<Expression> arguments3 = VisitQbservableOperatorArguments(method, enumerable); return FindObservableMethod(method, arguments3); } } return base.VisitMethodCall(node); } protected override Expression VisitLambda<T>(Expression<T> node) { return node; } private IList<Expression> VisitQbservableOperatorArguments(MethodInfo method, IEnumerable<Expression> arguments) { if (method.Name == "When") { Expression expression = arguments.Last(); if (expression.NodeType == ExpressionType.NewArrayInit) { NewArrayExpression newArrayExpression = (NewArrayExpression)expression; List<Expression> list = new List<Expression>(); list.Add(System.Linq.Expressions.Expression.NewArrayInit(typeof(Plan<>).MakeGenericType(method.GetGenericArguments()[0]), newArrayExpression.Expressions.Select((Expression param) => Visit(param)))); return list; } } return arguments.Select((Expression arg) => Visit(arg)).ToList(); } private static MethodCallExpression FindObservableMethod(MethodInfo method, IList<Expression> arguments) { IList<Expression> arguments2 = arguments; Type type; ILookup<string, MethodInfo> lookup; if (method.DeclaringType == typeof(Qbservable)) { type = typeof(Observable); lookup = ObservableMethods.Value; } else { type = method.DeclaringType; if (type.IsDefined(typeof(LocalQueryMethodImplementationTypeAttribute), inherit: false)) { type = ((LocalQueryMethodImplementationTypeAttribute)type.GetCustomAttributes(typeof(LocalQueryMethodImplementationTypeAttribute), inherit: false)[0]).TargetType; } lookup = GetMethods(type); } Type[] typeArgs = (method.IsGenericMethod ? method.GetGenericArguments() : null); MethodInfo methodInfo = lookup[method.Name].FirstOrDefault((MethodInfo candidateMethod) => ArgsMatch(candidateMethod, arguments2, typeArgs)) ?? throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Providers.NO_MATCHING_METHOD_FOUND, method.Name, type.Name)); if (typeArgs != null) { methodInfo = methodInfo.MakeGenericMethod(typeArgs); } ParameterInfo[] parameters = methodInfo.GetParameters(); int i = 0; for (int num = parameters.Length; i < num; i++) { arguments2[i] = Unquote(arguments2[i]); } return System.Linq.Expressions.Expression.Call(null, methodInfo, arguments2); } private static ILookup<string, MethodInfo> GetMethods(Type type) { return type.GetTypeInfo().DeclaredMethods.Where((MethodInfo m) => m.IsStatic && m.IsPublic).ToLookup((MethodInfo m) => m.Name); } private static bool ArgsMatch(MethodInfo method, IList<Expression> arguments, Type[]? typeArgs) { ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length != arguments.Count) { return false; } if (!method.IsGenericMethod && typeArgs != null && typeArgs.Length != 0) { return false; } if (method.IsGenericMethodDefinition) { if (typeArgs == null) { return false; } if (method.GetGenericArguments().Length != typeArgs.Length) { return false; } parameters = method.MakeGenericMethod(typeArgs).GetParameters(); } int i = 0; for (int count = arguments.Count; i < count; i++) { Type parameterType = parameters[i].ParameterType; Expression expression = arguments[i]; if (!parameterType.IsAssignableFrom(expression.Type)) { expression = Unquote(expression); if (!parameterType.IsAssignableFrom(expression.Type)) { return false; } } } return true; } private static Expression Unquote(Expression expression) { while (expression.NodeType == ExpressionType.Quote) { expression = ((UnaryExpression)expression).Operand; } return expression; } } public Type ElementType => typeof(TSource); public IQbservableProvider Provider => Qbservable.Provider; internal ObservableQuery(IObservable<TSource> source) : base(source) { } internal ObservableQuery(Expression expression) : base(expression) { } public IDisposable Subscribe(IObserver<TSource> observer) { if (_source == null) { Expression<Func<IObservable<TSource>>> expression = System.Linq.Expressions.Expression.Lambda<Func<IObservable<TSource>>>(new ObservableRewriter().Visit(_expression), Array.Empty<ParameterExpression>()); _source = expression.Compile()(); } return ((IObservable<TSource>)_source).Subscribe(observer); } public override string? ToString() { if (_expression is ConstantExpression constantExpression && constantExpression.Value == this) { if (_source != null) { return _source.ToString(); } return "null"; } return _expression.ToString(); } } public static class Observer { private class AnonymousProgress<T> : IProgress<T> { private readonly Action<T> _progress; public AnonymousProgress(Action<T> progress) { _progress = progress; } public void Report(T value) { _progress(value); } } public static IObserver<T> ToObserver<T>(this Action<Notification<T>> handler) { Action<Notification<T>> handler2 = handler; if (handler2 == null) { throw new ArgumentNullException("handler"); } return new AnonymousObserver<T>(delegate(T x) { handler2(Notification.CreateOnNext(x)); }, delegate(Exception exception) { handler2(Notification.CreateOnError<T>(exception)); }, delegate { handler2(Notification.CreateOnCompleted<T>()); }); } public static Action<Notification<T>> ToNotifier<T>(this IObserver<T> observer) { IObserver<T> observer2 = observer; if (observer2 == null) { throw new ArgumentNullException("observer"); } return delegate(Notification<T> n) { n.Accept(observer2); }; } public static IObserver<T> Create<T>(Action<T> onNext) { if (onNext == null) { throw new ArgumentNullException("onNext"); } return new AnonymousObserver<T>(onNext); } public static IObserver<T> Create<T>(Action<T> onNext, Action<Exception> onError) { if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } return new AnonymousObserver<T>(onNext, onError); } public static IObserver<T> Create<T>(Action<T> onNext, Action onCompleted) { if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } return new AnonymousObserver<T>(onNext, onCompleted); } public static IObserver<T> Create<T>(Action<T> onNext, Action<Exception> onError, Action onCompleted) { if (onNext == null) { throw new ArgumentNullException("onNext"); } if (onError == null) { throw new ArgumentNullException("onError"); } if (onCompleted == null) { throw new ArgumentNullException("onCompleted"); } return new AnonymousObserver<T>(onNext, onError, onCompleted); } public static IObserver<T> AsObserver<T>(this IObserver<T> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } return new AnonymousObserver<T>(observer.OnNext, observer.OnError, observer.OnCompleted); } public static IObserver<T> Checked<T>(this IObserver<T> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } return new CheckedObserver<T>(observer); } public static IObserver<T> Synchronize<T>(IObserver<T> observer) { if (observer == null) { throw new ArgumentNullException("observer"); } return new SynchronizedObserver<T>(observer, new object()); } public static IObserver<T> Synchronize<T>(IObserver<T> observer, bool preventReentrancy) { if (observer == null) { throw new ArgumentNullException("observer"); } if (preventReentrancy) { return new AsyncLockObserver<T>(observer, new AsyncLock()); } return new SynchronizedObserver<T>(observer, new object()); } public static IObserver<T> Synchronize<T>(IObserve
BepInEx/plugins/VNyanCommands/System.Reflection.TypeExtensions.dll
Decompiled 2 years agousing System; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using FxResources.System.Reflection.TypeExtensions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyDefaultAlias("System.Reflection.TypeExtensions")] [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.Reflection.TypeExtensions")] [assembly: AssemblyFileVersion("4.700.19.56404")] [assembly: AssemblyInformationalVersion("3.1.0+0f7f38c4fd323b26da10cce95f857f77f0f09b48")] [assembly: AssemblyProduct("Microsoft® .NET Core")] [assembly: AssemblyTitle("System.Reflection.TypeExtensions")] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("4.1.5.0")] [assembly: TypeForwardedTo(typeof(BindingFlags))] namespace FxResources.System.Reflection.TypeExtensions { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string NoMetadataTokenAvailable => GetResourceString("NoMetadataTokenAvailable"); internal static string PlatformNotSupported_ReflectionTypeExtensions => GetResourceString("PlatformNotSupported_ReflectionTypeExtensions"); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } 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; } 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.Reflection { internal static class Requires { internal static void NotNull(object obj, string name) { if (obj == null) { throw new ArgumentNullException(name); } } } public static class TypeExtensions { public static ConstructorInfo GetConstructor(Type type, Type[] types) { Requires.NotNull(type, "type"); return type.GetConstructor(types); } public static ConstructorInfo[] GetConstructors(Type type) { Requires.NotNull(type, "type"); return type.GetConstructors(); } public static ConstructorInfo[] GetConstructors(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetConstructors(bindingAttr); } public static MemberInfo[] GetDefaultMembers(Type type) { Requires.NotNull(type, "type"); return type.GetDefaultMembers(); } public static EventInfo GetEvent(Type type, string name) { Requires.NotNull(type, "type"); return type.GetEvent(name); } public static EventInfo GetEvent(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetEvent(name, bindingAttr); } public static EventInfo[] GetEvents(Type type) { Requires.NotNull(type, "type"); return type.GetEvents(); } public static EventInfo[] GetEvents(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetEvents(bindingAttr); } public static FieldInfo GetField(Type type, string name) { Requires.NotNull(type, "type"); return type.GetField(name); } public static FieldInfo GetField(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetField(name, bindingAttr); } public static FieldInfo[] GetFields(Type type) { Requires.NotNull(type, "type"); return type.GetFields(); } public static FieldInfo[] GetFields(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetFields(bindingAttr); } public static Type[] GetGenericArguments(Type type) { Requires.NotNull(type, "type"); return type.GetGenericArguments(); } public static Type[] GetInterfaces(Type type) { Requires.NotNull(type, "type"); return type.GetInterfaces(); } public static MemberInfo[] GetMember(Type type, string name) { Requires.NotNull(type, "type"); return type.GetMember(name); } public static MemberInfo[] GetMember(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetMember(name, bindingAttr); } public static MemberInfo[] GetMembers(Type type) { Requires.NotNull(type, "type"); return type.GetMembers(); } public static MemberInfo[] GetMembers(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetMembers(bindingAttr); } public static MethodInfo GetMethod(Type type, string name) { Requires.NotNull(type, "type"); return type.GetMethod(name); } public static MethodInfo GetMethod(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetMethod(name, bindingAttr); } public static MethodInfo GetMethod(Type type, string name, Type[] types) { Requires.NotNull(type, "type"); return type.GetMethod(name, types); } public static MethodInfo[] GetMethods(Type type) { Requires.NotNull(type, "type"); return type.GetMethods(); } public static MethodInfo[] GetMethods(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetMethods(bindingAttr); } public static Type GetNestedType(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetNestedType(name, bindingAttr); } public static Type[] GetNestedTypes(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetNestedTypes(bindingAttr); } public static PropertyInfo[] GetProperties(Type type) { Requires.NotNull(type, "type"); return type.GetProperties(); } public static PropertyInfo[] GetProperties(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetProperties(bindingAttr); } public static PropertyInfo GetProperty(Type type, string name) { Requires.NotNull(type, "type"); return type.GetProperty(name); } public static PropertyInfo GetProperty(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetProperty(name, bindingAttr); } public static PropertyInfo GetProperty(Type type, string name, Type returnType) { Requires.NotNull(type, "type"); return type.GetProperty(name, returnType); } public static PropertyInfo GetProperty(Type type, string name, Type returnType, Type[] types) { Requires.NotNull(type, "type"); return type.GetProperty(name, returnType, types); } public static bool IsAssignableFrom(Type type, Type c) { Requires.NotNull(type, "type"); return type.IsAssignableFrom(c); } public static bool IsInstanceOfType(Type type, object o) { Requires.NotNull(type, "type"); return type.IsInstanceOfType(o); } } public static class AssemblyExtensions { public static Type[] GetExportedTypes(Assembly assembly) { Requires.NotNull(assembly, "assembly"); return assembly.GetExportedTypes(); } public static Module[] GetModules(Assembly assembly) { Requires.NotNull(assembly, "assembly"); return assembly.GetModules(); } public static Type[] GetTypes(Assembly assembly) { Requires.NotNull(assembly, "assembly"); return assembly.GetTypes(); } } public static class EventInfoExtensions { public static MethodInfo GetAddMethod(EventInfo eventInfo) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetAddMethod(); } public static MethodInfo GetAddMethod(EventInfo eventInfo, bool nonPublic) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetAddMethod(nonPublic); } public static MethodInfo GetRaiseMethod(EventInfo eventInfo) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetRaiseMethod(); } public static MethodInfo GetRaiseMethod(EventInfo eventInfo, bool nonPublic) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetRaiseMethod(nonPublic); } public static MethodInfo GetRemoveMethod(EventInfo eventInfo) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetRemoveMethod(); } public static MethodInfo GetRemoveMethod(EventInfo eventInfo, bool nonPublic) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetRemoveMethod(nonPublic); } } public static class MemberInfoExtensions { public static bool HasMetadataToken(this MemberInfo member) { Requires.NotNull(member, "member"); try { return GetMetadataTokenOrZeroOrThrow(member) != 0; } catch (InvalidOperationException) { return false; } } public static int GetMetadataToken(this MemberInfo member) { Requires.NotNull(member, "member"); int metadataTokenOrZeroOrThrow = GetMetadataTokenOrZeroOrThrow(member); if (metadataTokenOrZeroOrThrow == 0) { throw new InvalidOperationException(System.SR.NoMetadataTokenAvailable); } return metadataTokenOrZeroOrThrow; } private static int GetMetadataTokenOrZeroOrThrow(MemberInfo member) { int metadataToken = member.MetadataToken; if ((metadataToken & 0xFFFFFF) == 0) { return 0; } return metadataToken; } } public static class MethodInfoExtensions { public static MethodInfo GetBaseDefinition(MethodInfo method) { Requires.NotNull(method, "method"); return method.GetBaseDefinition(); } } public static class ModuleExtensions { public static bool HasModuleVersionId(this Module module) { Requires.NotNull(module, "module"); return true; } public static Guid GetModuleVersionId(this Module module) { Requires.NotNull(module, "module"); return module.ModuleVersionId; } } public static class PropertyInfoExtensions { public static MethodInfo[] GetAccessors(PropertyInfo property) { Requires.NotNull(property, "property"); return property.GetAccessors(); } public static MethodInfo[] GetAccessors(PropertyInfo property, bool nonPublic) { Requires.NotNull(property, "property"); return property.GetAccessors(nonPublic); } public static MethodInfo GetGetMethod(PropertyInfo property) { Requires.NotNull(property, "property"); return property.GetGetMethod(); } public static MethodInfo GetGetMethod(PropertyInfo property, bool nonPublic) { Requires.NotNull(property, "property"); return property.GetGetMethod(nonPublic); } public static MethodInfo GetSetMethod(PropertyInfo property) { Requires.NotNull(property, "property"); return property.GetSetMethod(); } public static MethodInfo GetSetMethod(PropertyInfo property, bool nonPublic) { Requires.NotNull(property, "property"); return property.GetSetMethod(nonPublic); } } }
BepInEx/plugins/VNyanCommands/System.Runtime.CompilerServices.Unsafe.dll
Decompiled 2 years agousing System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyFileVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.0.0.0")] [assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: CLSCompliant(false)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyVersion("4.0.4.1")] namespace System.Runtime.CompilerServices { public static class Unsafe : Object { [MethodImpl(256)] [NonVersionable] public unsafe static T Read<T>(void* source) { return Unsafe.Read<T>(source); } [MethodImpl(256)] [NonVersionable] public unsafe static T ReadUnaligned<T>(void* source) { return Unsafe.ReadUnaligned<T>(source); } [MethodImpl(256)] [NonVersionable] public static T ReadUnaligned<T>(ref byte source) { return Unsafe.ReadUnaligned<T>(ref source); } [MethodImpl(256)] [NonVersionable] public unsafe static void Write<T>(void* destination, T value) { Unsafe.Write(destination, value); } [MethodImpl(256)] [NonVersionable] public unsafe static void WriteUnaligned<T>(void* destination, T value) { Unsafe.WriteUnaligned(destination, value); } [MethodImpl(256)] [NonVersionable] public static void WriteUnaligned<T>(ref byte destination, T value) { Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(256)] [NonVersionable] public unsafe static void Copy<T>(void* destination, ref T source) { Unsafe.Write(destination, source); } [MethodImpl(256)] [NonVersionable] public unsafe static void Copy<T>(ref T destination, void* source) { destination = Unsafe.Read<T>(source); } [MethodImpl(256)] [NonVersionable] public unsafe static void* AsPointer<T>(ref T value) { return Unsafe.AsPointer(ref value); } [MethodImpl(256)] [NonVersionable] public static int SizeOf<T>() { return Unsafe.SizeOf<T>(); } [MethodImpl(256)] [NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(256)] [NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(256)] [NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(256)] [NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(256)] [NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(256)] [NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(256)] [NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(256)] [NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(256)] [NonVersionable] public static T As<T>(object o) where T : class { return (T)o; } [MethodImpl(256)] [NonVersionable] public unsafe static ref T AsRef<T>(void* source) { return ref *(T*)source; } [MethodImpl(256)] [NonVersionable] public static ref T AsRef<T>(in T source) { return ref source; } [MethodImpl(256)] [NonVersionable] public static ref TTo As<TFrom, TTo>(ref TFrom source) { return ref Unsafe.As<TFrom, TTo>(ref source); } [MethodImpl(256)] [NonVersionable] public static ref T Add<T>(ref T source, int elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(256)] [NonVersionable] public unsafe static void* Add<T>(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(256)] [NonVersionable] public static ref T Add<T>(ref T source, System.IntPtr elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(256)] [NonVersionable] public static ref T AddByteOffset<T>(ref T source, System.IntPtr byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(256)] [NonVersionable] public static ref T Subtract<T>(ref T source, int elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(256)] [NonVersionable] public unsafe static void* Subtract<T>(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(256)] [NonVersionable] public static ref T Subtract<T>(ref T source, System.IntPtr elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(256)] [NonVersionable] public static ref T SubtractByteOffset<T>(ref T source, System.IntPtr byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(256)] [NonVersionable] public static System.IntPtr ByteOffset<T>(ref T origin, ref T target) { return Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(256)] [NonVersionable] public static bool AreSame<T>(ref T left, ref T right) { return Unsafe.AreSame(ref left, ref right); } [MethodImpl(256)] [NonVersionable] public static bool IsAddressGreaterThan<T>(ref T left, ref T right) { return Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(256)] [NonVersionable] public static bool IsAddressLessThan<T>(ref T left, ref T right) { return Unsafe.IsAddressLessThan(ref left, ref right); } } } namespace System.Runtime.Versioning { [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { internal sealed class IsReadOnlyAttribute : Attribute { } }
BepInEx/plugins/VNyanCommands/System.Threading.Channels.dll
Decompiled 2 years agousing System; using System.Collections.Concurrent; 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.Serialization; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using FxResources.System.Threading.Channels; using Internal; 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(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Threading.Channels")] [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 passing data between producers and consumers.\r\n\r\nCommonly Used Types:\r\nSystem.Threading.Channel\r\nSystem.Threading.Channel<T>")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Threading.Channels")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.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.System.Threading.Channels { 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 { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct VoidResult { } 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 ChannelClosedException_DefaultMessage => GetResourceString("ChannelClosedException_DefaultMessage"); internal static string InvalidOperation_IncompleteAsyncOperation => GetResourceString("InvalidOperation_IncompleteAsyncOperation"); internal static string InvalidOperation_MultipleContinuations => GetResourceString("InvalidOperation_MultipleContinuations"); internal static string InvalidOperation_IncorrectToken => GetResourceString("InvalidOperation_IncorrectToken"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.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.Collections.Generic { [DebuggerDisplay("Count = {_size}")] internal sealed class Deque<T> { private T[] _array = Array.Empty<T>(); private int _head; private int _tail; private int _size; public int Count => _size; public bool IsEmpty => _size == 0; public void EnqueueTail(T item) { if (_size == _array.Length) { Grow(); } _array[_tail] = item; if (++_tail == _array.Length) { _tail = 0; } _size++; } public T DequeueHead() { T result = _array[_head]; _array[_head] = default(T); if (++_head == _array.Length) { _head = 0; } _size--; return result; } public T PeekHead() { return _array[_head]; } public T PeekTail() { int num = _tail - 1; if (num == -1) { num = _array.Length - 1; } return _array[num]; } public T DequeueTail() { if (--_tail == -1) { _tail = _array.Length - 1; } T result = _array[_tail]; _array[_tail] = default(T); _size--; return result; } public IEnumerator<T> GetEnumerator() { int pos = _head; int count = _size; while (count-- > 0) { yield return _array[pos]; pos = (pos + 1) % _array.Length; } } private void Grow() { int num = (int)((long)_array.Length * 2L); if (num < _array.Length + 4) { num = _array.Length + 4; } T[] array = new T[num]; if (_head == 0) { Array.Copy(_array, array, _size); } else { Array.Copy(_array, _head, array, 0, _array.Length - _head); Array.Copy(_array, 0, array, _array.Length - _head, _tail); } _array = array; _head = 0; _tail = _size; } } } namespace System.Collections.Concurrent { [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))] internal sealed class SingleProducerSingleConsumerQueue<T> : IEnumerable<T>, IEnumerable { [StructLayout(LayoutKind.Sequential)] private sealed class Segment { internal Segment _next; internal readonly T[] _array; internal SegmentState _state; internal Segment(int size) { _array = new T[size]; } } private struct SegmentState { internal Internal.PaddingFor32 _pad0; internal volatile int _first; internal int _lastCopy; internal Internal.PaddingFor32 _pad1; internal int _firstCopy; internal volatile int _last; internal Internal.PaddingFor32 _pad2; } private sealed class SingleProducerSingleConsumerQueue_DebugView { private readonly SingleProducerSingleConsumerQueue<T> _queue; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => new List<T>(_queue).ToArray(); public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue) { _queue = queue; } } private const int InitialSegmentSize = 32; private const int MaxSegmentSize = 16777216; private volatile Segment _head; private volatile Segment _tail; public bool IsEmpty { get { Segment head = _head; if (head._state._first != head._state._lastCopy) { return false; } if (head._state._first != head._state._last) { return false; } return head._next == null; } } internal int Count { get { int num = 0; for (Segment segment = _head; segment != null; segment = segment._next) { int num2 = segment._array.Length; int first; int last; do { first = segment._state._first; last = segment._state._last; } while (first != segment._state._first); num += (last - first) & (num2 - 1); } return num; } } public SingleProducerSingleConsumerQueue() { _head = (_tail = new Segment(32)); } public void Enqueue(T item) { Segment segment = _tail; T[] array = segment._array; int last = segment._state._last; int num = (last + 1) & (array.Length - 1); if (num != segment._state._firstCopy) { array[last] = item; segment._state._last = num; } else { EnqueueSlow(item, ref segment); } } private void EnqueueSlow(T item, ref Segment segment) { if (segment._state._firstCopy != segment._state._first) { segment._state._firstCopy = segment._state._first; Enqueue(item); return; } int num = _tail._array.Length << 1; if (num > 16777216) { num = 16777216; } Segment segment2 = new Segment(num); segment2._array[0] = item; segment2._state._last = 1; segment2._state._lastCopy = 1; try { } finally { Volatile.Write(ref _tail._next, segment2); _tail = segment2; } } public bool TryDequeue([MaybeNullWhen(false)] out T result) { Segment head = _head; T[] array = head._array; int first = head._state._first; if (first != head._state._lastCopy) { result = array[first]; array[first] = default(T); head._state._first = (first + 1) & (array.Length - 1); return true; } return TryDequeueSlow(head, array, peek: false, out result); } public bool TryPeek([MaybeNullWhen(false)] out T result) { Segment head = _head; T[] array = head._array; int first = head._state._first; if (first != head._state._lastCopy) { result = array[first]; return true; } return TryDequeueSlow(head, array, peek: true, out result); } private bool TryDequeueSlow(Segment segment, T[] array, bool peek, [MaybeNullWhen(false)] out T result) { if (segment._state._last != segment._state._lastCopy) { segment._state._lastCopy = segment._state._last; if (!peek) { return TryDequeue(out result); } return TryPeek(out result); } if (segment._next != null && segment._state._first == segment._state._last) { segment = segment._next; array = segment._array; _head = segment; } int first = segment._state._first; if (first == segment._state._last) { result = default(T); return false; } result = array[first]; if (!peek) { array[first] = default(T); segment._state._first = (first + 1) & (segment._array.Length - 1); segment._state._lastCopy = segment._state._last; } return true; } public IEnumerator<T> GetEnumerator() { for (Segment segment = _head; segment != null; segment = segment._next) { for (int pt = segment._state._first; pt != segment._state._last; pt = (pt + 1) & (segment._array.Length - 1)) { yield return segment._array[pt]; } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } namespace System.Threading.Channels { internal abstract class AsyncOperation { protected static readonly Action<object> s_availableSentinel = AvailableSentinel; protected static readonly Action<object> s_completedSentinel = CompletedSentinel; private static void AvailableSentinel(object s) { } private static void CompletedSentinel(object s) { } protected static void ThrowIncompleteOperationException() { throw new InvalidOperationException(System.SR.InvalidOperation_IncompleteAsyncOperation); } protected static void ThrowMultipleContinuations() { throw new InvalidOperationException(System.SR.InvalidOperation_MultipleContinuations); } protected static void ThrowIncorrectCurrentIdException() { throw new InvalidOperationException(System.SR.InvalidOperation_IncorrectToken); } } internal class AsyncOperation<TResult> : AsyncOperation, IValueTaskSource, IValueTaskSource<TResult> { private readonly CancellationTokenRegistration _registration; private readonly bool _pooled; private readonly bool _runContinuationsAsynchronously; private volatile int _completionReserved; private TResult _result; private ExceptionDispatchInfo _error; private Action<object> _continuation; private object _continuationState; private object _schedulingContext; private ExecutionContext _executionContext; private short _currentId; public AsyncOperation<TResult> Next { get; set; } public CancellationToken CancellationToken { get; } public ValueTask ValueTask => new ValueTask(this, _currentId); public ValueTask<TResult> ValueTaskOfT => new ValueTask<TResult>(this, _currentId); internal bool IsCompleted => (object)_continuation == AsyncOperation.s_completedSentinel; public AsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false) { _continuation = (pooled ? AsyncOperation.s_availableSentinel : null); _pooled = pooled; _runContinuationsAsynchronously = runContinuationsAsynchronously; if (cancellationToken.CanBeCanceled) { CancellationToken = cancellationToken; _registration = UnsafeRegister(cancellationToken, delegate(object s) { AsyncOperation<TResult> asyncOperation = (AsyncOperation<TResult>)s; asyncOperation.TrySetCanceled(asyncOperation.CancellationToken); }, this); } } public ValueTaskSourceStatus GetStatus(short token) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (IsCompleted) { if (_error != null) { if (!(_error.SourceException is OperationCanceledException)) { return ValueTaskSourceStatus.Faulted; } return ValueTaskSourceStatus.Canceled; } return ValueTaskSourceStatus.Succeeded; } return ValueTaskSourceStatus.Pending; } public TResult GetResult(short token) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (!IsCompleted) { AsyncOperation.ThrowIncompleteOperationException(); } ExceptionDispatchInfo error = _error; TResult result = _result; _currentId++; if (_pooled) { Volatile.Write(ref _continuation, AsyncOperation.s_availableSentinel); } error?.Throw(); return result; } void IValueTaskSource.GetResult(short token) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (!IsCompleted) { AsyncOperation.ThrowIncompleteOperationException(); } ExceptionDispatchInfo error = _error; _currentId++; if (_pooled) { Volatile.Write(ref _continuation, AsyncOperation.s_availableSentinel); } error?.Throw(); } public bool TryOwnAndReset() { if ((object)Interlocked.CompareExchange(ref _continuation, null, AsyncOperation.s_availableSentinel) == AsyncOperation.s_availableSentinel) { _continuationState = null; _result = default(TResult); _error = null; _schedulingContext = null; _executionContext = null; return true; } return false; } public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (_continuationState != null) { AsyncOperation.ThrowMultipleContinuations(); } _continuationState = state; if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) { _executionContext = ExecutionContext.Capture(); } SynchronizationContext synchronizationContext = null; TaskScheduler taskScheduler = null; if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { synchronizationContext = SynchronizationContext.Current; if (synchronizationContext != null && synchronizationContext.GetType() != typeof(SynchronizationContext)) { _schedulingContext = synchronizationContext; } else { synchronizationContext = null; taskScheduler = TaskScheduler.Current; if (taskScheduler != TaskScheduler.Default) { _schedulingContext = taskScheduler; } } } Action<object> action = Interlocked.CompareExchange(ref _continuation, continuation, null); if (action == null) { return; } if ((object)action != AsyncOperation.s_completedSentinel) { AsyncOperation.ThrowMultipleContinuations(); } if (_schedulingContext == null) { if (_executionContext == null) { UnsafeQueueUserWorkItem(continuation, state); } else { QueueUserWorkItem(continuation, state); } } else if (synchronizationContext != null) { synchronizationContext.Post(delegate(object s) { KeyValuePair<Action<object>, object> keyValuePair = (KeyValuePair<Action<object>, object>)s; keyValuePair.Key(keyValuePair.Value); }, new KeyValuePair<Action<object>, object>(continuation, state)); } else { Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, taskScheduler); } } public bool UnregisterCancellation() { if (CancellationToken.CanBeCanceled) { _registration.Dispose(); return _completionReserved == 0; } return true; } public bool TrySetResult(TResult item) { UnregisterCancellation(); if (TryReserveCompletionIfCancelable()) { _result = item; SignalCompletion(); return true; } return false; } public bool TrySetException(Exception exception) { UnregisterCancellation(); if (TryReserveCompletionIfCancelable()) { _error = ExceptionDispatchInfo.Capture(exception); SignalCompletion(); return true; } return false; } public bool TrySetCanceled(CancellationToken cancellationToken = default(CancellationToken)) { if (TryReserveCompletionIfCancelable()) { _error = ExceptionDispatchInfo.Capture(new OperationCanceledException(cancellationToken)); SignalCompletion(); return true; } return false; } private bool TryReserveCompletionIfCancelable() { if (CancellationToken.CanBeCanceled) { return Interlocked.CompareExchange(ref _completionReserved, 1, 0) == 0; } return true; } private void SignalCompletion() { if (_continuation == null && Interlocked.CompareExchange(ref _continuation, AsyncOperation.s_completedSentinel, null) == null) { return; } if (_schedulingContext == null) { if (_runContinuationsAsynchronously) { UnsafeQueueSetCompletionAndInvokeContinuation(); return; } } else if (_schedulingContext is SynchronizationContext synchronizationContext) { if (_runContinuationsAsynchronously || synchronizationContext != SynchronizationContext.Current) { synchronizationContext.Post(delegate(object s) { ((AsyncOperation<TResult>)s).SetCompletionAndInvokeContinuation(); }, this); return; } } else { TaskScheduler taskScheduler = (TaskScheduler)_schedulingContext; if (_runContinuationsAsynchronously || taskScheduler != TaskScheduler.Current) { Task.Factory.StartNew(delegate(object s) { ((AsyncOperation<TResult>)s).SetCompletionAndInvokeContinuation(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, taskScheduler); return; } } SetCompletionAndInvokeContinuation(); } private void SetCompletionAndInvokeContinuation() { if (_executionContext == null) { Action<object> continuation = _continuation; _continuation = AsyncOperation.s_completedSentinel; continuation(_continuationState); return; } ExecutionContext.Run(_executionContext, delegate(object s) { AsyncOperation<TResult> asyncOperation = (AsyncOperation<TResult>)s; Action<object> continuation2 = asyncOperation._continuation; asyncOperation._continuation = AsyncOperation.s_completedSentinel; continuation2(asyncOperation._continuationState); }, this); } private void UnsafeQueueSetCompletionAndInvokeContinuation() { ThreadPool.UnsafeQueueUserWorkItem(delegate(object s) { ((AsyncOperation<TResult>)s).SetCompletionAndInvokeContinuation(); }, this); } private static void UnsafeQueueUserWorkItem(Action<object> action, object state) { QueueUserWorkItem(action, state); } private static void QueueUserWorkItem(Action<object> action, object state) { Task.Factory.StartNew(action, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } private static CancellationTokenRegistration UnsafeRegister(CancellationToken cancellationToken, Action<object> action, object state) { return cancellationToken.Register(action, state); } } internal sealed class VoidAsyncOperationWithData<TData> : AsyncOperation<VoidResult> { public TData Item { get; set; } public VoidAsyncOperationWithData(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false) : base(runContinuationsAsynchronously, cancellationToken, pooled) { } } [DebuggerDisplay("Items={ItemsCountForDebugger}, Capacity={_bufferedCapacity}, Mode={_mode}, Closed={ChannelIsClosedForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] internal sealed class BoundedChannel<T> : Channel<T>, IDebugEnumerable<T> { [DebuggerDisplay("Items={ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class BoundedChannelReader : ChannelReader<T>, IDebugEnumerable<T> { internal readonly BoundedChannel<T> _parent; private readonly AsyncOperation<T> _readerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; public override Task Completion => _parent._completion.Task; public override bool CanCount => true; public override bool CanPeek => true; public override int Count { get { BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { return parent._items.Count; } } } private int ItemsCountForDebugger => _parent._items.Count; internal BoundedChannelReader(BoundedChannel<T> parent) { _parent = parent; _readerSingleton = new AsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); } public override bool TryRead([MaybeNullWhen(false)] out T item) { BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { item = DequeueItemAndPostProcess(); return true; } } item = default(T); return false; } public override bool TryPeek([MaybeNullWhen(false)] out T item) { BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { item = parent._items.PeekHead(); return true; } } item = default(T); return false; } public override ValueTask<T> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<T>(DequeueItemAndPostProcess()); } if (parent._doneWriting != null) { return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<T> readerSingleton = _readerSingleton; if (readerSingleton.TryOwnAndReset()) { parent._blockedReaders.EnqueueTail(readerSingleton); return readerSingleton.ValueTaskOfT; } } AsyncOperation<T> asyncOperation = new AsyncOperation<T>(parent._runContinuationsAsynchronously | cancellationToken.CanBeCanceled, cancellationToken); parent._blockedReaders.EnqueueTail(asyncOperation); return asyncOperation.ValueTaskOfT; } } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<bool> waiterSingleton = _waiterSingleton; if (waiterSingleton.TryOwnAndReset()) { ChannelUtilities.QueueWaiter(ref parent._waitingReadersTail, waiterSingleton); return waiterSingleton.ValueTaskOfT; } } AsyncOperation<bool> asyncOperation = new AsyncOperation<bool>(parent._runContinuationsAsynchronously | cancellationToken.CanBeCanceled, cancellationToken); ChannelUtilities.QueueWaiter(ref _parent._waitingReadersTail, asyncOperation); return asyncOperation.ValueTaskOfT; } } private T DequeueItemAndPostProcess() { BoundedChannel<T> parent = _parent; T result = parent._items.DequeueHead(); if (parent._doneWriting != null) { if (parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } } else { while (!parent._blockedWriters.IsEmpty) { VoidAsyncOperationWithData<T> voidAsyncOperationWithData = parent._blockedWriters.DequeueHead(); if (voidAsyncOperationWithData.TrySetResult(default(VoidResult))) { parent._items.EnqueueTail(voidAsyncOperationWithData.Item); return result; } } ChannelUtilities.WakeUpWaiters(ref parent._waitingWritersTail, result: true); } return result; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } [DebuggerDisplay("Items={ItemsCountForDebugger}, Capacity={CapacityForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class BoundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T> { internal readonly BoundedChannel<T> _parent; private readonly VoidAsyncOperationWithData<T> _writerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; private int ItemsCountForDebugger => _parent._items.Count; private int CapacityForDebugger => _parent._bufferedCapacity; internal BoundedChannelWriter(BoundedChannel<T> parent) { _parent = parent; _writerSingleton = new VoidAsyncOperationWithData<T>(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true); } public override bool TryComplete(Exception error) { BoundedChannel<T> parent = _parent; bool isEmpty; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel; isEmpty = parent._items.IsEmpty; } if (isEmpty) { ChannelUtilities.Complete(parent._completion, error); } ChannelUtilities.FailOperations<AsyncOperation<T>, T>(parent._blockedReaders, ChannelUtilities.CreateInvalidCompletionException(error)); ChannelUtilities.FailOperations<VoidAsyncOperationWithData<T>, VoidResult>(parent._blockedWriters, ChannelUtilities.CreateInvalidCompletionException(error)); ChannelUtilities.WakeUpWaiters(ref parent._waitingReadersTail, result: false, error); ChannelUtilities.WakeUpWaiters(ref parent._waitingWritersTail, result: false, error); return true; } public override bool TryWrite(T item) { AsyncOperation<T> asyncOperation = null; AsyncOperation<bool> listTail = null; BoundedChannel<T> parent = _parent; bool lockTaken = false; try { Monitor.Enter(parent.SyncObj, ref lockTaken); if (parent._doneWriting != null) { return false; } int count = parent._items.Count; if (count != 0) { if (count < parent._bufferedCapacity) { parent._items.EnqueueTail(item); return true; } if (parent._mode == BoundedChannelFullMode.Wait) { return false; } if (parent._mode == BoundedChannelFullMode.DropWrite) { Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(item); return true; } T obj = ((parent._mode == BoundedChannelFullMode.DropNewest) ? parent._items.DequeueTail() : parent._items.DequeueHead()); parent._items.EnqueueTail(item); Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(obj); return true; } while (!parent._blockedReaders.IsEmpty) { AsyncOperation<T> asyncOperation2 = parent._blockedReaders.DequeueHead(); if (asyncOperation2.UnregisterCancellation()) { asyncOperation = asyncOperation2; break; } } if (asyncOperation == null) { parent._items.EnqueueTail(item); listTail = parent._waitingReadersTail; if (listTail == null) { return true; } parent._waitingReadersTail = null; } } finally { if (lockTaken) { Monitor.Exit(parent.SyncObj); } } if (asyncOperation != null) { bool flag = asyncOperation.TrySetResult(item); } else { ChannelUtilities.WakeUpWaiters(ref listTail, result: true); } return true; } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } if (parent._items.Count < parent._bufferedCapacity || parent._mode != 0) { return new ValueTask<bool>(result: true); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<bool> waiterSingleton = _waiterSingleton; if (waiterSingleton.TryOwnAndReset()) { ChannelUtilities.QueueWaiter(ref parent._waitingWritersTail, waiterSingleton); return waiterSingleton.ValueTaskOfT; } } AsyncOperation<bool> asyncOperation = new AsyncOperation<bool>(runContinuationsAsynchronously: true, cancellationToken); ChannelUtilities.QueueWaiter(ref parent._waitingWritersTail, asyncOperation); return asyncOperation.ValueTaskOfT; } } public override ValueTask WriteAsync(T item, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask(Task.FromCanceled(cancellationToken)); } AsyncOperation<T> asyncOperation = null; AsyncOperation<bool> listTail = null; BoundedChannel<T> parent = _parent; bool lockTaken = false; try { Monitor.Enter(parent.SyncObj, ref lockTaken); if (parent._doneWriting != null) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(parent._doneWriting))); } int count = parent._items.Count; if (count != 0) { if (count < parent._bufferedCapacity) { parent._items.EnqueueTail(item); return default(ValueTask); } if (parent._mode == BoundedChannelFullMode.Wait) { if (!cancellationToken.CanBeCanceled) { VoidAsyncOperationWithData<T> writerSingleton = _writerSingleton; if (writerSingleton.TryOwnAndReset()) { writerSingleton.Item = item; parent._blockedWriters.EnqueueTail(writerSingleton); return writerSingleton.ValueTask; } } VoidAsyncOperationWithData<T> voidAsyncOperationWithData = new VoidAsyncOperationWithData<T>(runContinuationsAsynchronously: true, cancellationToken); voidAsyncOperationWithData.Item = item; parent._blockedWriters.EnqueueTail(voidAsyncOperationWithData); return voidAsyncOperationWithData.ValueTask; } if (parent._mode == BoundedChannelFullMode.DropWrite) { Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(item); return default(ValueTask); } T obj = ((parent._mode == BoundedChannelFullMode.DropNewest) ? parent._items.DequeueTail() : parent._items.DequeueHead()); parent._items.EnqueueTail(item); Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(obj); return default(ValueTask); } while (!parent._blockedReaders.IsEmpty) { AsyncOperation<T> asyncOperation2 = parent._blockedReaders.DequeueHead(); if (asyncOperation2.UnregisterCancellation()) { asyncOperation = asyncOperation2; break; } } if (asyncOperation == null) { parent._items.EnqueueTail(item); listTail = parent._waitingReadersTail; if (listTail == null) { return default(ValueTask); } parent._waitingReadersTail = null; } } finally { if (lockTaken) { Monitor.Exit(parent.SyncObj); } } if (asyncOperation != null) { bool flag = asyncOperation.TrySetResult(item); } else { ChannelUtilities.WakeUpWaiters(ref listTail, result: true); } return default(ValueTask); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } private readonly BoundedChannelFullMode _mode; private readonly Action<T> _itemDropped; private readonly TaskCompletionSource _completion; private readonly int _bufferedCapacity; private readonly Deque<T> _items = new Deque<T>(); private readonly Deque<AsyncOperation<T>> _blockedReaders = new Deque<AsyncOperation<T>>(); private readonly Deque<VoidAsyncOperationWithData<T>> _blockedWriters = new Deque<VoidAsyncOperationWithData<T>>(); private AsyncOperation<bool> _waitingReadersTail; private AsyncOperation<bool> _waitingWritersTail; private readonly bool _runContinuationsAsynchronously; private Exception _doneWriting; private object SyncObj => _items; private int ItemsCountForDebugger => _items.Count; private bool ChannelIsClosedForDebugger => _doneWriting != null; internal BoundedChannel(int bufferedCapacity, BoundedChannelFullMode mode, bool runContinuationsAsynchronously, Action<T> itemDropped) { _bufferedCapacity = bufferedCapacity; _mode = mode; _runContinuationsAsynchronously = runContinuationsAsynchronously; _itemDropped = itemDropped; _completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); base.Reader = new BoundedChannelReader(this); base.Writer = new BoundedChannelWriter(this); } [Conditional("DEBUG")] private void AssertInvariants() { _ = _items.IsEmpty; _ = _items.Count; _ = _bufferedCapacity; _ = _blockedReaders.IsEmpty; _ = _blockedWriters.IsEmpty; _ = _completion.Task.IsCompleted; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _items.GetEnumerator(); } } public enum BoundedChannelFullMode { Wait, DropNewest, DropOldest, DropWrite } public static class Channel { public static Channel<T> CreateUnbounded<T>() { return new UnboundedChannel<T>(runContinuationsAsynchronously: true); } public static Channel<T> CreateUnbounded<T>(UnboundedChannelOptions options) { if (options == null) { throw new ArgumentNullException("options"); } if (options.SingleReader) { return new SingleConsumerUnboundedChannel<T>(!options.AllowSynchronousContinuations); } return new UnboundedChannel<T>(!options.AllowSynchronousContinuations); } public static Channel<T> CreateBounded<T>(int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity"); } return new BoundedChannel<T>(capacity, BoundedChannelFullMode.Wait, runContinuationsAsynchronously: true, null); } public static Channel<T> CreateBounded<T>(BoundedChannelOptions options) { return CreateBounded<T>(options, null); } public static Channel<T> CreateBounded<T>(BoundedChannelOptions options, Action<T>? itemDropped) { if (options == null) { throw new ArgumentNullException("options"); } return new BoundedChannel<T>(options.Capacity, options.FullMode, !options.AllowSynchronousContinuations, itemDropped); } } [Serializable] public class ChannelClosedException : InvalidOperationException { public ChannelClosedException() : base(System.SR.ChannelClosedException_DefaultMessage) { } public ChannelClosedException(string? message) : base(message) { } public ChannelClosedException(Exception? innerException) : base(System.SR.ChannelClosedException_DefaultMessage, innerException) { } public ChannelClosedException(string? message, Exception? innerException) : base(message, innerException) { } protected ChannelClosedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public abstract class ChannelOptions { public bool SingleWriter { get; set; } public bool SingleReader { get; set; } public bool AllowSynchronousContinuations { get; set; } } public sealed class BoundedChannelOptions : ChannelOptions { private int _capacity; private BoundedChannelFullMode _mode; public int Capacity { get { return _capacity; } set { if (value < 1) { throw new ArgumentOutOfRangeException("value"); } _capacity = value; } } public BoundedChannelFullMode FullMode { get { return _mode; } set { if ((uint)value <= 3u) { _mode = value; return; } throw new ArgumentOutOfRangeException("value"); } } public BoundedChannelOptions(int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity"); } _capacity = capacity; } } public sealed class UnboundedChannelOptions : ChannelOptions { } public abstract class ChannelReader<T> { public virtual Task Completion => ChannelUtilities.s_neverCompletingTask; public virtual bool CanCount => false; public virtual bool CanPeek => false; public virtual int Count { get { throw new NotSupportedException(); } } public abstract bool TryRead([MaybeNullWhen(false)] out T item); public virtual bool TryPeek([MaybeNullWhen(false)] out T item) { item = default(T); return false; } public abstract ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default(CancellationToken)); public virtual ValueTask<T> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } try { if (TryRead(out var item)) { return new ValueTask<T>(item); } } catch (Exception ex) when (!(ex is ChannelClosedException) && !(ex is OperationCanceledException)) { return new ValueTask<T>(Task.FromException<T>(ex)); } return ReadAsyncCore(cancellationToken); async ValueTask<T> ReadAsyncCore(CancellationToken ct) { T item2; do { if (!(await WaitToReadAsync(ct).ConfigureAwait(continueOnCapturedContext: false))) { throw new ChannelClosedException(); } } while (!TryRead(out item2)); return item2; } } public virtual async IAsyncEnumerable<T> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { while (await WaitToReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { T item; while (TryRead(out item)) { yield return item; } } } } internal static class ChannelUtilities { internal static readonly Exception s_doneWritingSentinel = new Exception("s_doneWritingSentinel"); internal static readonly Task<bool> s_trueTask = Task.FromResult(result: true); internal static readonly Task<bool> s_falseTask = Task.FromResult(result: false); internal static readonly Task s_neverCompletingTask = new TaskCompletionSource<bool>().Task; internal static void Complete(TaskCompletionSource tcs, Exception error = null) { if (error is OperationCanceledException ex) { tcs.TrySetCanceled(ex.CancellationToken); } else if (error != null && error != s_doneWritingSentinel) { tcs.TrySetException(error); } else { tcs.TrySetResult(); } } internal static ValueTask<T> GetInvalidCompletionValueTask<T>(Exception error) { Task<T> task = ((error == s_doneWritingSentinel) ? Task.FromException<T>(CreateInvalidCompletionException()) : ((error is OperationCanceledException ex) ? Task.FromCanceled<T>(ex.CancellationToken.IsCancellationRequested ? ex.CancellationToken : new CancellationToken(canceled: true)) : Task.FromException<T>(CreateInvalidCompletionException(error)))); return new ValueTask<T>(task); } internal static void QueueWaiter(ref AsyncOperation<bool> tail, AsyncOperation<bool> waiter) { AsyncOperation<bool> asyncOperation = tail; if (asyncOperation == null) { waiter.Next = waiter; } else { waiter.Next = asyncOperation.Next; asyncOperation.Next = waiter; } tail = waiter; } internal static void WakeUpWaiters(ref AsyncOperation<bool> listTail, bool result, Exception error = null) { AsyncOperation<bool> asyncOperation = listTail; if (asyncOperation != null) { listTail = null; AsyncOperation<bool> next = asyncOperation.Next; AsyncOperation<bool> asyncOperation2 = next; do { AsyncOperation<bool> next2 = asyncOperation2.Next; asyncOperation2.Next = null; bool flag = ((error != null) ? asyncOperation2.TrySetException(error) : asyncOperation2.TrySetResult(result)); asyncOperation2 = next2; } while (asyncOperation2 != next); } } internal static void FailOperations<T, TInner>(Deque<T> operations, Exception error) where T : AsyncOperation<TInner> { while (!operations.IsEmpty) { operations.DequeueHead().TrySetException(error); } } internal static Exception CreateInvalidCompletionException(Exception inner = null) { if (!(inner is OperationCanceledException)) { if (inner == null || inner == s_doneWritingSentinel) { return new ChannelClosedException(); } return new ChannelClosedException(inner); } return inner; } } public abstract class ChannelWriter<T> { public virtual bool TryComplete(Exception? error = null) { return false; } public abstract bool TryWrite(T item); public abstract ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken = default(CancellationToken)); public virtual ValueTask WriteAsync(T item, CancellationToken cancellationToken = default(CancellationToken)) { try { return cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled<T>(cancellationToken)) : (TryWrite(item) ? default(ValueTask) : WriteAsyncCore(item, cancellationToken)); } catch (Exception exception) { return new ValueTask(Task.FromException(exception)); } } private async ValueTask WriteAsyncCore(T innerItem, CancellationToken ct) { while (await WaitToWriteAsync(ct).ConfigureAwait(continueOnCapturedContext: false)) { if (TryWrite(innerItem)) { return; } } throw ChannelUtilities.CreateInvalidCompletionException(); } public void Complete(Exception? error = null) { if (!TryComplete(error)) { throw ChannelUtilities.CreateInvalidCompletionException(); } } } public abstract class Channel<T> : Channel<T, T> { } public abstract class Channel<TWrite, TRead> { public ChannelReader<TRead> Reader { get; protected set; } public ChannelWriter<TWrite> Writer { get; protected set; } public static implicit operator ChannelReader<TRead>(Channel<TWrite, TRead> channel) { return channel.Reader; } public static implicit operator ChannelWriter<TWrite>(Channel<TWrite, TRead> channel) { return channel.Writer; } } internal interface IDebugEnumerable<T> { IEnumerator<T> GetEnumerator(); } internal sealed class DebugEnumeratorDebugView<T> { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get; } public DebugEnumeratorDebugView(IDebugEnumerable<T> enumerable) { List<T> list = new List<T>(); foreach (T item in enumerable) { list.Add(item); } Items = list.ToArray(); } } [DebuggerDisplay("Items={ItemsCountForDebugger}, Closed={ChannelIsClosedForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] internal sealed class SingleConsumerUnboundedChannel<T> : Channel<T>, IDebugEnumerable<T> { [DebuggerDisplay("Items={ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelReader : ChannelReader<T>, IDebugEnumerable<T> { internal readonly SingleConsumerUnboundedChannel<T> _parent; private readonly AsyncOperation<T> _readerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; public override Task Completion => _parent._completion.Task; public override bool CanPeek => true; private int ItemsCountForDebugger => _parent._items.Count; internal UnboundedChannelReader(SingleConsumerUnboundedChannel<T> parent) { _parent = parent; _readerSingleton = new AsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); } public override ValueTask<T> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } if (TryRead(out var item)) { return new ValueTask<T>(item); } SingleConsumerUnboundedChannel<T> parent = _parent; AsyncOperation<T> asyncOperation; AsyncOperation<T> asyncOperation2; lock (parent.SyncObj) { if (TryRead(out item)) { return new ValueTask<T>(item); } if (parent._doneWriting != null) { return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting); } asyncOperation = parent._blockedReader; if (!cancellationToken.CanBeCanceled && _readerSingleton.TryOwnAndReset()) { asyncOperation2 = _readerSingleton; if (asyncOperation2 == asyncOperation) { asyncOperation = null; } } else { asyncOperation2 = new AsyncOperation<T>(_parent._runContinuationsAsynchronously, cancellationToken); } parent._blockedReader = asyncOperation2; } asyncOperation?.TrySetCanceled(); return asyncOperation2.ValueTaskOfT; } public override bool TryRead([MaybeNullWhen(false)] out T item) { SingleConsumerUnboundedChannel<T> parent = _parent; if (parent._items.TryDequeue(out item)) { if (parent._doneWriting != null && parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } return true; } return false; } public override bool TryPeek([MaybeNullWhen(false)] out T item) { return _parent._items.TryPeek(out item); } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } if (!_parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } SingleConsumerUnboundedChannel<T> parent = _parent; AsyncOperation<bool> asyncOperation = null; AsyncOperation<bool> asyncOperation2; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } asyncOperation = parent._waitingReader; if (!cancellationToken.CanBeCanceled && _waiterSingleton.TryOwnAndReset()) { asyncOperation2 = _waiterSingleton; if (asyncOperation2 == asyncOperation) { asyncOperation = null; } } else { asyncOperation2 = new AsyncOperation<bool>(_parent._runContinuationsAsynchronously, cancellationToken); } parent._waitingReader = asyncOperation2; } asyncOperation?.TrySetCanceled(); return asyncOperation2.ValueTaskOfT; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } [DebuggerDisplay("Items={ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T> { internal readonly SingleConsumerUnboundedChannel<T> _parent; private int ItemsCountForDebugger => _parent._items.Count; internal UnboundedChannelWriter(SingleConsumerUnboundedChannel<T> parent) { _parent = parent; } public override bool TryComplete(Exception error) { AsyncOperation<T> asyncOperation = null; AsyncOperation<bool> asyncOperation2 = null; bool flag = false; SingleConsumerUnboundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel; if (parent._items.IsEmpty) { flag = true; if (parent._blockedReader != null) { asyncOperation = parent._blockedReader; parent._blockedReader = null; } if (parent._waitingReader != null) { asyncOperation2 = parent._waitingReader; parent._waitingReader = null; } } } if (flag) { ChannelUtilities.Complete(parent._completion, error); } if (asyncOperation != null) { error = ChannelUtilities.CreateInvalidCompletionException(error); asyncOperation.TrySetException(error); } if (asyncOperation2 != null) { if (error != null) { asyncOperation2.TrySetException(error); } else { asyncOperation2.TrySetResult(item: false); } } return true; } public override bool TryWrite(T item) { SingleConsumerUnboundedChannel<T> parent = _parent; AsyncOperation<T> asyncOperation; do { asyncOperation = null; AsyncOperation<bool> asyncOperation2 = null; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } asyncOperation = parent._blockedReader; if (asyncOperation != null) { parent._blockedReader = null; } else { parent._items.Enqueue(item); asyncOperation2 = parent._waitingReader; if (asyncOperation2 == null) { return true; } parent._waitingReader = null; } } if (asyncOperation2 != null) { asyncOperation2.TrySetResult(item: true); return true; } } while (!asyncOperation.TrySetResult(item)); return true; } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) { Exception doneWriting = _parent._doneWriting; if (!cancellationToken.IsCancellationRequested) { if (doneWriting != null) { if (doneWriting == ChannelUtilities.s_doneWritingSentinel) { return default(ValueTask<bool>); } return new ValueTask<bool>(Task.FromException<bool>(doneWriting)); } return new ValueTask<bool>(result: true); } return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } public override ValueTask WriteAsync(T item, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { if (!TryWrite(item)) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(_parent._doneWriting))); } return default(ValueTask); } return new ValueTask(Task.FromCanceled(cancellationToken)); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } private readonly TaskCompletionSource _completion; private readonly SingleProducerSingleConsumerQueue<T> _items = new SingleProducerSingleConsumerQueue<T>(); private readonly bool _runContinuationsAsynchronously; private volatile Exception _doneWriting; private AsyncOperation<T> _blockedReader; private AsyncOperation<bool> _waitingReader; private object SyncObj => _items; private int ItemsCountForDebugger => _items.Count; private bool ChannelIsClosedForDebugger => _doneWriting != null; internal SingleConsumerUnboundedChannel(bool runContinuationsAsynchronously) { _runContinuationsAsynchronously = runContinuationsAsynchronously; _completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); base.Reader = new UnboundedChannelReader(this); base.Writer = new UnboundedChannelWriter(this); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _items.GetEnumerator(); } } internal sealed class TaskCompletionSource : TaskCompletionSource<VoidResult> { public TaskCompletionSource(TaskCreationOptions creationOptions) : base(creationOptions) { } public bool TrySetResult() { return TrySetResult(default(VoidResult)); } } [DebuggerDisplay("Items={ItemsCountForDebugger}, Closed={ChannelIsClosedForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] internal sealed class UnboundedChannel<T> : Channel<T>, IDebugEnumerable<T> { [DebuggerDisplay("Items={Count}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelReader : ChannelReader<T>, IDebugEnumerable<T> { internal readonly UnboundedChannel<T> _parent; private readonly AsyncOperation<T> _readerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; public override Task Completion => _parent._completion.Task; public override bool CanCount => true; public override bool CanPeek => true; public override int Count => _parent._items.Count; internal UnboundedChannelReader(UnboundedChannel<T> parent) { _parent = parent; _readerSingleton = new AsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); } public override ValueTask<T> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } UnboundedChannel<T> parent = _parent; if (parent._items.TryDequeue(out var result)) { CompleteIfDone(parent); return new ValueTask<T>(result); } lock (parent.SyncObj) { if (parent._items.TryDequeue(out result)) { CompleteIfDone(parent); return new ValueTask<T>(result); } if (parent._doneWriting != null) { return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<T> readerSingleton = _readerSingleton; if (readerSingleton.TryOwnAndReset()) { parent._blockedReaders.EnqueueTail(readerSingleton); return readerSingleton.ValueTaskOfT; } } AsyncOperation<T> asyncOperation = new AsyncOperation<T>(parent._runContinuationsAsynchronously, cancellationToken); parent._blockedReaders.EnqueueTail(asyncOperation); return asyncOperation.ValueTaskOfT; } } public override bool TryRead([MaybeNullWhen(false)] out T item) { UnboundedChannel<T> parent = _parent; if (parent._items.TryDequeue(out item)) { CompleteIfDone(parent); return true; } item = default(T); return false; } public override bool TryPeek([MaybeNullWhen(false)] out T item) { return _parent._items.TryPeek(out item); } private static void CompleteIfDone(UnboundedChannel<T> parent) { if (parent._doneWriting != null && parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } if (!_parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } UnboundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<bool> waiterSingleton = _waiterSingleton; if (waiterSingleton.TryOwnAndReset()) { ChannelUtilities.QueueWaiter(ref parent._waitingReadersTail, waiterSingleton); return waiterSingleton.ValueTaskOfT; } } AsyncOperation<bool> asyncOperation = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, cancellationToken); ChannelUtilities.QueueWaiter(ref parent._waitingReadersTail, asyncOperation); return asyncOperation.ValueTaskOfT; } } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } [DebuggerDisplay("Items={ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T> { internal readonly UnboundedChannel<T> _parent; private int ItemsCountForDebugger => _parent._items.Count; internal UnboundedChannelWriter(UnboundedChannel<T> parent) { _parent = parent; } public override bool TryComplete(Exception error) { UnboundedChannel<T> parent = _parent; bool isEmpty; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel; isEmpty = parent._items.IsEmpty; } if (isEmpty) { ChannelUtilities.Complete(parent._completion, error); } ChannelUtilities.FailOperations<AsyncOperation<T>, T>(parent._blockedReaders, ChannelUtilities.CreateInvalidCompletionException(error)); ChannelUtilities.WakeUpWaiters(ref parent._waitingReadersTail, result: false, error); return true; } public override bool TryWrite(T item) { UnboundedChannel<T> parent = _parent; AsyncOperation<bool> listTail; while (true) { AsyncOperation<T> asyncOperation = null; listTail = null; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } if (parent._blockedReaders.IsEmpty) { parent._items.Enqueue(item); listTail = parent._waitingReadersTail; if (listTail == null) { return true; } parent._waitingReadersTail = null; } else { asyncOperation = parent._blockedReaders.DequeueHead(); } } if (asyncOperation == null) { break; } if (asyncOperation.TrySetResult(item)) { return true; } } ChannelUtilities.WakeUpWaiters(ref listTail, result: true); return true; } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) { Exception doneWriting = _parent._doneWriting; if (!cancellationToken.IsCancellationRequested) { if (doneWriting != null) { if (doneWriting == ChannelUtilities.s_doneWritingSentinel) { return default(ValueTask<bool>); } return new ValueTask<bool>(Task.FromException<bool>(doneWriting)); } return new ValueTask<bool>(result: true); } return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } public override ValueTask WriteAsync(T item, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { if (!TryWrite(item)) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(_parent._doneWriting))); } return default(ValueTask); } return new ValueTask(Task.FromCanceled(cancellationToken)); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } private readonly TaskCompletionSource _completion; private readonly ConcurrentQueue<T> _items = new ConcurrentQueue<T>(); private readonly Deque<AsyncOperation<T>> _blockedReaders = new Deque<AsyncOperation<T>>(); private readonly bool _runContinuationsAsynchronously; private AsyncOperation<bool> _waitingReadersTail; private Exception _doneWriting; private object SyncObj => _items; private int ItemsCountForDebugger => _items.Count; private bool ChannelIsClosedForDebugger => _doneWriting != null; internal UnboundedChannel(bool runContinuationsAsynchronously) { _runContinuationsAsynchronously = runContinuationsAsynchronously; _completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); base.Reader = new UnboundedChannelReader(this); base.Writer = new UnboundedChannelWriter(this); } [Conditional("DEBUG")] private void AssertInvariants() { if (!_items.IsEmpty) { _ = _runContinuationsAsynchronously; } if (!_blockedReaders.IsEmpty || _waitingReadersTail != null) { _ = _runContinuationsAsynchronously; } _ = _completion.Task.IsCompleted; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _items.GetEnumerator(); } } }
BepInEx/plugins/VNyanCommands/System.Threading.dll
Decompiled 2 years agousing 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.Threading; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Threading")] [assembly: AssemblyDescription("System.Threading")] [assembly: AssemblyDefaultAlias("System.Threading")] [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: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.12.0")] [assembly: TypeForwardedTo(typeof(AbandonedMutexException))] [assembly: TypeForwardedTo(typeof(AsyncLocal<>))] [assembly: TypeForwardedTo(typeof(AsyncLocalValueChangedArgs<>))] [assembly: TypeForwardedTo(typeof(AutoResetEvent))] [assembly: TypeForwardedTo(typeof(ContextCallback))] [assembly: TypeForwardedTo(typeof(EventResetMode))] [assembly: TypeForwardedTo(typeof(EventWaitHandle))] [assembly: TypeForwardedTo(typeof(ExecutionContext))] [assembly: TypeForwardedTo(typeof(Interlocked))] [assembly: TypeForwardedTo(typeof(LazyInitializer))] [assembly: TypeForwardedTo(typeof(LockRecursionException))] [assembly: TypeForwardedTo(typeof(ManualResetEvent))] [assembly: TypeForwardedTo(typeof(ManualResetEventSlim))] [assembly: TypeForwardedTo(typeof(Monitor))] [assembly: TypeForwardedTo(typeof(Mutex))] [assembly: TypeForwardedTo(typeof(Semaphore))] [assembly: TypeForwardedTo(typeof(SemaphoreFullException))] [assembly: TypeForwardedTo(typeof(SemaphoreSlim))] [assembly: TypeForwardedTo(typeof(SendOrPostCallback))] [assembly: TypeForwardedTo(typeof(SpinLock))] [assembly: TypeForwardedTo(typeof(SpinWait))] [assembly: TypeForwardedTo(typeof(SynchronizationContext))] [assembly: TypeForwardedTo(typeof(SynchronizationLockException))] [assembly: TypeForwardedTo(typeof(ThreadLocal<>))] [assembly: TypeForwardedTo(typeof(Volatile))] [assembly: TypeForwardedTo(typeof(WaitHandleCannotBeOpenedException))] [module: UnverifiableCode] namespace FxResources.System.Threading { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Threading.SR"; private static ResourceManager ResourceManager { get { if (s_resourceManager == null) { s_resourceManager = new ResourceManager(ResourceType); } return s_resourceManager; } } internal static string CountdownEvent_Increment_AlreadyZero => GetResourceString("CountdownEvent_Increment_AlreadyZero", null); internal static string CountdownEvent_Increment_AlreadyMax => GetResourceString("CountdownEvent_Increment_AlreadyMax", null); internal static string CountdownEvent_Decrement_BelowZero => GetResourceString("CountdownEvent_Decrement_BelowZero", null); internal static string Common_OperationCanceled => GetResourceString("Common_OperationCanceled", null); internal static string Barrier_Dispose => GetResourceString("Barrier_Dispose", null); internal static string Barrier_SignalAndWait_InvalidOperation_ZeroTotal => GetResourceString("Barrier_SignalAndWait_InvalidOperation_ZeroTotal", null); internal static string Barrier_SignalAndWait_ArgumentOutOfRange => GetResourceString("Barrier_SignalAndWait_ArgumentOutOfRange", null); internal static string Barrier_RemoveParticipants_InvalidOperation => GetResourceString("Barrier_RemoveParticipants_InvalidOperation", null); internal static string Barrier_RemoveParticipants_ArgumentOutOfRange => GetResourceString("Barrier_RemoveParticipants_ArgumentOutOfRange", null); internal static string Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange => GetResourceString("Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange", null); internal static string Barrier_InvalidOperation_CalledFromPHA => GetResourceString("Barrier_InvalidOperation_CalledFromPHA", null); internal static string Barrier_AddParticipants_NonPositive_ArgumentOutOfRange => GetResourceString("Barrier_AddParticipants_NonPositive_ArgumentOutOfRange", null); internal static string Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded => GetResourceString("Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded", null); internal static string BarrierPostPhaseException => GetResourceString("BarrierPostPhaseException", null); internal static string Barrier_ctor_ArgumentOutOfRange => GetResourceString("Barrier_ctor_ArgumentOutOfRange", null); internal static string Barrier_AddParticipants_Overflow_ArgumentOutOfRange => GetResourceString("Barrier_AddParticipants_Overflow_ArgumentOutOfRange", null); internal static string SynchronizationLockException_IncorrectDispose => GetResourceString("SynchronizationLockException_IncorrectDispose", null); internal static string SynchronizationLockException_MisMatchedWrite => GetResourceString("SynchronizationLockException_MisMatchedWrite", null); internal static string LockRecursionException_UpgradeAfterReadNotAllowed => GetResourceString("LockRecursionException_UpgradeAfterReadNotAllowed", null); internal static string LockRecursionException_UpgradeAfterWriteNotAllowed => GetResourceString("LockRecursionException_UpgradeAfterWriteNotAllowed", null); internal static string SynchronizationLockException_MisMatchedUpgrade => GetResourceString("SynchronizationLockException_MisMatchedUpgrade", null); internal static string SynchronizationLockException_MisMatchedRead => GetResourceString("SynchronizationLockException_MisMatchedRead", null); internal static string LockRecursionException_WriteAfterReadNotAllowed => GetResourceString("LockRecursionException_WriteAfterReadNotAllowed", null); internal static string LockRecursionException_RecursiveWriteNotAllowed => GetResourceString("LockRecursionException_RecursiveWriteNotAllowed", null); internal static string LockRecursionException_ReadAfterWriteNotAllowed => GetResourceString("LockRecursionException_ReadAfterWriteNotAllowed", null); internal static string LockRecursionException_RecursiveUpgradeNotAllowed => GetResourceString("LockRecursionException_RecursiveUpgradeNotAllowed", null); internal static string LockRecursionException_RecursiveReadNotAllowed => GetResourceString("LockRecursionException_RecursiveReadNotAllowed", null); internal static Type ResourceType => typeof(FxResources.System.Threading.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.Threading { internal static class Helpers { internal static void Sleep(int milliseconds) { Thread.Sleep(milliseconds); } internal static void Spin(int iterations) { Thread.SpinWait(iterations); } } public class BarrierPostPhaseException : Exception { public BarrierPostPhaseException() : this((string)null) { } public BarrierPostPhaseException(Exception innerException) : this(null, innerException) { } public BarrierPostPhaseException(string message) : this(message, null) { } public BarrierPostPhaseException(string message, Exception innerException) : base((message == null) ? System.SR.BarrierPostPhaseException : message, innerException) { } } [DebuggerDisplay("Participant Count={ParticipantCount},Participants Remaining={ParticipantsRemaining}")] public class Barrier : IDisposable { private volatile int _currentTotalCount; private const int CURRENT_MASK = 2147418112; private const int TOTAL_MASK = 32767; private const int SENSE_MASK = int.MinValue; private const int MAX_PARTICIPANTS = 32767; private long _currentPhase; private bool _disposed; private ManualResetEventSlim _oddEvent; private ManualResetEventSlim _evenEvent; private ExecutionContext _ownerThreadContext; [SecurityCritical] private static ContextCallback s_invokePostPhaseAction; private Action<Barrier> _postPhaseAction; private Exception _exception; private int _actionCallerID; public int ParticipantsRemaining { get { int currentTotalCount = _currentTotalCount; int num = currentTotalCount & 0x7FFF; int num2 = (currentTotalCount & 0x7FFF0000) >> 16; return num - num2; } } public int ParticipantCount => _currentTotalCount & 0x7FFF; public long CurrentPhaseNumber { get { return Volatile.Read(ref _currentPhase); } internal set { Volatile.Write(ref _currentPhase, value); } } public Barrier(int participantCount) : this(participantCount, null) { } public Barrier(int participantCount, Action<Barrier> postPhaseAction) { if (participantCount < 0 || participantCount > 32767) { throw new ArgumentOutOfRangeException("participantCount", participantCount, System.SR.Barrier_ctor_ArgumentOutOfRange); } _currentTotalCount = participantCount; _postPhaseAction = postPhaseAction; _oddEvent = new ManualResetEventSlim(initialState: true); _evenEvent = new ManualResetEventSlim(initialState: false); if (postPhaseAction != null) { _ownerThreadContext = ExecutionContext.Capture(); } _actionCallerID = 0; } private void GetCurrentTotal(int currentTotal, out int current, out int total, out bool sense) { total = currentTotal & 0x7FFF; current = (currentTotal & 0x7FFF0000) >> 16; sense = (((currentTotal & int.MinValue) == 0) ? true : false); } private bool SetCurrentTotal(int currentTotal, int current, int total, bool sense) { int num = (current << 16) | total; if (!sense) { num |= int.MinValue; } return Interlocked.CompareExchange(ref _currentTotalCount, num, currentTotal) == currentTotal; } public long AddParticipant() { try { return AddParticipants(1); } catch (ArgumentOutOfRangeException) { throw new InvalidOperationException(System.SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } } public long AddParticipants(int participantCount) { ThrowIfDisposed(); if (participantCount < 1) { throw new ArgumentOutOfRangeException("participantCount", participantCount, System.SR.Barrier_AddParticipants_NonPositive_ArgumentOutOfRange); } if (participantCount > 32767) { throw new ArgumentOutOfRangeException("participantCount", System.SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(System.SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinWait = default(SpinWait); long num = 0L; bool sense; while (true) { int currentTotalCount = _currentTotalCount; GetCurrentTotal(currentTotalCount, out var current, out var total, out sense); if (participantCount + total > 32767) { throw new ArgumentOutOfRangeException("participantCount", System.SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } if (SetCurrentTotal(currentTotalCount, current, total + participantCount, sense)) { break; } spinWait.SpinOnce(); } long currentPhaseNumber = CurrentPhaseNumber; num = ((sense != (currentPhaseNumber % 2 == 0)) ? (currentPhaseNumber + 1) : currentPhaseNumber); if (num != currentPhaseNumber) { if (sense) { _oddEvent.Wait(); } else { _evenEvent.Wait(); } } else if (sense && _evenEvent.IsSet) { _evenEvent.Reset(); } else if (!sense && _oddEvent.IsSet) { _oddEvent.Reset(); } return num; } public void RemoveParticipant() { RemoveParticipants(1); } public void RemoveParticipants(int participantCount) { ThrowIfDisposed(); if (participantCount < 1) { throw new ArgumentOutOfRangeException("participantCount", participantCount, System.SR.Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange); } if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(System.SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinWait = default(SpinWait); while (true) { int currentTotalCount = _currentTotalCount; GetCurrentTotal(currentTotalCount, out var current, out var total, out var sense); if (total < participantCount) { throw new ArgumentOutOfRangeException("participantCount", System.SR.Barrier_RemoveParticipants_ArgumentOutOfRange); } if (total - participantCount < current) { throw new InvalidOperationException(System.SR.Barrier_RemoveParticipants_InvalidOperation); } int num = total - participantCount; if (num > 0 && current == num) { if (SetCurrentTotal(currentTotalCount, 0, total - participantCount, !sense)) { FinishPhase(sense); break; } } else if (SetCurrentTotal(currentTotalCount, current, total - participantCount, sense)) { break; } spinWait.SpinOnce(); } } public void SignalAndWait() { SignalAndWait(default(CancellationToken)); } public void SignalAndWait(CancellationToken cancellationToken) { SignalAndWait(-1, cancellationToken); } public bool SignalAndWait(TimeSpan timeout) { return SignalAndWait(timeout, default(CancellationToken)); } public bool SignalAndWait(TimeSpan timeout, CancellationToken cancellationToken) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", timeout, System.SR.Barrier_SignalAndWait_ArgumentOutOfRange); } return SignalAndWait((int)timeout.TotalMilliseconds, cancellationToken); } public bool SignalAndWait(int millisecondsTimeout) { return SignalAndWait(millisecondsTimeout, default(CancellationToken)); } public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", millisecondsTimeout, System.SR.Barrier_SignalAndWait_ArgumentOutOfRange); } if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(System.SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinWait = default(SpinWait); int current; int total; bool sense; long currentPhaseNumber; while (true) { int currentTotalCount = _currentTotalCount; GetCurrentTotal(currentTotalCount, out current, out total, out sense); currentPhaseNumber = CurrentPhaseNumber; if (total == 0) { throw new InvalidOperationException(System.SR.Barrier_SignalAndWait_InvalidOperation_ZeroTotal); } if (current == 0 && sense != (CurrentPhaseNumber % 2 == 0)) { throw new InvalidOperationException(System.SR.Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded); } if (current + 1 == total) { if (SetCurrentTotal(currentTotalCount, 0, total, !sense)) { if (System.Threading.CdsSyncEtwBCLProvider.Log.IsEnabled()) { System.Threading.CdsSyncEtwBCLProvider.Log.Barrier_PhaseFinished(sense, CurrentPhaseNumber); } FinishPhase(sense); return true; } } else if (SetCurrentTotal(currentTotalCount, current + 1, total, sense)) { break; } spinWait.SpinOnce(); } ManualResetEventSlim currentPhaseEvent = (sense ? _evenEvent : _oddEvent); bool flag = false; bool flag2 = false; try { flag2 = DiscontinuousWait(currentPhaseEvent, millisecondsTimeout, cancellationToken, currentPhaseNumber); } catch (OperationCanceledException) { flag = true; } catch (ObjectDisposedException) { if (currentPhaseNumber >= CurrentPhaseNumber) { throw; } flag2 = true; } if (!flag2) { spinWait.Reset(); while (true) { int currentTotalCount = _currentTotalCount; GetCurrentTotal(currentTotalCount, out current, out total, out var sense2); if (currentPhaseNumber < CurrentPhaseNumber || sense != sense2) { break; } if (SetCurrentTotal(currentTotalCount, current - 1, total, sense)) { if (flag) { throw new OperationCanceledException(System.SR.Common_OperationCanceled, cancellationToken); } return false; } spinWait.SpinOnce(); } WaitCurrentPhase(currentPhaseEvent, currentPhaseNumber); } if (_exception != null) { throw new BarrierPostPhaseException(_exception); } return true; } [SecuritySafeCritical] private void FinishPhase(bool observedSense) { if (_postPhaseAction != null) { try { _actionCallerID = Environment.CurrentManagedThreadId; if (_ownerThreadContext != null) { ExecutionContext ownerThreadContext = _ownerThreadContext; ContextCallback callback = InvokePostPhaseAction; ExecutionContext.Run(_ownerThreadContext, callback, this); } else { _postPhaseAction(this); } _exception = null; return; } catch (Exception exception) { _exception = exception; return; } finally { _actionCallerID = 0; SetResetEvents(observedSense); if (_exception != null) { throw new BarrierPostPhaseException(_exception); } } } SetResetEvents(observedSense); } [SecurityCritical] private static void InvokePostPhaseAction(object obj) { Barrier barrier = (Barrier)obj; barrier._postPhaseAction(barrier); } private void SetResetEvents(bool observedSense) { CurrentPhaseNumber++; if (observedSense) { _oddEvent.Reset(); _evenEvent.Set(); } else { _evenEvent.Reset(); _oddEvent.Set(); } } private void WaitCurrentPhase(ManualResetEventSlim currentPhaseEvent, long observedPhase) { SpinWait spinWait = default(SpinWait); while (!currentPhaseEvent.IsSet && CurrentPhaseNumber - observedPhase <= 1) { spinWait.SpinOnce(); } } private bool DiscontinuousWait(ManualResetEventSlim currentPhaseEvent, int totalTimeout, CancellationToken token, long observedPhase) { int num = 100; int num2 = 10000; while (observedPhase == CurrentPhaseNumber) { int num3 = ((totalTimeout == -1) ? num : Math.Min(num, totalTimeout)); if (currentPhaseEvent.Wait(num3, token)) { return true; } if (totalTimeout != -1) { totalTimeout -= num3; if (totalTimeout <= 0) { return false; } } num = ((num >= num2) ? num2 : Math.Min(num << 1, num2)); } WaitCurrentPhase(currentPhaseEvent, observedPhase); return true; } public void Dispose() { if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(System.SR.Barrier_InvalidOperation_CalledFromPHA); } Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _oddEvent.Dispose(); _evenEvent.Dispose(); } _disposed = true; } } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException("Barrier", System.SR.Barrier_Dispose); } } } [EventSource(Name = "System.Threading.SynchronizationEventSource", Guid = "EC631D38-466B-4290-9306-834971BA0217")] internal sealed class CdsSyncEtwBCLProvider : EventSource { public static System.Threading.CdsSyncEtwBCLProvider Log = new System.Threading.CdsSyncEtwBCLProvider(); private const EventKeywords ALL_KEYWORDS = EventKeywords.All; private const int SPINLOCK_FASTPATHFAILED_ID = 1; private const int SPINWAIT_NEXTSPINWILLYIELD_ID = 2; private const int BARRIER_PHASEFINISHED_ID = 3; private CdsSyncEtwBCLProvider() { } [Event(1, Level = EventLevel.Warning)] public void SpinLock_FastPathFailed(int ownerID) { if (IsEnabled(EventLevel.Warning, EventKeywords.All)) { WriteEvent(1, ownerID); } } [Event(2, Level = EventLevel.Informational)] public void SpinWait_NextSpinWillYield() { if (IsEnabled(EventLevel.Informational, EventKeywords.All)) { WriteEvent(2); } } [SecuritySafeCritical] [Event(3, Level = EventLevel.Verbose, Version = 1)] public unsafe void Barrier_PhaseFinished(bool currentSense, long phaseNum) { if (IsEnabled(EventLevel.Verbose, EventKeywords.All)) { EventData* ptr = stackalloc EventData[2]; int num = (currentSense ? 1 : 0); ptr->Size = 4; ptr->DataPointer = (IntPtr)(&num); ptr[1].Size = 8; ptr[1].DataPointer = (IntPtr)(&phaseNum); WriteEventCore(3, 2, ptr); } } } [DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")] public class CountdownEvent : IDisposable { private int _initialCount; private volatile int _currentCount; private ManualResetEventSlim _event; private volatile bool _disposed; public int CurrentCount { get { int currentCount = _currentCount; if (currentCount >= 0) { return currentCount; } return 0; } } public int InitialCount => _initialCount; public bool IsSet => _currentCount <= 0; public WaitHandle WaitHandle { get { ThrowIfDisposed(); return _event.WaitHandle; } } public CountdownEvent(int initialCount) { if (initialCount < 0) { throw new ArgumentOutOfRangeException("initialCount"); } _initialCount = initialCount; _currentCount = initialCount; _event = new ManualResetEventSlim(); if (initialCount == 0) { _event.Set(); } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _event.Dispose(); _disposed = true; } } public bool Signal() { ThrowIfDisposed(); if (_currentCount <= 0) { throw new InvalidOperationException(System.SR.CountdownEvent_Decrement_BelowZero); } int num = Interlocked.Decrement(ref _currentCount); if (num == 0) { _event.Set(); return true; } if (num < 0) { throw new InvalidOperationException(System.SR.CountdownEvent_Decrement_BelowZero); } return false; } public bool Signal(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException("signalCount"); } ThrowIfDisposed(); SpinWait spinWait = default(SpinWait); int currentCount; while (true) { currentCount = _currentCount; if (currentCount < signalCount) { throw new InvalidOperationException(System.SR.CountdownEvent_Decrement_BelowZero); } if (Interlocked.CompareExchange(ref _currentCount, currentCount - signalCount, currentCount) == currentCount) { break; } spinWait.SpinOnce(); } if (currentCount == signalCount) { _event.Set(); return true; } return false; } public void AddCount() { AddCount(1); } public bool TryAddCount() { return TryAddCount(1); } public void AddCount(int signalCount) { if (!TryAddCount(signalCount)) { throw new InvalidOperationException(System.SR.CountdownEvent_Increment_AlreadyZero); } } public bool TryAddCount(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException("signalCount"); } ThrowIfDisposed(); SpinWait spinWait = default(SpinWait); while (true) { int currentCount = _currentCount; if (currentCount <= 0) { return false; } if (currentCount > int.MaxValue - signalCount) { throw new InvalidOperationException(System.SR.CountdownEvent_Increment_AlreadyMax); } if (Interlocked.CompareExchange(ref _currentCount, currentCount + signalCount, currentCount) == currentCount) { break; } spinWait.SpinOnce(); } return true; } public void Reset() { Reset(_initialCount); } public void Reset(int count) { ThrowIfDisposed(); if (count < 0) { throw new ArgumentOutOfRangeException("count"); } _currentCount = count; _initialCount = count; if (count == 0) { _event.Set(); } else { _event.Reset(); } } public void Wait() { Wait(-1, default(CancellationToken)); } public void Wait(CancellationToken cancellationToken) { Wait(-1, cancellationToken); } public bool Wait(TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)num, default(CancellationToken)); } public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)num, cancellationToken); } public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, default(CancellationToken)); } public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout"); } ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); bool flag = IsSet; if (!flag) { flag = _event.Wait(millisecondsTimeout, cancellationToken); } return flag; } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException("CountdownEvent"); } } } public enum LockRecursionPolicy { NoRecursion, SupportsRecursion } internal class ReaderWriterCount { public long lockID; public int readercount; public int writercount; public int upgradecount; public System.Threading.ReaderWriterCount next; } public class ReaderWriterLockSlim : IDisposable { private struct TimeoutTracker { private int _total; private int _start; public int RemainingMilliseconds { get { if (_total == -1 || _total == 0) { return _total; } int num = Environment.TickCount - _start; if (num < 0 || num >= _total) { return 0; } return _total - num; } } public bool IsExpired => RemainingMilliseconds == 0; public TimeoutTracker(TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } _total = (int)num; if (_total != -1 && _total != 0) { _start = Environment.TickCount; } else { _start = 0; } } public TimeoutTracker(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout"); } _total = millisecondsTimeout; if (_total != -1 && _total != 0) { _start = Environment.TickCount; } else { _start = 0; } } } private bool _fIsReentrant; private int _myLock; private const int LockSpinCycles = 20; private const int LockSpinCount = 10; private const int LockSleep0Count = 5; private uint _numWriteWaiters; private uint _numReadWaiters; private uint _numWriteUpgradeWaiters; private uint _numUpgradeWaiters; private bool _fNoWaiters; private int _upgradeLockOwnerId; private int _writeLockOwnerId; private EventWaitHandle _writeEvent; private EventWaitHandle _readEvent; private EventWaitHandle _upgradeEvent; private EventWaitHandle _waitUpgradeEvent; private static long s_nextLockID; private long _lockID; [ThreadStatic] private static System.Threading.ReaderWriterCount t_rwc; private bool _fUpgradeThreadHoldingRead; private const int MaxSpinCount = 20; private uint _owners; private const uint WRITER_HELD = 2147483648u; private const uint WAITING_WRITERS = 1073741824u; private const uint WAITING_UPGRADER = 536870912u; private const uint MAX_READER = 268435454u; private const uint READER_MASK = 268435455u; private bool _fDisposed; public bool IsReadLockHeld { get { if (RecursiveReadCount > 0) { return true; } return false; } } public bool IsUpgradeableReadLockHeld { get { if (RecursiveUpgradeCount > 0) { return true; } return false; } } public bool IsWriteLockHeld { get { if (RecursiveWriteCount > 0) { return true; } return false; } } public LockRecursionPolicy RecursionPolicy { get { if (_fIsReentrant) { return LockRecursionPolicy.SupportsRecursion; } return LockRecursionPolicy.NoRecursion; } } public int CurrentReadCount { get { int numReaders = (int)GetNumReaders(); if (_upgradeLockOwnerId != -1) { return numReaders - 1; } return numReaders; } } public int RecursiveReadCount { get { int result = 0; System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null) { result = threadRWCount.readercount; } return result; } } public int RecursiveUpgradeCount { get { if (_fIsReentrant) { int result = 0; System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null) { result = threadRWCount.upgradecount; } return result; } if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId) { return 1; } return 0; } } public int RecursiveWriteCount { get { if (_fIsReentrant) { int result = 0; System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null) { result = threadRWCount.writercount; } return result; } if (Environment.CurrentManagedThreadId == _writeLockOwnerId) { return 1; } return 0; } } public int WaitingReadCount => (int)_numReadWaiters; public int WaitingUpgradeCount => (int)_numUpgradeWaiters; public int WaitingWriteCount => (int)_numWriteWaiters; private void InitializeThreadCounts() { _upgradeLockOwnerId = -1; _writeLockOwnerId = -1; } public ReaderWriterLockSlim() : this(LockRecursionPolicy.NoRecursion) { } public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy) { if (recursionPolicy == LockRecursionPolicy.SupportsRecursion) { _fIsReentrant = true; } InitializeThreadCounts(); _fNoWaiters = true; _lockID = Interlocked.Increment(ref s_nextLockID); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsRWEntryEmpty(System.Threading.ReaderWriterCount rwc) { if (rwc.lockID == 0L) { return true; } if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0) { return true; } return false; } private bool IsRwHashEntryChanged(System.Threading.ReaderWriterCount lrwc) { return lrwc.lockID != _lockID; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private System.Threading.ReaderWriterCount GetThreadRWCount(bool dontAllocate) { System.Threading.ReaderWriterCount next = t_rwc; System.Threading.ReaderWriterCount readerWriterCount = null; while (next != null) { if (next.lockID == _lockID) { return next; } if (!dontAllocate && readerWriterCount == null && IsRWEntryEmpty(next)) { readerWriterCount = next; } next = next.next; } if (dontAllocate) { return null; } if (readerWriterCount == null) { readerWriterCount = new System.Threading.ReaderWriterCount(); readerWriterCount.next = t_rwc; t_rwc = readerWriterCount; } readerWriterCount.lockID = _lockID; return readerWriterCount; } public void EnterReadLock() { TryEnterReadLock(-1); } public bool TryEnterReadLock(TimeSpan timeout) { return TryEnterReadLock(new TimeoutTracker(timeout)); } public bool TryEnterReadLock(int millisecondsTimeout) { return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterReadLock(TimeoutTracker timeout) { return TryEnterReadLockCore(timeout); } private bool TryEnterReadLockCore(TimeoutTracker timeout) { if (_fDisposed) { throw new ObjectDisposedException(null); } System.Threading.ReaderWriterCount readerWriterCount = null; int currentManagedThreadId = Environment.CurrentManagedThreadId; if (!_fIsReentrant) { if (currentManagedThreadId == _writeLockOwnerId) { throw new LockRecursionException(System.SR.LockRecursionException_ReadAfterWriteNotAllowed); } EnterMyLock(); readerWriterCount = GetThreadRWCount(dontAllocate: false); if (readerWriterCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_RecursiveReadNotAllowed); } if (currentManagedThreadId == _upgradeLockOwnerId) { readerWriterCount.readercount++; _owners++; ExitMyLock(); return true; } } else { EnterMyLock(); readerWriterCount = GetThreadRWCount(dontAllocate: false); if (readerWriterCount.readercount > 0) { readerWriterCount.readercount++; ExitMyLock(); return true; } if (currentManagedThreadId == _upgradeLockOwnerId) { readerWriterCount.readercount++; _owners++; ExitMyLock(); _fUpgradeThreadHoldingRead = true; return true; } if (currentManagedThreadId == _writeLockOwnerId) { readerWriterCount.readercount++; _owners++; ExitMyLock(); return true; } } bool flag = true; int num = 0; while (true) { if (_owners < 268435454) { _owners++; readerWriterCount.readercount++; ExitMyLock(); return flag; } if (num < 20) { ExitMyLock(); if (timeout.IsExpired) { return false; } num++; SpinWait(num); EnterMyLock(); if (IsRwHashEntryChanged(readerWriterCount)) { readerWriterCount = GetThreadRWCount(dontAllocate: false); } } else if (_readEvent == null) { LazyCreateEvent(ref _readEvent, makeAutoResetEvent: false); if (IsRwHashEntryChanged(readerWriterCount)) { readerWriterCount = GetThreadRWCount(dontAllocate: false); } } else { flag = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, isWriteWaiter: false); if (!flag) { break; } if (IsRwHashEntryChanged(readerWriterCount)) { readerWriterCount = GetThreadRWCount(dontAllocate: false); } } } return false; } public void EnterWriteLock() { TryEnterWriteLock(-1); } public bool TryEnterWriteLock(TimeSpan timeout) { return TryEnterWriteLock(new TimeoutTracker(timeout)); } public bool TryEnterWriteLock(int millisecondsTimeout) { return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterWriteLock(TimeoutTracker timeout) { return TryEnterWriteLockCore(timeout); } private bool TryEnterWriteLockCore(TimeoutTracker timeout) { if (_fDisposed) { throw new ObjectDisposedException(null); } int currentManagedThreadId = Environment.CurrentManagedThreadId; bool flag = false; System.Threading.ReaderWriterCount threadRWCount; if (!_fIsReentrant) { if (currentManagedThreadId == _writeLockOwnerId) { throw new LockRecursionException(System.SR.LockRecursionException_RecursiveWriteNotAllowed); } if (currentManagedThreadId == _upgradeLockOwnerId) { flag = true; } EnterMyLock(); threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null && threadRWCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_WriteAfterReadNotAllowed); } } else { EnterMyLock(); threadRWCount = GetThreadRWCount(dontAllocate: false); if (currentManagedThreadId == _writeLockOwnerId) { threadRWCount.writercount++; ExitMyLock(); return true; } if (currentManagedThreadId == _upgradeLockOwnerId) { flag = true; } else if (threadRWCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_WriteAfterReadNotAllowed); } } int num = 0; bool flag2 = true; while (true) { if (IsWriterAcquired()) { SetWriterAcquired(); break; } if (flag) { uint numReaders = GetNumReaders(); if (numReaders == 1) { SetWriterAcquired(); break; } if (numReaders == 2 && threadRWCount != null) { if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } if (threadRWCount.readercount > 0) { SetWriterAcquired(); break; } } } if (num < 20) { ExitMyLock(); if (timeout.IsExpired) { return false; } num++; SpinWait(num); EnterMyLock(); } else if (flag) { if (_waitUpgradeEvent == null) { LazyCreateEvent(ref _waitUpgradeEvent, makeAutoResetEvent: true); } else if (!WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, isWriteWaiter: true)) { return false; } } else if (_writeEvent == null) { LazyCreateEvent(ref _writeEvent, makeAutoResetEvent: true); } else if (!WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, isWriteWaiter: true)) { return false; } } if (_fIsReentrant) { if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } threadRWCount.writercount++; } ExitMyLock(); _writeLockOwnerId = currentManagedThreadId; return true; } public void EnterUpgradeableReadLock() { TryEnterUpgradeableReadLock(-1); } public bool TryEnterUpgradeableReadLock(TimeSpan timeout) { return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout)); } public bool TryEnterUpgradeableReadLock(int millisecondsTimeout) { return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout) { return TryEnterUpgradeableReadLockCore(timeout); } private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout) { if (_fDisposed) { throw new ObjectDisposedException(null); } int currentManagedThreadId = Environment.CurrentManagedThreadId; System.Threading.ReaderWriterCount threadRWCount; if (!_fIsReentrant) { if (currentManagedThreadId == _upgradeLockOwnerId) { throw new LockRecursionException(System.SR.LockRecursionException_RecursiveUpgradeNotAllowed); } if (currentManagedThreadId == _writeLockOwnerId) { throw new LockRecursionException(System.SR.LockRecursionException_UpgradeAfterWriteNotAllowed); } EnterMyLock(); threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null && threadRWCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_UpgradeAfterReadNotAllowed); } } else { EnterMyLock(); threadRWCount = GetThreadRWCount(dontAllocate: false); if (currentManagedThreadId == _upgradeLockOwnerId) { threadRWCount.upgradecount++; ExitMyLock(); return true; } if (currentManagedThreadId == _writeLockOwnerId) { _owners++; _upgradeLockOwnerId = currentManagedThreadId; threadRWCount.upgradecount++; if (threadRWCount.readercount > 0) { _fUpgradeThreadHoldingRead = true; } ExitMyLock(); return true; } if (threadRWCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_UpgradeAfterReadNotAllowed); } } bool flag = true; int num = 0; while (true) { if (_upgradeLockOwnerId == -1 && _owners < 268435454) { _owners++; _upgradeLockOwnerId = currentManagedThreadId; if (_fIsReentrant) { if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } threadRWCount.upgradecount++; } break; } if (num < 20) { ExitMyLock(); if (timeout.IsExpired) { return false; } num++; SpinWait(num); EnterMyLock(); } else if (_upgradeEvent == null) { LazyCreateEvent(ref _upgradeEvent, makeAutoResetEvent: true); } else if (!WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, isWriteWaiter: false)) { return false; } } ExitMyLock(); return true; } public void ExitReadLock() { System.Threading.ReaderWriterCount readerWriterCount = null; EnterMyLock(); readerWriterCount = GetThreadRWCount(dontAllocate: true); if (readerWriterCount == null || readerWriterCount.readercount < 1) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedRead); } if (_fIsReentrant) { if (readerWriterCount.readercount > 1) { readerWriterCount.readercount--; ExitMyLock(); return; } if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId) { _fUpgradeThreadHoldingRead = false; } } _owners--; readerWriterCount.readercount--; ExitAndWakeUpAppropriateWaiters(); } public void ExitWriteLock() { if (!_fIsReentrant) { if (Environment.CurrentManagedThreadId != _writeLockOwnerId) { throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedWrite); } EnterMyLock(); } else { EnterMyLock(); System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: false); if (threadRWCount == null) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedWrite); } if (threadRWCount.writercount < 1) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedWrite); } threadRWCount.writercount--; if (threadRWCount.writercount > 0) { ExitMyLock(); return; } } ClearWriterAcquired(); _writeLockOwnerId = -1; ExitAndWakeUpAppropriateWaiters(); } public void ExitUpgradeableReadLock() { if (!_fIsReentrant) { if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId) { throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedUpgrade); } EnterMyLock(); } else { EnterMyLock(); System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount == null) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedUpgrade); } if (threadRWCount.upgradecount < 1) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedUpgrade); } threadRWCount.upgradecount--; if (threadRWCount.upgradecount > 0) { ExitMyLock(); return; } _fUpgradeThreadHoldingRead = false; } _owners--; _upgradeLockOwnerId = -1; ExitAndWakeUpAppropriateWaiters(); } private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) { ExitMyLock(); EventWaitHandle eventWaitHandle = ((!makeAutoResetEvent) ? ((EventWaitHandle)new ManualResetEvent(initialState: false)) : ((EventWaitHandle)new AutoResetEvent(initialState: false))); EnterMyLock(); if (waitEvent == null) { waitEvent = eventWaitHandle; } else { eventWaitHandle.Dispose(); } } private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, TimeoutTracker timeout, bool isWriteWaiter) { waitEvent.Reset(); numWaiters++; _fNoWaiters = false; if (_numWriteWaiters == 1) { SetWritersWaiting(); } if (_numWriteUpgradeWaiters == 1) { SetUpgraderWaiting(); } bool flag = false; ExitMyLock(); try { flag = waitEvent.WaitOne(timeout.RemainingMilliseconds); } finally { EnterMyLock(); numWaiters--; if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0) { _fNoWaiters = true; } if (_numWriteWaiters == 0) { ClearWritersWaiting(); } if (_numWriteUpgradeWaiters == 0) { ClearUpgraderWaiting(); } if (!flag) { if (isWriteWaiter) { ExitAndWakeUpAppropriateReadWaiters(); } else { ExitMyLock(); } } } return flag; } private void ExitAndWakeUpAppropriateWaiters() { if (_fNoWaiters) { ExitMyLock(); } else { ExitAndWakeUpAppropriateWaitersPreferringWriters(); } } private void ExitAndWakeUpAppropriateWaitersPreferringWriters() { uint numReaders = GetNumReaders(); if (_fIsReentrant && _numWriteUpgradeWaiters != 0 && _fUpgradeThreadHoldingRead && numReaders == 2) { ExitMyLock(); _waitUpgradeEvent.Set(); } else if (numReaders == 1 && _numWriteUpgradeWaiters != 0) { ExitMyLock(); _waitUpgradeEvent.Set(); } else if (numReaders == 0 && _numWriteWaiters != 0) { ExitMyLock(); _writeEvent.Set(); } else { ExitAndWakeUpAppropriateReadWaiters(); } } private void ExitAndWakeUpAppropriateReadWaiters() { if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || _fNoWaiters) { ExitMyLock(); return; } bool flag = _numReadWaiters != 0; bool flag2 = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1; ExitMyLock(); if (flag) { _readEvent.Set(); } if (flag2) { _upgradeEvent.Set(); } } private bool IsWriterAcquired() { return (_owners & 0xBFFFFFFFu) == 0; } private void SetWriterAcquired() { _owners |= 2147483648u; } private void ClearWriterAcquired() { _owners &= 2147483647u; } private void SetWritersWaiting() { _owners |= 1073741824u; } private void ClearWritersWaiting() { _owners &= 3221225471u; } private void SetUpgraderWaiting() { _owners |= 536870912u; } private void ClearUpgraderWaiting() { _owners &= 3758096383u; } private uint GetNumReaders() { return _owners & 0xFFFFFFFu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnterMyLock() { if (Interlocked.CompareExchange(ref _myLock, 1, 0) != 0) { EnterMyLockSpin(); } } private void EnterMyLockSpin() { int processorCount = Environment.ProcessorCount; int num = 0; while (true) { if (num < 10 && processorCount > 1) { Helpers.Spin(20 * (num + 1)); } else if (num < 15) { Helpers.Sleep(0); } else { Helpers.Sleep(1); } if (_myLock == 0 && Interlocked.CompareExchange(ref _myLock, 1, 0) == 0) { break; } num++; } } private void ExitMyLock() { Volatile.Write(ref _myLock, 0); } private static void SpinWait(int SpinCount) { if (SpinCount < 5 && Environment.ProcessorCount > 1) { Helpers.Spin(20 * SpinCount); } else if (SpinCount < 17) { Helpers.Sleep(0); } else { Helpers.Sleep(1); } } public void Dispose() { Dispose(disposing: true); } private void Dispose(bool disposing) { if (disposing && !_fDisposed) { if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0) { throw new SynchronizationLockException(System.SR.SynchronizationLockException_IncorrectDispose); } if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld) { throw new SynchronizationLockException(System.SR.SynchronizationLockException_IncorrectDispose); } if (_writeEvent != null) { _writeEvent.Dispose(); _writeEvent = null; } if (_readEvent != null) { _readEvent.Dispose(); _readEvent = null; } if (_upgradeEvent != null) { _upgradeEvent.Dispose(); _upgradeEvent = null; } if (_waitUpgradeEvent != null) { _waitUpgradeEvent.Dispose(); _waitUpgradeEvent = null; } _fDisposed = true; } } } }
BepInEx/plugins/VNyanCommands/System.Threading.Tasks.Extensions.dll
Decompiled 2 years agousing 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 { } }
BepInEx/plugins/VNyanCommands/VNyanCommands.dll
Decompiled 2 years agousing System; using System.Diagnostics; using System.Net.WebSockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using UnityEngine; using Websocket.Client; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("VNyanCommands")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Create interactions in VNyan based on Lethal Company events")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: AssemblyInformationalVersion("1.3.0")] [assembly: AssemblyProduct("VNyanCommands")] [assembly: AssemblyTitle("VNyanCommands")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.3.0.0")] [module: UnverifiableCode] namespace VNyanCommands { [BepInPlugin("VNyanCommands", "VNyanCommands", "1.3.0")] public class Plugin : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("VNyanCommands"); public static ManualLogSource logger; public static WebsocketClient wsClient; public static ConfigEntry<string> vnyanUrl; public static ConfigEntry<string> prefix; private void StartWS() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown try { wsClient = new WebsocketClient(new Uri(vnyanUrl.Value), (Func<ClientWebSocket>)null) { ReconnectTimeout = TimeSpan.FromSeconds(30.0) }; ObservableExtensions.Subscribe<ReconnectionInfo>(wsClient.ReconnectionHappened, (Action<ReconnectionInfo>)delegate(ReconnectionInfo info) { //IL_0001: 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_0027: Unknown result type (might be due to invalid IL or missing references) if ((int)info.Type == 0) { logger.LogInfo((object)"Vnyan WebSocket started!"); } ManualLogSource obj = logger; ReconnectionType type = info.Type; obj.LogDebug((object)("Reconnection happened, type: " + ((object)(ReconnectionType)(ref type)).ToString())); }); wsClient.Start(); } catch (Exception ex) { logger.LogError((object)ex.ToString()); } } public static void sendWS(string message) { string text = prefix.Value + message; logger.LogInfo((object)("Sending message: " + text)); wsClient.Send(text); } private void Awake() { logger = ((BaseUnityPlugin)this).Logger; vnyanUrl = ((BaseUnityPlugin)this).Config.Bind<string>("General", "VnyanUrl", "ws://localhost:8000/vnyan", "VNyan WebSocket server URL. It can be modified in `Menu -> Misc -> WebSockets` on VNyan"); prefix = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Prefix", "LC_", "Prefix added before every WS message"); StartWS(); logger.LogInfo((object)"Plugin VNyanCommands is loaded!"); harmony.PatchAll(); } private void OnDestroy() { harmony.UnpatchSelf(); wsClient.Dispose(); } } public static class PluginInfo { public const string PLUGIN_GUID = "VNyanCommands"; public const string PLUGIN_NAME = "VNyanCommands"; public const string PLUGIN_VERSION = "1.3.0"; } } namespace VNyanCommands.Events { [HarmonyPatch(typeof(PlayerControllerB))] internal class DamagePlayerEvents { [HarmonyPatch("DamagePlayer")] [HarmonyPrefix] private static void DamagePlayer(PlayerControllerB __instance, int damageNumber, CauseOfDeath causeOfDeath = 0) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Invalid comparison between Unknown and I4 if ((Object)(object)StartOfRound.Instance.localPlayerController != (Object)(object)__instance) { return; } int health = __instance.health; int num = ((!__instance.isPlayerDead && __instance.AllowPlayerDeath()) ? damageNumber : 0); int num2 = ((__instance.health - num > 0 || __instance.criticallyInjured || num >= 50) ? Mathf.Clamp(__instance.health - num, 0, 100) : 5); if (health <= 0 || num2 > 0 || health == num2) { Plugin.sendWS("PlayerDamage"); if ((int)causeOfDeath == 1) { Plugin.sendWS("PlayerDamage_Shovel"); } } } } [HarmonyPatch(typeof(PlayerControllerB))] internal class LocalPlayerDeath { [HarmonyPatch("KillPlayer")] [HarmonyPostfix] private static void KillPlayer(PlayerControllerB __instance, CauseOfDeath causeOfDeath = 0) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)StartOfRound.Instance.localPlayerController != (Object)(object)__instance) { return; } string message = $"Death_{causeOfDeath}"; DeadBodyInfo deadBody = __instance.deadBody; if ((Object)(object)deadBody != (Object)null) { if (deadBody.detachedHead && ((Object)deadBody).name.Contains("RagdollSpring")) { Plugin.sendWS("Death_Spring"); } if ((Object)(object)deadBody?.attachedTo != (Object)null && ((Object)deadBody.attachedTo.parent).name.Contains("WebHanger")) { Plugin.sendWS("Death_Cocoon"); } } Plugin.sendWS("Death"); Plugin.sendWS(message); } catch (Exception ex) { Plugin.logger.LogError((object)("Error in PlayerControllerB.killPlayer.Postfix: " + ex)); Plugin.logger.LogError((object)ex.StackTrace); } } } [HarmonyPatch(typeof(BlobAI))] [HarmonyPatch("SlimeKillPlayerEffectClientRpc")] internal class SlimeDeath { public static void Postfix(int playerKilled) { try { PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController; PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerKilled]; if (!((Object)(object)val == (Object)null) && !((Object)(object)localPlayerController != (Object)(object)val) && val.isPlayerDead) { Plugin.sendWS("Death_Slime"); } } catch (Exception ex) { Plugin.logger.LogError((object)("Error in BlobAISlimeKillPlayerEffectServerRpcPatch.Postfix: " + ex)); Plugin.logger.LogError((object)ex.StackTrace); } } } [HarmonyPatch(typeof(MaskedPlayerEnemy))] [HarmonyPatch("killAnimation")] internal class EnemyMaskDeath { public static void Postfix(MaskedPlayerEnemy __instance) { try { PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController; PlayerControllerB inSpecialAnimationWithPlayer = ((EnemyAI)__instance).inSpecialAnimationWithPlayer; if (!((Object)(object)inSpecialAnimationWithPlayer == (Object)null) && !((Object)(object)localPlayerController != (Object)(object)inSpecialAnimationWithPlayer)) { Plugin.sendWS("Death_Possession"); } } catch (Exception ex) { Plugin.logger.LogError((object)("Error in MaskedPlayerEnemykillAnimationPatch.Postfix: " + ex)); Plugin.logger.LogError((object)ex.StackTrace); } } } [HarmonyPatch(typeof(DressGirlAI))] [HarmonyPatch("OnCollideWithPlayer")] internal class DressGirlAIOnCollideWithPlayerPatch { public static void Postfix(DressGirlAI __instance) { try { PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController; PlayerControllerB hauntingPlayer = __instance.hauntingPlayer; if (!((Object)(object)hauntingPlayer == (Object)null) && !((Object)(object)localPlayerController != (Object)(object)hauntingPlayer) && hauntingPlayer.isPlayerDead) { Plugin.sendWS("Death_Decapitation"); } } catch (Exception ex) { Plugin.logger.LogError((object)("Error in DressGirlAIOnCollideWithPlayerPatch.Postfix: " + ex)); Plugin.logger.LogError((object)ex.StackTrace); } } } [HarmonyPatch(typeof(WalkieTalkie))] internal class WalkieTalkieEvents { [HarmonyPatch("EquipItem")] [HarmonyPostfix] private static void EquipItem(WalkieTalkie __instance) { PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController; PlayerControllerB playerHeldBy = ((GrabbableObject)__instance).playerHeldBy; if ((Object)(object)localPlayerController == (Object)(object)playerHeldBy) { Plugin.sendWS("WalkieTalkie_Hold_On"); } } [HarmonyPatch("PocketItem")] [HarmonyPostfix] private static void PocketItem(WalkieTalkie __instance) { PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController; PlayerControllerB playerHeldBy = ((GrabbableObject)__instance).playerHeldBy; if ((Object)(object)localPlayerController == (Object)(object)playerHeldBy) { Plugin.sendWS("WalkieTalkie_Hold_Off"); } } [HarmonyPatch("SwitchWalkieTalkieOn")] [HarmonyPostfix] private static void SwitchWalkieTalkieOn(WalkieTalkie __instance, bool on) { PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController; PlayerControllerB playerHeldBy = ((GrabbableObject)__instance).playerHeldBy; if ((Object)(object)localPlayerController == (Object)(object)playerHeldBy) { Plugin.sendWS("WalkieTalkie_Power_" + (on ? "On" : "Off")); } } [HarmonyPatch("SetLocalClientSpeaking")] [HarmonyPostfix] private static void SetLocalClientSpeaking(WalkieTalkie __instance, bool speaking) { PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController; PlayerControllerB playerHeldBy = ((GrabbableObject)__instance).playerHeldBy; if ((Object)(object)localPlayerController == (Object)(object)playerHeldBy) { Plugin.sendWS("WalkieTalkie_Speak_" + (speaking ? "On" : "Off")); } } } }
BepInEx/plugins/VNyanCommands/Websocket.Client.dll
Decompiled 2 years agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.WebSockets; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Websocket.Client.Exceptions; using Websocket.Client.Threading; using Websocket.Client.Validations; [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("Mariusz Kotas")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2023 Mariusz Kotas. All rights reserved.")] [assembly: AssemblyDescription("Client for websocket API with built-in reconnection and error handling")] [assembly: AssemblyFileVersion("5.0.0.0")] [assembly: AssemblyInformationalVersion("5.0.0")] [assembly: AssemblyProduct("Websocket.Client")] [assembly: AssemblyTitle("Websocket.Client")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Marfusios/websocket-client")] [assembly: AssemblyVersion("5.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 Websocket.Client { public interface IWebsocketClient : IDisposable { Uri Url { get; set; } IObservable<ResponseMessage> MessageReceived { get; } IObservable<ReconnectionInfo> ReconnectionHappened { get; } IObservable<DisconnectionInfo> DisconnectionHappened { get; } TimeSpan? ReconnectTimeout { get; set; } TimeSpan? ErrorReconnectTimeout { get; set; } TimeSpan? LostReconnectTimeout { get; set; } string? Name { get; set; } bool IsStarted { get; } bool IsRunning { get; } bool IsReconnectionEnabled { get; set; } bool IsTextMessageConversionEnabled { get; set; } ClientWebSocket? NativeClient { get; } Encoding? MessageEncoding { get; set; } Task Start(); Task StartOrFail(); Task<bool> Stop(WebSocketCloseStatus status, string statusDescription); Task<bool> StopOrFail(WebSocketCloseStatus status, string statusDescription); void Send(string message); void Send(byte[] message); void Send(ArraySegment<byte> message); Task SendInstant(string message); Task SendInstant(byte[] message); Task Reconnect(); Task ReconnectOrFail(); void StreamFakeMessage(ResponseMessage message); } public class DisconnectionInfo { public DisconnectionType Type { get; } public WebSocketCloseStatus? CloseStatus { get; } public string? CloseStatusDescription { get; } public string? SubProtocol { get; } public Exception? Exception { get; } public bool CancelReconnection { get; set; } public bool CancelClosing { get; set; } public DisconnectionInfo(DisconnectionType type, WebSocketCloseStatus? closeStatus, string? closeStatusDescription, string? subProtocol, Exception? exception) { Type = type; CloseStatus = closeStatus; CloseStatusDescription = closeStatusDescription; SubProtocol = subProtocol; Exception = exception; } public static DisconnectionInfo Create(DisconnectionType type, WebSocket? client, Exception? exception) { return new DisconnectionInfo(type, client?.CloseStatus, client?.CloseStatusDescription, client?.SubProtocol, exception); } } public enum DisconnectionType { Exit, Lost, NoMessageReceived, Error, ByUser, ByServer } public class ReconnectionInfo { public ReconnectionType Type { get; } public ReconnectionInfo(ReconnectionType type) { Type = type; } public static ReconnectionInfo Create(ReconnectionType type) { return new ReconnectionInfo(type); } } public enum ReconnectionType { Initial, Lost, NoMessageReceived, Error, ByUser, ByServer } public class ResponseMessage { public string? Text { get; } public byte[]? Binary { get; } public WebSocketMessageType MessageType { get; } private ResponseMessage(byte[]? binary, string? text, WebSocketMessageType messageType) { Binary = binary; Text = text; MessageType = messageType; } public override string ToString() { if (MessageType == WebSocketMessageType.Text) { return Text ?? string.Empty; } return $"Type binary, length: {Binary?.Length}"; } public static ResponseMessage TextMessage(string? data) { return new ResponseMessage(null, data, WebSocketMessageType.Text); } public static ResponseMessage BinaryMessage(byte[]? data) { return new ResponseMessage(data, null, WebSocketMessageType.Binary); } } public class WebsocketClient : IWebsocketClient, IDisposable { private readonly ILogger<WebsocketClient> _logger; private readonly WebsocketAsyncLock _locker = new WebsocketAsyncLock(); private readonly Func<Uri, CancellationToken, Task<WebSocket>> _connectionFactory; private Uri _url; private Timer? _lastChanceTimer; private DateTime _lastReceivedMsg = DateTime.UtcNow; private Timer? _errorReconnectTimer; private bool _disposing; private bool _reconnecting; private bool _stopping; private bool _isReconnectionEnabled = true; private WebSocket? _client; private CancellationTokenSource? _cancellation; private CancellationTokenSource? _cancellationTotal; private readonly Subject<ResponseMessage> _messageReceivedSubject = new Subject<ResponseMessage>(); private readonly Subject<ReconnectionInfo> _reconnectionSubject = new Subject<ReconnectionInfo>(); private readonly Subject<DisconnectionInfo> _disconnectedSubject = new Subject<DisconnectionInfo>(); private readonly Channel<string> _messagesTextToSendQueue = Channel.CreateUnbounded<string>(new UnboundedChannelOptions { SingleReader = true, SingleWriter = false }); private readonly Channel<ArraySegment<byte>> _messagesBinaryToSendQueue = Channel.CreateUnbounded<ArraySegment<byte>>(new UnboundedChannelOptions { SingleReader = true, SingleWriter = false }); public Uri Url { get { return _url; } set { Websocket.Client.Validations.Validations.ValidateInput(value, "Url"); _url = value; } } public IObservable<ResponseMessage> MessageReceived => Observable.AsObservable<ResponseMessage>((IObservable<ResponseMessage>)_messageReceivedSubject); public IObservable<ReconnectionInfo> ReconnectionHappened => Observable.AsObservable<ReconnectionInfo>((IObservable<ReconnectionInfo>)_reconnectionSubject); public IObservable<DisconnectionInfo> DisconnectionHappened => Observable.AsObservable<DisconnectionInfo>((IObservable<DisconnectionInfo>)_disconnectedSubject); public TimeSpan? ReconnectTimeout { get; set; } = TimeSpan.FromMinutes(1.0); public TimeSpan? ErrorReconnectTimeout { get; set; } = TimeSpan.FromMinutes(1.0); public TimeSpan? LostReconnectTimeout { get; set; } public bool IsReconnectionEnabled { get { return _isReconnectionEnabled; } set { _isReconnectionEnabled = value; if (IsStarted) { if (_isReconnectionEnabled) { ActivateLastChance(); } else { DeactivateLastChance(); } } } } public string? Name { get; set; } public bool IsStarted { get; private set; } public bool IsRunning { get; private set; } public bool IsTextMessageConversionEnabled { get; set; } = true; public Encoding? MessageEncoding { get; set; } public ClientWebSocket? NativeClient => GetSpecificOrThrow(_client); public WebsocketClient(Uri url, Func<ClientWebSocket>? clientFactory = null) : this(url, null, GetClientFactory(clientFactory)) { } public WebsocketClient(Uri url, ILogger<WebsocketClient>? logger, Func<ClientWebSocket>? clientFactory = null) : this(url, logger, GetClientFactory(clientFactory)) { } public WebsocketClient(Uri url, ILogger<WebsocketClient>? logger, Func<Uri, CancellationToken, Task<WebSocket>>? connectionFactory) { Websocket.Client.Validations.Validations.ValidateInput(url, "url"); _logger = logger ?? NullLogger<WebsocketClient>.Instance; _url = url; _connectionFactory = connectionFactory ?? ((Func<Uri, CancellationToken, Task<WebSocket>>)async delegate(Uri uri, CancellationToken token) { ClientWebSocket client = new ClientWebSocket(); await client.ConnectAsync(uri, token).ConfigureAwait(continueOnCapturedContext: false); return client; }); } public void Dispose() { _disposing = true; _logger.LogDebug(L("Disposing.."), Name); try { _messagesTextToSendQueue.Writer.Complete(); _messagesBinaryToSendQueue.Writer.Complete(); _lastChanceTimer?.Dispose(); _errorReconnectTimer?.Dispose(); _cancellation?.Cancel(); _cancellationTotal?.Cancel(); _client?.Abort(); _client?.Dispose(); _cancellation?.Dispose(); _cancellationTotal?.Dispose(); ((SubjectBase<ResponseMessage>)(object)_messageReceivedSubject).OnCompleted(); ((SubjectBase<ReconnectionInfo>)(object)_reconnectionSubject).OnCompleted(); } catch (Exception ex) { _logger.LogError(ex, L("Failed to dispose client, error: {error}"), Name, ex.Message); } if (IsRunning) { ((SubjectBase<DisconnectionInfo>)(object)_disconnectedSubject).OnNext(DisconnectionInfo.Create(DisconnectionType.Exit, _client, null)); } IsRunning = false; IsStarted = false; ((SubjectBase<DisconnectionInfo>)(object)_disconnectedSubject).OnCompleted(); } public Task Start() { return StartInternal(failFast: false); } public Task StartOrFail() { return StartInternal(failFast: true); } public async Task<bool> Stop(WebSocketCloseStatus status, string statusDescription) { bool result = await StopInternal(_client, status, statusDescription, null, failFast: false, byServer: false).ConfigureAwait(continueOnCapturedContext: false); ((SubjectBase<DisconnectionInfo>)(object)_disconnectedSubject).OnNext(DisconnectionInfo.Create(DisconnectionType.ByUser, _client, null)); return result; } public async Task<bool> StopOrFail(WebSocketCloseStatus status, string statusDescription) { bool result = await StopInternal(_client, status, statusDescription, null, failFast: true, byServer: false).ConfigureAwait(continueOnCapturedContext: false); ((SubjectBase<DisconnectionInfo>)(object)_disconnectedSubject).OnNext(DisconnectionInfo.Create(DisconnectionType.ByUser, _client, null)); return result; } private static Func<Uri, CancellationToken, Task<WebSocket>>? GetClientFactory(Func<ClientWebSocket>? clientFactory) { Func<ClientWebSocket> clientFactory2 = clientFactory; if (clientFactory2 == null) { return null; } return async delegate(Uri uri, CancellationToken token) { ClientWebSocket client = clientFactory2(); await client.ConnectAsync(uri, token).ConfigureAwait(continueOnCapturedContext: false); return client; }; } private async Task StartInternal(bool failFast) { if (_disposing) { throw new WebsocketException("Client " + Name + " is already disposed, starting not possible"); } if (IsStarted) { _logger.LogDebug(L("Client already started, ignoring.."), Name); return; } IsStarted = true; _logger.LogDebug(L("Starting.."), Name); _cancellation = new CancellationTokenSource(); _cancellationTotal = new CancellationTokenSource(); await StartClient(_url, _cancellation.Token, ReconnectionType.Initial, failFast).ConfigureAwait(continueOnCapturedContext: false); StartBackgroundThreadForSendingText(); StartBackgroundThreadForSendingBinary(); } private async Task<bool> StopInternal(WebSocket? client, WebSocketCloseStatus status, string statusDescription, CancellationToken? cancellation, bool failFast, bool byServer) { if (_disposing) { throw new WebsocketException("Client " + Name + " is already disposed, stopping not possible"); } DeactivateLastChance(); if (client == null) { IsStarted = false; IsRunning = false; return false; } if (!IsRunning) { _logger.LogInformation(L("Client is already stopped"), Name); IsStarted = false; return false; } bool result = false; try { CancellationToken cancellationToken = cancellation ?? CancellationToken.None; _stopping = true; if (!byServer) { await client.CloseAsync(status, statusDescription, cancellationToken); } else { await client.CloseOutputAsync(status, statusDescription, cancellationToken); } result = true; } catch (Exception ex) { _logger.LogError(ex, L("Error while stopping client, message: '{error}'"), Name, ex.Message); if (failFast) { throw new WebsocketException("Failed to stop Websocket client " + Name + ", error: '" + ex.Message + "'", ex); } } finally { IsRunning = false; _stopping = false; if (!byServer || !IsReconnectionEnabled) { IsStarted = false; } } return result; } private async Task StartClient(Uri uri, CancellationToken token, ReconnectionType type, bool failFast) { DeactivateLastChance(); try { _client = await _connectionFactory(uri, token).ConfigureAwait(continueOnCapturedContext: false); Listen(_client, token); IsRunning = true; IsStarted = true; ((SubjectBase<ReconnectionInfo>)(object)_reconnectionSubject).OnNext(ReconnectionInfo.Create(type)); _lastReceivedMsg = DateTime.UtcNow; ActivateLastChance(); } catch (Exception ex) { DisconnectionInfo disconnectionInfo = DisconnectionInfo.Create(DisconnectionType.Error, _client, ex); ((SubjectBase<DisconnectionInfo>)(object)_disconnectedSubject).OnNext(disconnectionInfo); if (disconnectionInfo.CancelReconnection) { _logger.LogError(ex, L("Exception while connecting. Reconnecting canceled by user, exiting. Error: '{error}'"), Name, ex.Message); return; } if (failFast) { throw new WebsocketException("Failed to start Websocket client " + Name + ", error: '" + ex.Message + "'", ex); } if (!ErrorReconnectTimeout.HasValue) { _logger.LogError(ex, L("Exception while connecting. Reconnecting disabled, exiting. Error: '{error}'"), Name, ex.Message); return; } TimeSpan value = ErrorReconnectTimeout.Value; _logger.LogError(ex, L("Exception while connecting. Waiting {timeout} sec before next reconnection try. Error: '{error}'"), Name, value.TotalSeconds, ex.Message); _errorReconnectTimer?.Dispose(); _errorReconnectTimer = new Timer(ReconnectOnError, ex, value, Timeout.InfiniteTimeSpan); } } private void ReconnectOnError(object? state) { Reconnect(ReconnectionType.Error, failFast: false, state as Exception).ConfigureAwait(continueOnCapturedContext: false); } private bool IsClientConnected() { WebSocket? client = _client; if (client == null) { return false; } return client.State == WebSocketState.Open; } private async Task Listen(WebSocket client, CancellationToken token) { Exception causedException = null; try { ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[4096]); do { byte[] resultArrayWithTrailing = null; int resultArraySize = 0; bool isResultArrayCloned = false; MemoryStream ms = null; WebSocketReceiveResult webSocketReceiveResult; while (true) { webSocketReceiveResult = await client.ReceiveAsync(buffer, token); byte[] array = buffer.Array; int count = webSocketReceiveResult.Count; if (resultArrayWithTrailing == null) { resultArraySize += count; resultArrayWithTrailing = array; isResultArrayCloned = false; } else if (array != null) { if (ms == null) { ms = new MemoryStream(); ms.Write(resultArrayWithTrailing, 0, resultArraySize); } ms.Write(array, buffer.Offset, count); } if (webSocketReceiveResult.EndOfMessage) { break; } if (!isResultArrayCloned) { resultArrayWithTrailing = resultArrayWithTrailing?.ToArray(); isResultArrayCloned = true; } } ms?.Seek(0L, SeekOrigin.Begin); ResponseMessage responseMessage; if (webSocketReceiveResult.MessageType == WebSocketMessageType.Text && IsTextMessageConversionEnabled) { responseMessage = ResponseMessage.TextMessage((ms != null) ? GetEncoding().GetString(ms.ToArray()) : ((resultArrayWithTrailing != null) ? GetEncoding().GetString(resultArrayWithTrailing, 0, resultArraySize) : null)); } else { if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close) { _logger.LogTrace(L("Received close message"), Name); if (!IsStarted || _stopping) { return; } DisconnectionInfo disconnectionInfo = DisconnectionInfo.Create(DisconnectionType.ByServer, client, null); ((SubjectBase<DisconnectionInfo>)(object)_disconnectedSubject).OnNext(disconnectionInfo); if (disconnectionInfo.CancelClosing) { if (IsReconnectionEnabled) { throw new OperationCanceledException("Websocket connection was closed by server (client: " + Name + ")"); } continue; } await StopInternal(client, WebSocketCloseStatus.NormalClosure, "Closing", token, failFast: false, byServer: true); if (IsReconnectionEnabled && !ShouldIgnoreReconnection(client)) { ReconnectSynchronized(ReconnectionType.Lost, failFast: false, null); } return; } if (ms != null) { responseMessage = ResponseMessage.BinaryMessage(ms.ToArray()); } else { Array.Resize(ref resultArrayWithTrailing, resultArraySize); responseMessage = ResponseMessage.BinaryMessage(resultArrayWithTrailing); } } ms?.Dispose(); _logger.LogTrace(L("Received: {message}"), Name, responseMessage); _lastReceivedMsg = DateTime.UtcNow; ((SubjectBase<ResponseMessage>)(object)_messageReceivedSubject).OnNext(responseMessage); } while (client.State == WebSocketState.Open && !token.IsCancellationRequested); } catch (TaskCanceledException ex) { causedException = ex; } catch (OperationCanceledException ex2) { causedException = ex2; } catch (ObjectDisposedException ex3) { causedException = ex3; } catch (Exception ex4) { _logger.LogError(ex4, L("Error while listening to websocket stream, error: '{error}'"), Name, ex4.Message); causedException = ex4; } if (!ShouldIgnoreReconnection(client) && IsStarted) { if (LostReconnectTimeout.HasValue) { TimeSpan value = LostReconnectTimeout.Value; _logger.LogWarning(L("Listening websocket stream is lost. Waiting {timeout} sec before next reconnection try."), Name, value.TotalSeconds); await Task.Delay(value, token).ConfigureAwait(continueOnCapturedContext: false); } ReconnectSynchronized(ReconnectionType.Lost, failFast: false, causedException); } } private bool ShouldIgnoreReconnection(WebSocket client) { bool num = _disposing || _reconnecting || _stopping; bool flag = client != _client; return num || flag; } private Encoding GetEncoding() { if (MessageEncoding == null) { MessageEncoding = Encoding.UTF8; } return MessageEncoding; } private ClientWebSocket? GetSpecificOrThrow(WebSocket? client) { if (client == null) { return null; } return (client as ClientWebSocket) ?? throw new WebsocketException("Cannot cast 'WebSocket' client to 'ClientWebSocket', provide correct type via factory or don't use this property at all."); } private string L(string msg) { return "[WEBSOCKET {name}] " + msg; } private DisconnectionType TranslateTypeToDisconnection(ReconnectionType type) { return (DisconnectionType)type; } public Task Reconnect() { return ReconnectInternal(failFast: false); } public Task ReconnectOrFail() { return ReconnectInternal(failFast: true); } private async Task ReconnectInternal(bool failFast) { if (!IsStarted) { _logger.LogDebug(L("Client not started, ignoring reconnection.."), Name); return; } try { await ReconnectSynchronized(ReconnectionType.ByUser, failFast, null).ConfigureAwait(continueOnCapturedContext: false); } finally { _reconnecting = false; } } private async Task ReconnectSynchronized(ReconnectionType type, bool failFast, Exception? causedException) { using (await _locker.LockAsync()) { await Reconnect(type, failFast, causedException); } } private async Task Reconnect(ReconnectionType type, bool failFast, Exception? causedException) { IsRunning = false; if (_disposing || !IsStarted) { return; } _reconnecting = true; DisconnectionInfo disconnectionInfo = DisconnectionInfo.Create(TranslateTypeToDisconnection(type), _client, causedException); if (type != ReconnectionType.Error) { ((SubjectBase<DisconnectionInfo>)(object)_disconnectedSubject).OnNext(disconnectionInfo); if (disconnectionInfo.CancelReconnection) { _logger.LogInformation(L("Reconnecting canceled by user, exiting."), Name); } } _cancellation?.Cancel(); try { _client?.Abort(); } catch (Exception ex) { _logger.LogError(ex, L("Exception while aborting client. Error: '{error}'"), Name, ex.Message); } _client?.Dispose(); if (!IsReconnectionEnabled || disconnectionInfo.CancelReconnection) { IsStarted = false; _reconnecting = false; return; } _logger.LogDebug(L("Reconnecting..."), Name); _cancellation = new CancellationTokenSource(); await StartClient(_url, _cancellation.Token, type, failFast).ConfigureAwait(continueOnCapturedContext: false); _reconnecting = false; } private void ActivateLastChance() { int num = 1000; _lastChanceTimer = new Timer(LastChance, null, num, num); } private void DeactivateLastChance() { _lastChanceTimer?.Dispose(); _lastChanceTimer = null; } private void LastChance(object? state) { if (!IsReconnectionEnabled || !ReconnectTimeout.HasValue) { DeactivateLastChance(); return; } double num = Math.Abs(ReconnectTimeout.Value.TotalMilliseconds); if (Math.Abs(DateTime.UtcNow.Subtract(_lastReceivedMsg).TotalMilliseconds) > num) { _logger.LogDebug(L("Last message received more than {timeoutMs} ms ago. Hard restart.."), Name, num.ToString("F")); DeactivateLastChance(); ReconnectSynchronized(ReconnectionType.NoMessageReceived, failFast: false, null); } } public void Send(string message) { Websocket.Client.Validations.Validations.ValidateInput(message, "message"); _messagesTextToSendQueue.Writer.TryWrite(message); } public void Send(byte[] message) { Websocket.Client.Validations.Validations.ValidateInput(message, "message"); _messagesBinaryToSendQueue.Writer.TryWrite(new ArraySegment<byte>(message)); } public void Send(ArraySegment<byte> message) { Websocket.Client.Validations.Validations.ValidateInput(message, "message"); _messagesBinaryToSendQueue.Writer.TryWrite(message); } public Task SendInstant(string message) { Websocket.Client.Validations.Validations.ValidateInput(message, "message"); return SendInternalSynchronized(message); } public Task SendInstant(byte[] message) { return SendInternalSynchronized(new ArraySegment<byte>(message)); } public void StreamFakeMessage(ResponseMessage message) { Websocket.Client.Validations.Validations.ValidateInput(message, "message"); ((SubjectBase<ResponseMessage>)(object)_messageReceivedSubject).OnNext(message); } private async Task SendTextFromQueue() { _ = 1; try { while (await _messagesTextToSendQueue.Reader.WaitToReadAsync()) { string message; while (_messagesTextToSendQueue.Reader.TryRead(out message)) { try { await SendInternalSynchronized(message).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception ex) { _logger.LogError(ex, L("Failed to send text message: '{message}'. Error: {error}"), Name, message, ex.Message); } } } } catch (TaskCanceledException) { } catch (OperationCanceledException) { } catch (Exception ex4) { if (!(_cancellationTotal?.IsCancellationRequested ?? false) && !_disposing) { _logger.LogTrace(L("Sending text thread failed, error: {error}. Creating a new sending thread."), Name, ex4.Message); StartBackgroundThreadForSendingText(); } } } private async Task SendBinaryFromQueue() { _ = 1; try { while (await _messagesBinaryToSendQueue.Reader.WaitToReadAsync()) { ArraySegment<byte> message; while (_messagesBinaryToSendQueue.Reader.TryRead(out message)) { try { await SendInternalSynchronized(message).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception ex) { _logger.LogError(ex, L("Failed to send binary message: '{message}'. Error: {error}"), Name, message, ex.Message); } } } } catch (TaskCanceledException) { } catch (OperationCanceledException) { } catch (Exception ex4) { if (!(_cancellationTotal?.IsCancellationRequested ?? false) && !_disposing) { _logger.LogTrace(L("Sending binary thread failed, error: {error}. Creating a new sending thread."), Name, ex4.Message); StartBackgroundThreadForSendingBinary(); } } } private void StartBackgroundThreadForSendingText() { Task.Factory.StartNew((object _) => SendTextFromQueue(), TaskCreationOptions.LongRunning, _cancellationTotal?.Token ?? CancellationToken.None); } private void StartBackgroundThreadForSendingBinary() { Task.Factory.StartNew((object _) => SendBinaryFromQueue(), TaskCreationOptions.LongRunning, _cancellationTotal?.Token ?? CancellationToken.None); } private async Task SendInternalSynchronized(string message) { using (await _locker.LockAsync()) { await SendInternal(message); } } private async Task SendInternal(string message) { if (!IsClientConnected()) { _logger.LogDebug(L("Client is not connected to server, cannot send: {message}"), Name, message); return; } _logger.LogTrace(L("Sending: {message}"), Name, message); byte[] bytes = GetEncoding().GetBytes(message); ArraySegment<byte> buffer = new ArraySegment<byte>(bytes); await _client.SendAsync(buffer, WebSocketMessageType.Text, endOfMessage: true, _cancellation?.Token ?? CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } private async Task SendInternalSynchronized(ArraySegment<byte> message) { using (await _locker.LockAsync()) { await SendInternal(message); } } private async Task SendInternal(ArraySegment<byte> message) { if (!IsClientConnected()) { _logger.LogDebug(L("Client is not connected to server, cannot send binary, length: {length}"), Name, message.Count); } else { _logger.LogTrace(L("Sending binary, length: {length}"), Name, message.Count); await _client.SendAsync(message, WebSocketMessageType.Binary, endOfMessage: true, _cancellation?.Token ?? CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } } } } namespace Websocket.Client.Validations { internal static class Validations { public static void ValidateInput(string value, string name) { if (string.IsNullOrEmpty(value)) { throw new WebsocketBadInputException("Input string parameter '" + name + "' is null or empty. Please correct it."); } } public static void ValidateInput<T>(T value, string name) { if (object.Equals(value, default(T))) { throw new WebsocketBadInputException("Input parameter '" + name + "' is null. Please correct it."); } } public static void ValidateInputCollection<T>(IEnumerable<T> collection, string name) { ValidateInput(collection, name); if (!collection.Any()) { throw new WebsocketBadInputException("Input collection '" + name + "' is empty. Please correct it."); } } public static void ValidateInput(int value, string name, int minValue = int.MinValue, int maxValue = int.MaxValue) { if (value < minValue) { throw new WebsocketBadInputException($"Input parameter '{name}' is lower than {minValue}. Please correct it."); } if (value > maxValue) { throw new WebsocketBadInputException($"Input parameter '{name}' is higher than {maxValue}. Please correct it."); } } public static void ValidateInput(long value, string name, long minValue = long.MinValue, long maxValue = long.MaxValue) { if (value < minValue) { throw new WebsocketBadInputException($"Input parameter '{name}' is lower than {minValue}. Please correct it."); } if (value > maxValue) { throw new WebsocketBadInputException($"Input parameter '{name}' is higher than {maxValue}. Please correct it."); } } public static void ValidateInput(double value, string name, double minValue = double.MinValue, double maxValue = double.MaxValue) { if (value < minValue) { throw new WebsocketBadInputException($"Input parameter '{name}' is lower than {minValue}. Please correct it."); } if (value > maxValue) { throw new WebsocketBadInputException($"Input parameter '{name}' is higher than {maxValue}. Please correct it."); } } } } namespace Websocket.Client.Threading { public class WebsocketAsyncLock { private class Releaser : IDisposable { private readonly SemaphoreSlim _semaphore; public Releaser(SemaphoreSlim semaphore) { _semaphore = semaphore; } public void Dispose() { _semaphore.Release(); } } private readonly Task<IDisposable> _releaserTask; private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); private readonly IDisposable _releaser; public WebsocketAsyncLock() { _releaser = new Releaser(_semaphore); _releaserTask = Task.FromResult(_releaser); } public IDisposable Lock() { _semaphore.Wait(); return _releaser; } public Task<IDisposable> LockAsync() { Task task = _semaphore.WaitAsync(); if (!task.IsCompleted) { return task.ContinueWith((Task _, object releaser) => (IDisposable)releaser, _releaser, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } return _releaserTask; } } } namespace Websocket.Client.Exceptions { public class WebsocketBadInputException : WebsocketException { public WebsocketBadInputException() { } public WebsocketBadInputException(string message) : base(message) { } public WebsocketBadInputException(string message, Exception innerException) : base(message, innerException) { } } public class WebsocketException : Exception { public WebsocketException() { } public WebsocketException(string message) : base(message) { } public WebsocketException(string message, Exception innerException) : base(message, innerException) { } } }