Decompiled source of TwitchChat v1.1.1
plugins/Microsoft.Extensions.DependencyInjection.Abstractions.dll
Decompiled 2 hours 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.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.DependencyInjection.Abstractions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Abstractions for dependency injection.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.DependencyInjection.IServiceCollection")] [assembly: AssemblyFileVersion("8.0.1024.46610")] [assembly: AssemblyInformationalVersion("8.0.10+81cabf2857a01351e5ab578947c7403a5b128ad1")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("8.0.0.0")] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.DependencyInjection.Abstractions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } private static void Throw(string paramName) { throw new ArgumentNullException(paramName); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "") { if (argument == null) { throw new ArgumentNullException(paramName); } if (string.IsNullOrWhiteSpace(argument)) { if (argument == null) { throw new ArgumentNullException(paramName); } throw new ArgumentException(paramName, "Argument is whitespace"); } return argument; } } internal static class SR { private static readonly bool s_usingResourceKeys = 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 AmbiguousConstructorMatch => GetResourceString("AmbiguousConstructorMatch"); internal static string CannotResolveService => GetResourceString("CannotResolveService"); internal static string NoConstructorMatch => GetResourceString("NoConstructorMatch"); internal static string NoServiceRegistered => GetResourceString("NoServiceRegistered"); internal static string ServiceCollectionReadOnly => GetResourceString("ServiceCollectionReadOnly"); internal static string TryAddIndistinguishableTypeToEnumerable => GetResourceString("TryAddIndistinguishableTypeToEnumerable"); internal static string MultipleCtorsMarkedWithAttribute => GetResourceString("MultipleCtorsMarkedWithAttribute"); internal static string MarkedCtorMissingArgumentTypes => GetResourceString("MarkedCtorMissingArgumentTypes"); internal static string CannotCreateAbstractClasses => GetResourceString("CannotCreateAbstractClasses"); internal static string MultipleCtorsFoundWithBestLength => GetResourceString("MultipleCtorsFoundWithBestLength"); internal static string UnableToResolveService => GetResourceString("UnableToResolveService"); internal static string CtorNotLocated => GetResourceString("CtorNotLocated"); internal static string MultipleCtorsFound => GetResourceString("MultipleCtorsFound"); internal static string KeyedServicesNotSupported => GetResourceString("KeyedServicesNotSupported"); internal static string NonKeyedDescriptorMisuse => GetResourceString("NonKeyedDescriptorMisuse"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string? Scope { get; set; } public string? Target { get; set; } public string? MessageId { get; set; } public string? Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } } namespace Microsoft.Extensions.Internal { internal static class ParameterDefaultValue { public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue) { bool tryToGetDefaultValue; bool flag = CheckHasDefaultValue(parameter, out tryToGetDefaultValue); defaultValue = null; if (flag) { if (tryToGetDefaultValue) { defaultValue = parameter.DefaultValue; } bool flag2 = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>); if (defaultValue == null && parameter.ParameterType.IsValueType && !flag2) { defaultValue = CreateValueType(parameter.ParameterType); } if (defaultValue != null && flag2) { Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType); if (underlyingType != null && underlyingType.IsEnum) { defaultValue = Enum.ToObject(underlyingType, defaultValue); } } } return flag; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")] static object? CreateValueType(Type t) { return RuntimeHelpers.GetUninitializedObject(t); } } public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue) { tryToGetDefaultValue = true; try { return parameter.HasDefaultValue; } catch (FormatException) when (parameter.ParameterType == typeof(DateTime)) { tryToGetDefaultValue = false; return true; } } } } namespace Microsoft.Extensions.DependencyInjection { public static class ActivatorUtilities { private readonly struct FactoryParameterContext { public Type ParameterType { get; } public bool HasDefaultValue { get; } public object DefaultValue { get; } public int ArgumentIndex { get; } public object ServiceKey { get; } public FactoryParameterContext(Type parameterType, bool hasDefaultValue, object defaultValue, int argumentIndex, object serviceKey) { ParameterType = parameterType; HasDefaultValue = hasDefaultValue; DefaultValue = defaultValue; ArgumentIndex = argumentIndex; ServiceKey = serviceKey; } } private sealed class ConstructorInfoEx { public readonly ConstructorInfo Info; public readonly ParameterInfo[] Parameters; public readonly bool IsPreferred; private readonly object[] _parameterKeys; public ConstructorInfoEx(ConstructorInfo constructor) { Info = constructor; Parameters = constructor.GetParameters(); IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false); for (int i = 0; i < Parameters.Length; i++) { FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false); if (fromKeyedServicesAttribute != null) { if (_parameterKeys == null) { _parameterKeys = new object[Parameters.Length]; } _parameterKeys[i] = fromKeyedServicesAttribute.Key; } } } public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex) { ParameterInfo parameterInfo = Parameters[parameterIndex]; object[] parameterKeys = _parameterKeys; object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null); if (obj != null) { if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService) { return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, obj); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } return serviceProviderIsService.IsService(parameterInfo.ParameterType); } public object GetService(IServiceProvider serviceProvider, int parameterIndex) { ParameterInfo parameterInfo = Parameters[parameterIndex]; object[] parameterKeys = _parameterKeys; object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null); if (obj != null) { if (serviceProvider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, obj); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } return serviceProvider.GetService(parameterInfo.ParameterType); } } private readonly struct ConstructorMatcher { private readonly ConstructorInfoEx _constructor; private readonly object[] _parameterValues; public ConstructorMatcher(ConstructorInfoEx constructor) { _constructor = constructor; _parameterValues = new object[constructor.Parameters.Length]; } public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService) { for (int i = 0; i < givenParameters.Length; i++) { Type c = givenParameters[i]?.GetType(); bool flag = false; for (int j = 0; j < _constructor.Parameters.Length; j++) { if (_parameterValues[j] == null && _constructor.Parameters[j].ParameterType.IsAssignableFrom(c)) { flag = true; _parameterValues[j] = givenParameters[i]; break; } } if (!flag) { return -1; } } for (int k = 0; k < _constructor.Parameters.Length; k++) { if (_parameterValues[k] == null && !_constructor.IsService(serviceProviderIsService, k)) { if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[k], out object defaultValue)) { return -1; } _parameterValues[k] = defaultValue; } } return _constructor.Parameters.Length; } public object CreateInstance(IServiceProvider provider) { for (int i = 0; i < _constructor.Parameters.Length; i++) { if (_parameterValues[i] != null) { continue; } object service = _constructor.GetService(provider, i); if (service == null) { if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object defaultValue)) { throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, _constructor.Parameters[i].ParameterType, _constructor.Info.DeclaringType)); } _parameterValues[i] = defaultValue; } else { _parameterValues[i] = service; } } return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, null, _parameterValues, null); } public void MapParameters(int?[] parameterMap, object[] givenParameters) { for (int i = 0; i < _constructor.Parameters.Length; i++) { if (parameterMap[i].HasValue) { _parameterValues[i] = givenParameters[parameterMap[i].Value]; } } } } private static readonly MethodInfo GetServiceInfo = GetMethodInfo<Func<IServiceProvider, Type, Type, bool, object, object>>((IServiceProvider sp, Type t, Type r, bool c, object k) => GetService(sp, t, r, c, k)); public static object CreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, params object[] parameters) { if (provider == null) { throw new ArgumentNullException("provider"); } if (instanceType.IsAbstract) { throw new InvalidOperationException(System.SR.CannotCreateAbstractClasses); } ConstructorInfoEx[] array = CreateConstructorInfoExs(instanceType); IServiceProviderIsService service = provider.GetService<IServiceProviderIsService>(); ConstructorInfoEx constructorInfoEx; if (service != null) { int num = -1; bool flag = false; ConstructorMatcher constructorMatcher = default(ConstructorMatcher); bool flag2 = false; for (int i = 0; i < array.Length; i++) { constructorInfoEx = array[i]; ConstructorMatcher constructorMatcher2 = new ConstructorMatcher(constructorInfoEx); bool isPreferred = constructorInfoEx.IsPreferred; int num2 = constructorMatcher2.Match(parameters, service); if (isPreferred) { if (flag) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (num2 == -1) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } } if (isPreferred || num < num2) { num = num2; constructorMatcher = constructorMatcher2; flag2 = false; } else if (num == num2) { flag2 = true; } flag = flag || isPreferred; } if (num != -1) { if (flag2) { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFoundWithBestLength, instanceType, num)); } return constructorMatcher.CreateInstance(provider); } } Type[] array2; if (parameters.Length == 0) { array2 = Type.EmptyTypes; } else { array2 = new Type[parameters.Length]; for (int j = 0; j < array2.Length; j++) { array2[j] = parameters[j]?.GetType(); } } FindApplicableConstructor(instanceType, array2, out var matchingConstructor, out var matchingParameterMap); constructorInfoEx = null; ConstructorInfoEx[] array3 = array; foreach (ConstructorInfoEx constructorInfoEx2 in array3) { if ((object)constructorInfoEx2.Info == matchingConstructor) { constructorInfoEx = constructorInfoEx2; break; } } ConstructorMatcher constructorMatcher3 = new ConstructorMatcher(constructorInfoEx); constructorMatcher3.MapParameters(matchingParameterMap, parameters); return constructorMatcher3.CreateInstance(provider); } private static ConstructorInfoEx[] CreateConstructorInfoExs([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { ConstructorInfo[] constructors = type.GetConstructors(); ConstructorInfoEx[] array = new ConstructorInfoEx[constructors.Length]; for (int i = 0; i < constructors.Length; i++) { array[i] = new ConstructorInfoEx(constructors[i]); } return array; } public static ObjectFactory CreateFactory([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes) { if (!RuntimeFeature.IsDynamicCodeCompiled) { return CreateFactoryReflection(instanceType, argumentTypes); } CreateFactoryInternal(instanceType, argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody); Expression<Func<IServiceProvider, object[], object>> expression = Expression.Lambda<Func<IServiceProvider, object[], object>>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }); Func<IServiceProvider, object[], object> @object = expression.Compile(); return @object.Invoke; } public static ObjectFactory<T> CreateFactory<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(Type[] argumentTypes) { if (!RuntimeFeature.IsDynamicCodeCompiled) { ObjectFactory factory = CreateFactoryReflection(typeof(T), argumentTypes); return (IServiceProvider serviceProvider, object[] arguments) => (T)factory(serviceProvider, arguments); } CreateFactoryInternal(typeof(T), argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody); Expression<Func<IServiceProvider, object[], T>> expression = Expression.Lambda<Func<IServiceProvider, object[], T>>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }); Func<IServiceProvider, object[], T> @object = expression.Compile(); return @object.Invoke; } private static void CreateFactoryInternal([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ParameterExpression provider, out ParameterExpression argumentArray, out Expression factoryExpressionBody) { FindApplicableConstructor(instanceType, argumentTypes, out var matchingConstructor, out var matchingParameterMap); provider = Expression.Parameter(typeof(IServiceProvider), "provider"); argumentArray = Expression.Parameter(typeof(object[]), "argumentArray"); factoryExpressionBody = BuildFactoryExpression(matchingConstructor, matchingParameterMap, provider, argumentArray); } public static T CreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider, params object[] parameters) { return (T)CreateInstance(provider, typeof(T), parameters); } public static T GetServiceOrCreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider) { return (T)GetServiceOrCreateInstance(provider, typeof(T)); } public static object GetServiceOrCreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { return provider.GetService(type) ?? CreateInstance(provider, type); } private static MethodInfo GetMethodInfo<T>(Expression<T> expr) { MethodCallExpression methodCallExpression = (MethodCallExpression)expr.Body; return methodCallExpression.Method; } private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool hasDefaultValue, object key) { object obj = ((key == null) ? sp.GetService(type) : GetKeyedService(sp, type, key)); if (obj == null && !hasDefaultValue) { ThrowHelperUnableToResolveService(type, requiredBy); } return obj; } [DoesNotReturn] private static void ThrowHelperUnableToResolveService(Type type, Type requiredBy) { throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, type, requiredBy)); } private static BlockExpression BuildFactoryExpression(ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, Expression factoryArgumentArray) { ParameterInfo[] parameters = constructor.GetParameters(); Expression[] array = new Expression[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameterInfo = parameters[i]; Type parameterType = parameterInfo.ParameterType; object defaultValue; bool flag = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue); if (parameterMap[i].HasValue) { array[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i])); } else { FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false); Expression[] arguments = new Expression[5] { serviceProvider, Expression.Constant(parameterType, typeof(Type)), Expression.Constant(constructor.DeclaringType, typeof(Type)), Expression.Constant(flag), Expression.Constant(fromKeyedServicesAttribute?.Key) }; array[i] = Expression.Call(GetServiceInfo, arguments); } if (flag) { ConstantExpression right = Expression.Constant(defaultValue); array[i] = Expression.Coalesce(array[i], right); } array[i] = Expression.Convert(array[i], parameterType); } return Expression.Block(Expression.IfThen(Expression.Equal(serviceProvider, Expression.Constant(null)), Expression.Throw(Expression.Constant(new ArgumentNullException("serviceProvider")))), Expression.New(constructor, array)); } [DoesNotReturn] private static void ThrowHelperArgumentNullExceptionServiceProvider() { throw new ArgumentNullException("serviceProvider"); } private static ObjectFactory CreateFactoryReflection([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes) { FindApplicableConstructor(instanceType, argumentTypes, out var constructor, out var parameterMap); Type declaringType = constructor.DeclaringType; ParameterInfo[] constructorParameters = constructor.GetParameters(); if (constructorParameters.Length == 0) { return (IServiceProvider serviceProvider, object[] arguments) => constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, null, null); } FactoryParameterContext[] parameters = GetFactoryParameterContext(); return (IServiceProvider serviceProvider, object[] arguments) => ReflectionFactoryCanonical(constructor, parameters, declaringType, serviceProvider, arguments); FactoryParameterContext[] GetFactoryParameterContext() { FactoryParameterContext[] array = new FactoryParameterContext[constructorParameters.Length]; for (int i = 0; i < constructorParameters.Length; i++) { ParameterInfo parameterInfo = constructorParameters[i]; FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false); object defaultValue; bool hasDefaultValue = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue); array[i] = new FactoryParameterContext(parameterInfo.ParameterType, hasDefaultValue, defaultValue, parameterMap[i] ?? (-1), fromKeyedServicesAttribute?.Key); } return array; } } private static void FindApplicableConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out int?[] matchingParameterMap) { if (!TryFindPreferredConstructor(instanceType, argumentTypes, out var matchingConstructor2, out var parameterMap) && !TryFindMatchingConstructor(instanceType, argumentTypes, out matchingConstructor2, out parameterMap)) { throw new InvalidOperationException(System.SR.Format(System.SR.CtorNotLocated, instanceType)); } matchingConstructor = matchingConstructor2; matchingParameterMap = parameterMap; } private static bool TryFindMatchingConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap) { matchingConstructor = null; parameterMap = null; ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo constructorInfo in constructors) { if (TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2)) { if (matchingConstructor != null) { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFound, instanceType)); } matchingConstructor = constructorInfo; parameterMap = parameterMap2; } } if (matchingConstructor != null) { return true; } return false; } private static bool TryFindPreferredConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap) { bool flag = false; matchingConstructor = null; parameterMap = null; ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo constructorInfo in constructors) { if (constructorInfo.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false)) { if (flag) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (!TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2)) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } matchingConstructor = constructorInfo; parameterMap = parameterMap2; flag = true; } } if (matchingConstructor != null) { return true; } return false; } private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap) { parameterMap = new int?[constructorParameters.Length]; for (int i = 0; i < argumentTypes.Length; i++) { bool flag = false; Type c = argumentTypes[i]; for (int j = 0; j < constructorParameters.Length; j++) { if (!parameterMap[j].HasValue && constructorParameters[j].ParameterType.IsAssignableFrom(c)) { flag = true; parameterMap[j] = i; break; } } if (!flag) { return false; } } return true; } private static void ThrowMultipleCtorsMarkedWithAttributeException() { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsMarkedWithAttribute, "ActivatorUtilitiesConstructorAttribute")); } private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments() { throw new InvalidOperationException(System.SR.Format(System.SR.MarkedCtorMissingArgumentTypes, "ActivatorUtilitiesConstructorAttribute")); } private static object ReflectionFactoryCanonical(ConstructorInfo constructor, FactoryParameterContext[] parameters, Type declaringType, IServiceProvider serviceProvider, object[] arguments) { if (serviceProvider == null) { ThrowHelperArgumentNullExceptionServiceProvider(); } object[] array = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ref FactoryParameterContext reference = ref parameters[i]; array[i] = ((reference.ArgumentIndex != -1) ? arguments[reference.ArgumentIndex] : GetService(serviceProvider, reference.ParameterType, declaringType, reference.HasDefaultValue, reference.ServiceKey)) ?? reference.DefaultValue; } return constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, array, null); } private static object GetKeyedService(IServiceProvider provider, Type type, object serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetKeyedService(type, serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } } [AttributeUsage(AttributeTargets.All)] public class ActivatorUtilitiesConstructorAttribute : Attribute { } [DebuggerDisplay("{ServiceProvider,nq}")] public readonly struct AsyncServiceScope : IServiceScope, IDisposable, IAsyncDisposable { private readonly IServiceScope _serviceScope; public IServiceProvider ServiceProvider => _serviceScope.ServiceProvider; public AsyncServiceScope(IServiceScope serviceScope) { System.ThrowHelper.ThrowIfNull(serviceScope, "serviceScope"); _serviceScope = serviceScope; } public void Dispose() { _serviceScope.Dispose(); } public ValueTask DisposeAsync() { if (_serviceScope is IAsyncDisposable asyncDisposable) { return asyncDisposable.DisposeAsync(); } _serviceScope.Dispose(); return default(ValueTask); } } [AttributeUsage(AttributeTargets.Parameter)] public class FromKeyedServicesAttribute : Attribute { public object Key { get; } public FromKeyedServicesAttribute(object key) { Key = key; } } public interface IKeyedServiceProvider : IServiceProvider { object? GetKeyedService(Type serviceType, object? serviceKey); object GetRequiredKeyedService(Type serviceType, object? serviceKey); } public static class KeyedService { private sealed class AnyKeyObj { public override string ToString() { return "*"; } } public static object AnyKey { get; } = new AnyKeyObj(); } public interface IServiceCollection : IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable { } public interface IServiceProviderFactory<TContainerBuilder> where TContainerBuilder : notnull { TContainerBuilder CreateBuilder(IServiceCollection services); IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder); } public interface IServiceProviderIsKeyedService : IServiceProviderIsService { bool IsKeyedService(Type serviceType, object? serviceKey); } public interface IServiceProviderIsService { bool IsService(Type serviceType); } public interface IServiceScope : IDisposable { IServiceProvider ServiceProvider { get; } } public interface IServiceScopeFactory { IServiceScope CreateScope(); } public interface ISupportRequiredService { object GetRequiredService(Type serviceType); } public delegate object ObjectFactory(IServiceProvider serviceProvider, object?[]? arguments); public delegate T ObjectFactory<T>(IServiceProvider serviceProvider, object?[]? arguments); [DebuggerDisplay("{DebuggerToString(),nq}")] [DebuggerTypeProxy(typeof(ServiceCollectionDebugView))] public class ServiceCollection : IServiceCollection, IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable { private sealed class ServiceCollectionDebugView { private readonly ServiceCollection _services; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public ServiceDescriptor[] Items { get { ServiceDescriptor[] array = new ServiceDescriptor[_services.Count]; _services.CopyTo(array, 0); return array; } } public ServiceCollectionDebugView(ServiceCollection services) { _services = services; } } private readonly List<ServiceDescriptor> _descriptors = new List<ServiceDescriptor>(); private bool _isReadOnly; public int Count => _descriptors.Count; public bool IsReadOnly => _isReadOnly; public ServiceDescriptor this[int index] { get { return _descriptors[index]; } set { CheckReadOnly(); _descriptors[index] = value; } } public void Clear() { CheckReadOnly(); _descriptors.Clear(); } public bool Contains(ServiceDescriptor item) { return _descriptors.Contains(item); } public void CopyTo(ServiceDescriptor[] array, int arrayIndex) { _descriptors.CopyTo(array, arrayIndex); } public bool Remove(ServiceDescriptor item) { CheckReadOnly(); return _descriptors.Remove(item); } public IEnumerator<ServiceDescriptor> GetEnumerator() { return _descriptors.GetEnumerator(); } void ICollection<ServiceDescriptor>.Add(ServiceDescriptor item) { CheckReadOnly(); _descriptors.Add(item); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int IndexOf(ServiceDescriptor item) { return _descriptors.IndexOf(item); } public void Insert(int index, ServiceDescriptor item) { CheckReadOnly(); _descriptors.Insert(index, item); } public void RemoveAt(int index) { CheckReadOnly(); _descriptors.RemoveAt(index); } public void MakeReadOnly() { _isReadOnly = true; } private void CheckReadOnly() { if (_isReadOnly) { ThrowReadOnlyException(); } } private static void ThrowReadOnlyException() { throw new InvalidOperationException(System.SR.ServiceCollectionReadOnly); } private string DebuggerToString() { string text = $"Count = {_descriptors.Count}"; if (_isReadOnly) { text += ", IsReadOnly = true"; } return text; } } public static class ServiceCollectionServiceExtensions { public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Transient); } public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient); } public static IServiceCollection AddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddTransient(serviceType, serviceType); } public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService)); } public static IServiceCollection AddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), implementationFactory); } public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), implementationFactory); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddScoped(serviceType, serviceType); } public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService)); } public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), implementationFactory); } public static IServiceCollection AddScoped<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddSingleton(serviceType, serviceType); } public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService)); } public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, object implementationInstance) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationInstance); services.Add(item); return services; } public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return services.AddSingleton(typeof(TService), implementationInstance); } private static IServiceCollection Add(IServiceCollection collection, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationType, lifetime); collection.Add(item); return collection; } private static IServiceCollection Add(IServiceCollection collection, Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationFactory, lifetime); collection.Add(item); return collection; } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Transient); } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Transient); } public static IServiceCollection AddKeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation)); } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddKeyedTransient(serviceType, serviceKey, serviceType); } public static IServiceCollection AddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedTransient(typeof(TService), serviceKey); } public static IServiceCollection AddKeyedTransient<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedTransient<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Scoped); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static IServiceCollection AddKeyedScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedScoped(typeof(TService), serviceKey, typeof(TImplementation)); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddKeyedScoped(serviceType, serviceKey, serviceType); } public static IServiceCollection AddKeyedScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedScoped(typeof(TService), serviceKey); } public static IServiceCollection AddKeyedScoped<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedScoped<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Singleton); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static IServiceCollection AddKeyedSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TImplementation)); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddKeyedSingleton(serviceType, serviceKey, serviceType); } public static IServiceCollection AddKeyedSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TService)); } public static IServiceCollection AddKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, object implementationInstance) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationInstance); services.Add(item); return services; } public static IServiceCollection AddKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationInstance); } private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime); collection.Add(item); return collection; } private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, Func<IServiceProvider, object, object> implementationFactory, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime); collection.Add(item); return collection; } } [DebuggerDisplay("{DebuggerToString(),nq}")] public class ServiceDescriptor { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] private Type _implementationType; private object _implementationInstance; private object _implementationFactory; public ServiceLifetime Lifetime { get; } public object? ServiceKey { get; } public Type ServiceType { get; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] public Type? ImplementationType { get { if (!IsKeyedService) { return _implementationType; } return null; } } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] public Type? KeyedImplementationType { get { if (!IsKeyedService) { ThrowNonKeyedDescriptor(); } return _implementationType; } } public object? ImplementationInstance { get { if (!IsKeyedService) { return _implementationInstance; } return null; } } public object? KeyedImplementationInstance { get { if (!IsKeyedService) { ThrowNonKeyedDescriptor(); } return _implementationInstance; } } public Func<IServiceProvider, object>? ImplementationFactory { get { if (!IsKeyedService) { return (Func<IServiceProvider, object>)_implementationFactory; } return null; } } public Func<IServiceProvider, object?, object>? KeyedImplementationFactory { get { if (!IsKeyedService) { ThrowNonKeyedDescriptor(); } return (Func<IServiceProvider, object, object>)_implementationFactory; } } public bool IsKeyedService => ServiceKey != null; public ServiceDescriptor(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) : this(serviceType, null, implementationType, lifetime) { } public ServiceDescriptor(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) : this(serviceType, serviceKey, lifetime) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); _implementationType = implementationType; } public ServiceDescriptor(Type serviceType, object instance) : this(serviceType, null, instance) { } public ServiceDescriptor(Type serviceType, object? serviceKey, object instance) : this(serviceType, serviceKey, ServiceLifetime.Singleton) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(instance, "instance"); _implementationInstance = instance; } public ServiceDescriptor(Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime) : this(serviceType, (object)null, lifetime) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(factory, "factory"); _implementationFactory = factory; } public ServiceDescriptor(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> factory, ServiceLifetime lifetime) { Func<IServiceProvider, object, object> factory2 = factory; this..ctor(serviceType, serviceKey, lifetime); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(factory2, "factory"); if (serviceKey == null) { Func<IServiceProvider, object> implementationFactory = (IServiceProvider sp) => factory2(sp, null); _implementationFactory = implementationFactory; } else { _implementationFactory = factory2; } } private ServiceDescriptor(Type serviceType, object serviceKey, ServiceLifetime lifetime) { Lifetime = lifetime; ServiceType = serviceType; ServiceKey = serviceKey; } public override string ToString() { string text = string.Format("{0}: {1} {2}: {3} ", "ServiceType", ServiceType, "Lifetime", Lifetime); if (IsKeyedService) { text += string.Format("{0}: {1} ", "ServiceKey", ServiceKey); if (KeyedImplementationType != null) { return text + string.Format("{0}: {1}", "KeyedImplementationType", KeyedImplementationType); } if (KeyedImplementationFactory != null) { return text + string.Format("{0}: {1}", "KeyedImplementationFactory", KeyedImplementationFactory.Method); } return text + string.Format("{0}: {1}", "KeyedImplementationInstance", KeyedImplementationInstance); } if (ImplementationType != null) { return text + string.Format("{0}: {1}", "ImplementationType", ImplementationType); } if (ImplementationFactory != null) { return text + string.Format("{0}: {1}", "ImplementationFactory", ImplementationFactory.Method); } return text + string.Format("{0}: {1}", "ImplementationInstance", ImplementationInstance); } internal Type GetImplementationType() { if (ServiceKey == null) { if (ImplementationType != null) { return ImplementationType; } if (ImplementationInstance != null) { return ImplementationInstance.GetType(); } if (ImplementationFactory != null) { Type[] genericTypeArguments = ImplementationFactory.GetType().GenericTypeArguments; return genericTypeArguments[1]; } } else { if (KeyedImplementationType != null) { return KeyedImplementationType; } if (KeyedImplementationInstance != null) { return KeyedImplementationInstance.GetType(); } if (KeyedImplementationFactory != null) { Type[] genericTypeArguments2 = KeyedImplementationFactory.GetType().GenericTypeArguments; return genericTypeArguments2[2]; } } return null; } public static ServiceDescriptor Transient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Transient); } public static ServiceDescriptor Transient<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Scoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { return Describe(service, implementationType, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Singleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return Singleton(typeof(TService), implementationInstance); } public static ServiceDescriptor KeyedSingleton<TService>(object? serviceKey, TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return KeyedSingleton(typeof(TService), serviceKey, implementationInstance); } public static ServiceDescriptor Singleton(Type serviceType, object implementationInstance) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return new ServiceDescriptor(serviceType, implementationInstance); } public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, object implementationInstance) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return new ServiceDescriptor(serviceType, serviceKey, implementationInstance); } private static ServiceDescriptor DescribeKeyed<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object serviceKey, ServiceLifetime lifetime) where TService : class where TImplementation : class, TService { return DescribeKeyed(typeof(TService), serviceKey, typeof(TImplementation), lifetime); } public static ServiceDescriptor Describe(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, implementationType, lifetime); } public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime); } public static ServiceDescriptor Describe(Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, implementationFactory, lifetime); } public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime); } private string DebuggerToString() { string text = $"Lifetime = {Lifetime}, ServiceType = \"{ServiceType.FullName}\""; if (IsKeyedService) { text += $", ServiceKey = \"{ServiceKey}\""; if (KeyedImplementationType != null) { return text + ", KeyedImplementationType = \"" + KeyedImplementationType.FullName + "\""; } if (KeyedImplementationFactory != null) { return text + $", KeyedImplementationFactory = {KeyedImplementationFactory.Method}"; } return text + $", KeyedImplementationInstance = {KeyedImplementationInstance}"; } if (ImplementationType != null) { return text + ", ImplementationType = \"" + ImplementationType.FullName + "\""; } if (ImplementationFactory != null) { return text + $", ImplementationFactory = {ImplementationFactory.Method}"; } return text + $", ImplementationInstance = {ImplementationInstance}"; } private static void ThrowNonKeyedDescriptor() { throw new InvalidOperationException(System.SR.NonKeyedDescriptorMisuse); } } [AttributeUsage(AttributeTargets.Parameter)] public class ServiceKeyAttribute : Attribute { } public enum ServiceLifetime { Singleton, Scoped, Transient } public static class ServiceProviderKeyedServiceExtensions { public static T? GetKeyedService<T>(this IServiceProvider provider, object? serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return (T)keyedServiceProvider.GetKeyedService(typeof(T), serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static object GetRequiredKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetRequiredKeyedService(serviceType, serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static T GetRequiredKeyedService<T>(this IServiceProvider provider, object? serviceKey) where T : notnull { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredKeyedService(typeof(T), serviceKey); } public static IEnumerable<T> GetKeyedServices<T>(this IServiceProvider provider, object? serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return provider.GetRequiredKeyedService<IEnumerable<T>>(serviceKey); } [RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")] public static IEnumerable<object?> GetKeyedServices(this IServiceProvider provider, Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable<object>)provider.GetRequiredKeyedService(serviceType2, serviceKey); } } public static class ServiceProviderServiceExtensions { public static T? GetService<T>(this IServiceProvider provider) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetService(typeof(T)); } public static object GetRequiredService(this IServiceProvider provider, Type serviceType) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); if (provider is ISupportRequiredService supportRequiredService) { return supportRequiredService.GetRequiredService(serviceType); } object service = provider.GetService(serviceType); if (service == null) { throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType)); } return service; } public static T GetRequiredService<T>(this IServiceProvider provider) where T : notnull { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredService(typeof(T)); } public static IEnumerable<T> GetServices<T>(this IServiceProvider provider) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return provider.GetRequiredService<IEnumerable<T>>(); } [RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")] public static IEnumerable<object?> GetServices(this IServiceProvider provider, Type serviceType) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable<object>)provider.GetRequiredService(serviceType2); } public static IServiceScope CreateScope(this IServiceProvider provider) { return provider.GetRequiredService<IServiceScopeFactory>().CreateScope(); } public static AsyncServiceScope CreateAsyncScope(this IServiceProvider provider) { return new AsyncServiceScope(provider.CreateScope()); } public static AsyncServiceScope CreateAsyncScope(this IServiceScopeFactory serviceScopeFactory) { return new AsyncServiceScope(serviceScopeFactory.CreateScope()); } } } namespace Microsoft.Extensions.DependencyInjection.Extensions { public static class ServiceCollectionDescriptorExtensions { public static IServiceCollection Add(this IServiceCollection collection, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); collection.Add(descriptor); return collection; } public static IServiceCollection Add(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.Add(descriptor); } return collection; } public static void TryAdd(this IServiceCollection collection, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); int count = collection.Count; for (int i = 0; i < count; i++) { if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey)) { return; } } collection.Add(descriptor); } public static void TryAdd(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.TryAdd(descriptor); } } public static void TryAddTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, service); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TService)); } public static void TryAddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TImplementation)); } public static void TryAddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Transient(implementationFactory)); } public static void TryAddScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, service); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TService)); } public static void TryAddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TImplementation)); } public static void TryAddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Scoped(implementationFactory)); } public static void TryAddSingleton(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, service); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TService)); } public static void TryAddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TImplementation)); } public static void TryAddSingleton<TService>(this IServiceCollection collection, TService instance) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(instance, "instance"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(typeof(TService), instance); collection.TryAdd(descriptor); } public static void TryAddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Singleton(implementationFactory)); } public static void TryAddEnumerable(this IServiceCollection services, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); Type implementationType = descriptor.GetImplementationType(); if (implementationType == typeof(object) || implementationType == descriptor.ServiceType) { throw new ArgumentException(System.SR.Format(System.SR.TryAddIndistinguishableTypeToEnumerable, implementationType, descriptor.ServiceType), "descriptor"); } int count = services.Count; for (int i = 0; i < count; i++) { ServiceDescriptor serviceDescriptor = services[i]; if (serviceDescriptor.ServiceType == descriptor.ServiceType && serviceDescriptor.GetImplementationType() == implementationType && object.Equals(serviceDescriptor.ServiceKey, descriptor.ServiceKey)) { return; } } services.Add(descriptor); } public static void TryAddEnumerable(this IServiceCollection services, IEnumerable<ServiceDescriptor> descriptors) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { services.TryAddEnumerable(descriptor); } } public static IServiceCollection Replace(this IServiceCollection collection, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); int count = collection.Count; for (int i = 0; i < count; i++) { if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey)) { collection.RemoveAt(i); break; } } collection.Add(descriptor); return collection; } public static IServiceCollection RemoveAll<T>(this IServiceCollection collection) { return collection.RemoveAll(typeof(T)); } public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); for (int num = collection.Count - 1; num >= 0; num--) { ServiceDescriptor serviceDescriptor = collection[num]; if (serviceDescriptor.ServiceType == serviceType && serviceDescriptor.ServiceKey == null) { collection.RemoveAt(num); } } return collection; } public static void TryAddKeyedTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, service); collection.TryAdd(descriptor); } public static void TryAddKeyedTransient(this IServiceCollection collection, Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationType); collection.TryAdd(descriptor); } public static void TryAddKeyedTransient(this IServiceCollection collection, Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection, object? serviceKey) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddKeyedTransient(typeof(TService), serviceKey, typeof(TService)); } public static void TryAddKeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection, object? serviceKey) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation)); } public static void TryAddKeyedTransient<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.KeyedTransient(serviceKey, implementationFactory)); } public static void TryAddKeyedScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, service); collection.TryAdd(descriptor); } public static void TryAddKeyedScoped(this IServiceCollection collection, Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, implementationType); collection.TryAdd(descriptor); } public static void TryAddKeyedScoped(this IServiceCollection collection, Type service, object? serviceKey, Func<IServiceProvider, objec
plugins/Microsoft.Extensions.Logging.Abstractions.dll
Decompiled 2 hours 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.DependencyInjection; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Logging abstractions for Microsoft.Extensions.Logging.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Logging.ILogger\r\nMicrosoft.Extensions.Logging.ILoggerFactory\r\nMicrosoft.Extensions.Logging.ILogger<TCategoryName>\r\nMicrosoft.Extensions.Logging.LogLevel\r\nMicrosoft.Extensions.Logging.Logger<T>\r\nMicrosoft.Extensions.Logging.LoggerMessage\r\nMicrosoft.Extensions.Logging.Abstractions.NullLogger")] [assembly: AssemblyFileVersion("8.0.1024.46610")] [assembly: AssemblyInformationalVersion("8.0.10+81cabf2857a01351e5ab578947c7403a5b128ad1")] [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("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } [CompilerGenerated] [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] [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] [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] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Logging.Abstractions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } private static void Throw(string paramName) { throw new ArgumentNullException(paramName); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "") { if (argument == null) { throw new ArgumentNullException(paramName); } if (string.IsNullOrWhiteSpace(argument)) { if (argument == null) { throw new ArgumentNullException(paramName); } throw new ArgumentException(paramName, "Argument is whitespace"); } return argument; } } internal static class SR { private static readonly bool s_usingResourceKeys = 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"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } } namespace System.Text { internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => ref _chars[index]; public Span<char> RawChars => _chars; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public void EnsureCapacity(int capacity) { if ((uint)capacity > (uint)_chars.Length) { Grow(capacity - _pos); } } public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public override string ToString() { string result = _chars.Slice(0, _pos).ToString(); Dispose(); return result; } public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } charsWritten = 0; Dispose(); return false; } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int length = _pos - index; _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string? s) { if (s != null) { int length = s.Length; if (_pos > _chars.Length - length) { Grow(length); } int length2 = _pos - index; _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); s.AsSpan().CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; Span<char> chars = _chars; if ((uint)pos < (uint)chars.Length) { chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string? s) { if (s != null) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.AsSpan().CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span<char> span = _chars.Slice(_pos, count); for (int i = 0; i < span.Length; i++) { span[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { 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 builder = null; string text = ProcessType(ref builder, type, new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter)); return text ?? builder?.ToString() ?? string.Empty; } private static string ProcessType(ref StringBuilder builder, Type type, in DisplayNameOptions options) { string value; if (type.IsGenericType) { Type[] genericArguments = type.GetGenericArguments(); if (builder == null) { builder = new StringBuilder(); } ProcessGenericType(builder, type, genericArguments, genericArguments.Length, in options); } else if (type.IsArray) { if (builder == null) { builder = new StringBuilder(); } ProcessArrayType(builder, type, in options); } else if (_builtInTypeNames.TryGetValue(type, out value)) { if (builder == null) { return value; } builder.Append(value); } else if (type.IsGenericParameter) { if (options.IncludeGenericParameterNames) { if (builder == null) { return type.Name; } builder.Append(type.Name); } } else { string text = (options.FullName ? type.FullName : type.Name); if (builder == null) { if (options.NestedTypeDelimiter != '+') { return text.Replace('+', options.NestedTypeDelimiter); } return text; } builder.Append(text); if (options.NestedTypeDelimiter != '+') { builder.Replace('+', options.NestedTypeDelimiter, builder.Length - text.Length, text.Length); } } return null; } private static void ProcessArrayType(StringBuilder builder, Type type, in DisplayNameOptions options) { Type type2 = type; while (type2.IsArray) { type2 = type2.GetElementType(); } ProcessType(ref builder, type2, in options); while (type.IsArray) { builder.Append('['); builder.Append(',', type.GetArrayRank() - 1); builder.Append(']'); type = type.GetElementType(); } } private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, in DisplayNameOptions options) { int num = 0; if (type.IsNested) { num = type.DeclaringType.GetGenericArguments().Length; } if (options.FullName) { if (type.IsNested) { ProcessGenericType(builder, type.DeclaringType, genericArguments, num, in options); builder.Append(options.NestedTypeDelimiter); } else if (!string.IsNullOrEmpty(type.Namespace)) { builder.Append(type.Namespace); builder.Append('.'); } } int num2 = type.Name.IndexOf('`'); if (num2 <= 0) { builder.Append(type.Name); return; } builder.Append(type.Name, 0, num2); if (!options.IncludeGenericParameters) { return; } builder.Append('<'); for (int i = num; i < length; i++) { ProcessType(ref builder, genericArguments[i], in options); if (i + 1 != length) { builder.Append(','); if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter) { builder.Append(' '); } } } builder.Append('>'); } } } namespace Microsoft.Extensions.Logging { public readonly struct EventId : IEquatable<EventId> { public int Id { get; } public string? Name { get; } public static implicit operator EventId(int i) { return new EventId(i); } public static bool operator ==(EventId left, EventId right) { return left.Equals(right); } public static bool operator !=(EventId left, EventId right) { return !left.Equals(right); } public EventId(int id, string? name = null) { Id = id; Name = name; } public override string ToString() { return Name ?? Id.ToString(); } public bool Equals(EventId other) { return Id == other.Id; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null) { return false; } if (obj is EventId other) { return Equals(other); } return false; } public override int GetHashCode() { return Id; } } internal readonly struct FormattedLogValues : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>> { internal const int MaxCachedFormatters = 1024; private const string NullFormat = "[null]"; private static int s_count; private static readonly ConcurrentDictionary<string, LogValuesFormatter> s_formatters = new ConcurrentDictionary<string, LogValuesFormatter>(); private readonly LogValuesFormatter _formatter; private readonly object[] _values; private readonly string _originalMessage; internal LogValuesFormatter? Formatter => _formatter; public KeyValuePair<string, object?> this[int index] { get { if (index < 0 || index >= Count) { throw new IndexOutOfRangeException("index"); } if (index == Count - 1) { return new KeyValuePair<string, object>("{OriginalFormat}", _originalMessage); } return _formatter.GetValue(_values, index); } } public int Count { get { if (_formatter == null) { return 1; } return _formatter.ValueNames.Count + 1; } } public FormattedLogValues(string? format, params object?[]? values) { if (values != null && values.Length != 0 && format != null) { if (s_count >= 1024) { if (!s_formatters.TryGetValue(format, out _formatter)) { _formatter = new LogValuesFormatter(format); } } else { _formatter = s_formatters.GetOrAdd(format, delegate(string f) { Interlocked.Increment(ref s_count); return new LogValuesFormatter(f); }); } } else { _formatter = null; } _originalMessage = format ?? "[null]"; _values = values; } public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public override string ToString() { if (_formatter == null) { return _originalMessage; } return _formatter.Format(_values); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public interface IExternalScopeProvider { void ForEachScope<TState>(Action<object?, TState> callback, TState state); IDisposable Push(object? state); } public interface ILogger { void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter); bool IsEnabled(LogLevel logLevel); IDisposable? BeginScope<TState>(TState state) where TState : notnull; } public interface ILoggerFactory : IDisposable { ILogger CreateLogger(string categoryName); void AddProvider(ILoggerProvider provider); } public interface ILoggerProvider : IDisposable { ILogger CreateLogger(string categoryName); } public interface ILogger<out TCategoryName> : ILogger { } public interface ILoggingBuilder { IServiceCollection Services { get; } } public interface ISupportExternalScope { void SetScopeProvider(IExternalScopeProvider scopeProvider); } public class LogDefineOptions { public bool SkipEnabledCheck { get; set; } } public static class LoggerExtensions { private static readonly Func<FormattedLogValues, Exception, string> _messageFormatter = MessageFormatter; public static void LogDebug(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Debug, eventId, exception, message, args); } public static void LogDebug(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Debug, eventId, message, args); } public static void LogDebug(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Debug, exception, message, args); } public static void LogDebug(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Debug, message, args); } public static void LogTrace(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Trace, eventId, exception, message, args); } public static void LogTrace(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Trace, eventId, message, args); } public static void LogTrace(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Trace, exception, message, args); } public static void LogTrace(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Trace, message, args); } public static void LogInformation(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Information, eventId, exception, message, args); } public static void LogInformation(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Information, eventId, message, args); } public static void LogInformation(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Information, exception, message, args); } public static void LogInformation(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Information, message, args); } public static void LogWarning(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Warning, eventId, exception, message, args); } public static void LogWarning(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Warning, eventId, message, args); } public static void LogWarning(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Warning, exception, message, args); } public static void LogWarning(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Warning, message, args); } public static void LogError(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Error, eventId, exception, message, args); } public static void LogError(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Error, eventId, message, args); } public static void LogError(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Error, exception, message, args); } public static void LogError(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Error, message, args); } public static void LogCritical(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Critical, eventId, exception, message, args); } public static void LogCritical(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Critical, eventId, message, args); } public static void LogCritical(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Critical, exception, message, args); } public static void LogCritical(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Critical, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, string? message, params object?[] args) { logger.Log(logLevel, 0, null, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, string? message, params object?[] args) { logger.Log(logLevel, eventId, null, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, Exception? exception, string? message, params object?[] args) { logger.Log(logLevel, 0, exception, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, string? message, params object?[] args) { System.ThrowHelper.ThrowIfNull(logger, "logger"); logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter); } public static IDisposable? BeginScope(this ILogger logger, string messageFormat, params object?[] args) { System.ThrowHelper.ThrowIfNull(logger, "logger"); return logger.BeginScope(new FormattedLogValues(messageFormat, args)); } private static string MessageFormatter(FormattedLogValues state, Exception error) { return state.ToString(); } } public class LoggerExternalScopeProvider : IExternalScopeProvider { private sealed class Scope : IDisposable { private readonly LoggerExternalScopeProvider _provider; private bool _isDisposed; public Scope Parent { get; } public object State { get; } internal Scope(LoggerExternalScopeProvider provider, object state, Scope parent) { _provider = provider; State = state; Parent = parent; } public override string ToString() { return State?.ToString(); } public void Dispose() { if (!_isDisposed) { _provider._currentScope.Value = Parent; _isDisposed = true; } } } private readonly AsyncLocal<Scope> _currentScope = new AsyncLocal<Scope>(); public void ForEachScope<TState>(Action<object?, TState> callback, TState state) { Report(_currentScope.Value); void Report(Scope? current) { if (current != null) { Report(current.Parent); callback(current.State, state); } } } public IDisposable Push(object? state) { Scope value = _currentScope.Value; Scope scope = new Scope(this, state, value); _currentScope.Value = scope; return scope; } } public static class LoggerFactoryExtensions { public static ILogger<T> CreateLogger<T>(this ILoggerFactory factory) { System.ThrowHelper.ThrowIfNull(factory, "factory"); return new Logger<T>(factory); } public static ILogger CreateLogger(this ILoggerFactory factory, Type type) { System.ThrowHelper.ThrowIfNull(factory, "factory"); System.ThrowHelper.ThrowIfNull(type, "type"); return factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(type, fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.')); } } public static class LoggerMessage { private readonly struct LogValues : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues, Exception, string> Callback = (LogValues state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; public KeyValuePair<string, object> this[int index] { get { if (index == 0) { return new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat); } throw new IndexOutOfRangeException("index"); } } public int Count => 1; public LogValues(LogValuesFormatter formatter) { _formatter = formatter; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { yield return this[0]; } public override string ToString() { return _formatter.Format(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0>, Exception, string> Callback = (LogValues<T0> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public int Count => 2; public LogValues(LogValuesFormatter formatter, T0 value0) { _formatter = formatter; _value0 = value0; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public override string ToString() { return _formatter.Format(_value0); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1>, Exception, string> Callback = (LogValues<T0, T1> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public int Count => 3; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1) { _formatter = formatter; _value0 = value0; _value1 = value1; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public override string ToString() { return _formatter.Format(_value0, _value1); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2>, Exception, string> Callback = (LogValues<T0, T1, T2> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; public int Count => 4; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; } public override string ToString() { return _formatter.Format(_value0, _value1, _value2); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2, T3> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2, T3>, Exception, string> Callback = (LogValues<T0, T1, T2, T3> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; private readonly T3 _value3; public int Count => 5; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 4 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; } private object[] ToArray() { return new object[4] { _value0, _value1, _value2, _value3 }; } public override string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2, T3, T4> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2, T3, T4>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; private readonly T3 _value3; private readonly T4 _value4; public int Count => 6; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 5 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; _value4 = value4; } private object[] ToArray() { return new object[5] { _value0, _value1, _value2, _value3, _value4 }; } public override string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2, T3, T4, T5> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2, T3, T4, T5>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4, T5> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; private readonly T3 _value3; private readonly T4 _value4; private readonly T5 _value5; public int Count => 7; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 5 => new KeyValuePair<string, object>(_formatter.ValueNames[5], _value5), 6 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; _value4 = value4; _value5 = value5; } private object[] ToArray() { return new object[6] { _value0, _value1, _value2, _value3, _value4, _value5 }; } public override string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static Func<ILogger, IDisposable?> DefineScope(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0); LogValues logValues = new LogValues(formatter); return (ILogger logger) => logger.BeginScope(logValues); } public static Func<ILogger, T1, IDisposable?> DefineScope<T1>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1); return (ILogger logger, T1 arg1) => logger.BeginScope(new LogValues<T1>(formatter, arg1)); } public static Func<ILogger, T1, T2, IDisposable?> DefineScope<T1, T2>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2); return (ILogger logger, T1 arg1, T2 arg2) => logger.BeginScope(new LogValues<T1, T2>(formatter, arg1, arg2)); } public static Func<ILogger, T1, T2, T3, IDisposable?> DefineScope<T1, T2, T3>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3) => logger.BeginScope(new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3)); } public static Func<ILogger, T1, T2, T3, T4, IDisposable?> DefineScope<T1, T2, T3, T4>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4) => logger.BeginScope(new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4)); } public static Func<ILogger, T1, T2, T3, T4, T5, IDisposable?> DefineScope<T1, T2, T3, T4, T5>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5)); } public static Func<ILogger, T1, T2, T3, T4, T5, T6, IDisposable?> DefineScope<T1, T2, T3, T4, T5, T6>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6)); } public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString) { return Define(logLevel, eventId, formatString, null); } public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, exception); } }; void Log(ILogger logger, Exception exception) { logger.Log(logLevel, eventId, new LogValues(formatter), exception, LogValues.Callback); } } public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, exception); } }; void Log(ILogger logger, T1 arg1, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1>(formatter, arg1), exception, LogValues<T1>.Callback); } } public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2>(formatter, arg1, arg2), exception, LogValues<T1, T2>.Callback); } } public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3), exception, LogValues<T1, T2, T3>.Callback); } } public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3, T4>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, arg4, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4), exception, LogValues<T1, T2, T3, T4>.Callback); } } public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3, T4, T5>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, arg4, arg5, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5), exception, LogValues<T1, T2, T3, T4, T5>.Callback); } } public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3, T4, T5, T6>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, arg4, arg5, arg6, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6), exception, LogValues<T1, T2, T3, T4, T5, T6>.Callback); } } private static LogValuesFormatter CreateLogValuesFormatter(string formatString, int expectedNamedParameterCount) { LogValuesFormatter logValuesFormatter = new LogValuesFormatter(formatString); int count = logValuesFormatter.ValueNames.Count; if (count != expectedNamedParameterCount) { throw new ArgumentException(System.SR.Format(System.SR.UnexpectedNumberOfNamedParameters, formatString, expectedNamedParameterCount, count)); } return logValuesFormatter; } } [AttributeUsage(AttributeTargets.Method)] public sealed class LoggerMessageAttribute : Attribute { public int EventId { get; set; } = -1; public string? EventName { get; set; } public LogLevel Level { get; set; } = LogLevel.None; public string Message { get; set; } = ""; public bool SkipEnabledCheck { get; set; } public LoggerMessageAttribute() { } public LoggerMessageAttribute(int eventId, LogLevel level, string message) { EventId = eventId; Level = level; Message = message; } public LoggerMessageAttribute(LogLevel level, string message) { Level = level; Message = message; } public LoggerMessageAttribute(LogLevel level) { Level = level; } public LoggerMessageAttribute(string message) { Message = message; } } [DebuggerDisplay("{DebuggerToString(),nq}")] public class Logger<T> : ILogger<T>, ILogger { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private readonly ILogger _logger; public Logger(ILoggerFactory factory) { System.ThrowHelper.ThrowIfNull(factory, "factory"); _logger = factory.CreateLogger(GetCategoryName()); } IDisposable ILogger.BeginScope<TState>(TState state) { return _logger.BeginScope(state); } bool ILogger.IsEnabled(LogLevel logLevel) { return _logger.IsEnabled(logLevel); } void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { _logger.Log(logLevel, eventId, state, exception, formatter); } private static string GetCategoryName() { return TypeNameHelper.GetTypeDisplayName(typeof(T), fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.'); } internal string DebuggerToString() { return DebuggerDisplayFormatting.DebuggerToString(GetCategoryName(), this); } } public enum LogLevel { Trace, Debug, Information, Warning, Error, Critical, None } internal sealed class LogValuesFormatter { private const string NullValue = "(null)"; private static readonly char[] FormatDelimiters = new char[2] { ',', ':' }; private readonly List<string> _valueNames = new List<string>(); private readonly string _format; 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 static object FormatArgument(object value) { if (!TryFormatArgumentIfNullOrEnumerable(value, out var stringValue)) { return value; } return stringValue; } private static bool TryFormatArgumentIfNullOrEnumerable<T>(T value, [NotNullWhen(true)] out object stringValue) { if (value == null) { stringValue = "(null)"; return true; } if (!(value is string) && value is IEnumerable enumerable) { Span<char> initialBuffer = stackalloc char[256]; System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer); bool flag = true; foreach (object item in enumerable) { if (!flag) { valueStringBuilder.Append(", "); } valueStringBuilder.Append((item != null) ? item.ToString() : "(null)"); flag = false; } stringValue = valueStringBuilder.ToString(); return true; } stringValue = null; return false; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { public static IExternalScopeProvider Instance { get; } = new NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } internal sealed class NullScope : IDisposable { public static NullScope Instance { get; } = new NullScope(); private NullScope() { } public void Dispose() { } } internal static class DebuggerDisplayFormatting { internal static string DebuggerToString(string name, ILogger logger) { LogLevel? logLevel = CalculateEnabledLogLevel(logger); string text = "Name = \"" + name + "\""; if (logLevel.HasValue) { return text + $", MinLevel = {logLevel}"; } return text + ", Enabled = false"; } internal static LogLevel? CalculateEnabledLogLevel(ILogger logger) { Span<LogLevel> span = stackalloc LogLevel[6] { LogLevel.Critical, LogLevel.Error, LogLevel.Warning, LogLevel.Information, LogLevel.Debug, LogLevel.Trace }; ReadOnlySpan<LogLevel> readOnlySpan = span; LogLevel? result = null; ReadOnlySpan<LogLevel> readOnlySpan2 = readOnlySpan; for (int i = 0; i < readOnlySpan2.Length; i++) { LogLevel logLevel = readOnlySpan2[i]; if (!logger.IsEnabled(logLevel)) { break; } result = logLevel; } return result; } } } namespace Microsoft.Extensions.Logging.Abstractions { public 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; } } }
plugins/System.Buffers.dll
Decompiled 2 hours agousing System; using System.Diagnostics; using System.Diagnostics.Tracing; 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.Threading; using FxResources.System.Buffers; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: CLSCompliant(true)] [assembly: AssemblyDefaultAlias("System.Buffers")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("System.Buffers")] [assembly: AssemblyFileVersion("4.600.125.16908")] [assembly: AssemblyInformationalVersion("4.6.1+6b84308c9ad012f53240d72c1d716d7e42546483")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Buffers")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/maintenance-packages")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.2.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Buffers { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool"); 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.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; } } }
plugins/System.Diagnostics.DiagnosticSource.dll
Decompiled 2 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Globalization; using System.Net; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using FxResources.System.Diagnostics.DiagnosticSource; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Diagnostics.DiagnosticSource")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides Classes that allow you to decouple code logging rich (unserializable) diagnostics/telemetry (e.g. framework) from code that consumes it (e.g. tools)\r\n\r\nCommonly Used Types:\r\nSystem.Diagnostics.DiagnosticListener\r\nSystem.Diagnostics.DiagnosticSource")] [assembly: AssemblyFileVersion("8.0.424.16909")] [assembly: AssemblyInformationalVersion("8.0.4+2d7eea252964e69be94cb9c847b371b23e4dd470")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Diagnostics.DiagnosticSource")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Diagnostics.DiagnosticSource { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { byte value = readOnlySpan[i]; ToCharsBuffer(value, buffer, num, casing); num += 2; } return buffer.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes) { int charsProcessed; return TryDecodeFromUtf16(chars, bytes, out charsProcessed); } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { if (IntPtr.Size == 8) { ulong num = (uint)(c - 48); ulong num2 = (ulong)(-17875860044349952L << (int)num); ulong num3 = num - 64; return (long)(num2 & num3) < 0L; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class SR { private static readonly bool s_usingResourceKeys = 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 ActivityIdFormatInvalid => GetResourceString("ActivityIdFormatInvalid"); internal static string ActivityNotRunning => GetResourceString("ActivityNotRunning"); internal static string ActivityNotStarted => GetResourceString("ActivityNotStarted"); internal static string ActivityStartAlreadyStarted => GetResourceString("ActivityStartAlreadyStarted"); internal static string ActivitySetParentAlreadyStarted => GetResourceString("ActivitySetParentAlreadyStarted"); internal static string EndTimeNotUtc => GetResourceString("EndTimeNotUtc"); internal static string OperationNameInvalid => GetResourceString("OperationNameInvalid"); internal static string ParentIdAlreadySet => GetResourceString("ParentIdAlreadySet"); internal static string ParentIdInvalid => GetResourceString("ParentIdInvalid"); internal static string SetFormatOnStartedActivity => GetResourceString("SetFormatOnStartedActivity"); internal static string SetParentIdOnActivityWithParent => GetResourceString("SetParentIdOnActivityWithParent"); internal static string StartTimeNotUtc => GetResourceString("StartTimeNotUtc"); internal static string KeyAlreadyExist => GetResourceString("KeyAlreadyExist"); internal static string InvalidTraceParent => GetResourceString("InvalidTraceParent"); internal static string UnableAccessServicePointTable => GetResourceString("UnableAccessServicePointTable"); internal static string UnableToInitialize => GetResourceString("UnableToInitialize"); internal static string UnsupportedType => GetResourceString("UnsupportedType"); internal static string Arg_BufferTooSmall => GetResourceString("Arg_BufferTooSmall"); internal static string InvalidInstrumentType => GetResourceString("InvalidInstrumentType"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Runtime.Versioning { internal abstract class OSPlatformAttribute : Attribute { public string PlatformName { get; } private protected OSPlatformAttribute(string platformName) { PlatformName = platformName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetPlatformAttribute : OSPlatformAttribute { public TargetPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute { public SupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } public UnsupportedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public string Url { get; set; } public ObsoletedOSPlatformAttribute(string platformName) : base(platformName) { } public ObsoletedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute { public SupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute { public UnsupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } } namespace System.Diagnostics { public readonly struct ActivityChangedEventArgs { public Activity? Previous { get; init; } public Activity? Current { get; init; } internal ActivityChangedEventArgs(Activity previous, Activity current) { Previous = previous; Current = current; } } public class Activity : IDisposable { public struct Enumerator<T> { private static readonly DiagNode<T> s_Empty = new DiagNode<T>(default(T)); private DiagNode<T> _nextNode; private DiagNode<T> _currentNode; public readonly ref T Current => ref _currentNode.Value; internal Enumerator(DiagNode<T> head) { _nextNode = head; _currentNode = s_Empty; } [EditorBrowsable(EditorBrowsableState.Never)] public readonly Enumerator<T> GetEnumerator() { return this; } public bool MoveNext() { if (_nextNode == null) { _currentNode = s_Empty; return false; } _currentNode = _nextNode; _nextNode = _nextNode.Next; return true; } } private sealed class BaggageLinkedList : IEnumerable<KeyValuePair<string, string>>, IEnumerable { private DiagNode<KeyValuePair<string, string>> _first; public DiagNode<KeyValuePair<string, string>> First => _first; public BaggageLinkedList(KeyValuePair<string, string> firstValue, bool set = false) { _first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, string>>(firstValue)); } public void Add(KeyValuePair<string, string> value) { DiagNode<KeyValuePair<string, string>> diagNode = new DiagNode<KeyValuePair<string, string>>(value); lock (this) { diagNode.Next = _first; _first = diagNode; } } public void Set(KeyValuePair<string, string> value) { if (value.Value == null) { Remove(value.Key); return; } lock (this) { for (DiagNode<KeyValuePair<string, string>> diagNode = _first; diagNode != null; diagNode = diagNode.Next) { if (diagNode.Value.Key == value.Key) { diagNode.Value = value; return; } } DiagNode<KeyValuePair<string, string>> diagNode2 = new DiagNode<KeyValuePair<string, string>>(value); diagNode2.Next = _first; _first = diagNode2; } } public void Remove(string key) { lock (this) { if (_first == null) { return; } if (_first.Value.Key == key) { _first = _first.Next; return; } DiagNode<KeyValuePair<string, string>> diagNode = _first; while (diagNode.Next != null) { if (diagNode.Next.Value.Key == key) { diagNode.Next = diagNode.Next.Next; break; } diagNode = diagNode.Next; } } } public DiagEnumerator<KeyValuePair<string, string>> GetEnumerator() { return new DiagEnumerator<KeyValuePair<string, string>>(_first); } IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal sealed class TagsLinkedList : IEnumerable<KeyValuePair<string, object>>, IEnumerable { private DiagNode<KeyValuePair<string, object>> _first; private DiagNode<KeyValuePair<string, object>> _last; private StringBuilder _stringBuilder; public DiagNode<KeyValuePair<string, object>> First => _first; public TagsLinkedList(KeyValuePair<string, object> firstValue, bool set = false) { _last = (_first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, object>>(firstValue))); } public TagsLinkedList(IEnumerator<KeyValuePair<string, object>> e) { _last = (_first = new DiagNode<KeyValuePair<string, object>>(e.Current)); while (e.MoveNext()) { _last.Next = new DiagNode<KeyValuePair<string, object>>(e.Current); _last = _last.Next; } } public TagsLinkedList(IEnumerable<KeyValuePair<string, object>> list) { Add(list); } public void Add(IEnumerable<KeyValuePair<string, object>> list) { IEnumerator<KeyValuePair<string, object>> enumerator = list.GetEnumerator(); if (enumerator.MoveNext()) { if (_first == null) { _last = (_first = new DiagNode<KeyValuePair<string, object>>(enumerator.Current)); } else { _last.Next = new DiagNode<KeyValuePair<string, object>>(enumerator.Current); _last = _last.Next; } while (enumerator.MoveNext()) { _last.Next = new DiagNode<KeyValuePair<string, object>>(enumerator.Current); _last = _last.Next; } } } public void Add(KeyValuePair<string, object> value) { DiagNode<KeyValuePair<string, object>> diagNode = new DiagNode<KeyValuePair<string, object>>(value); lock (this) { if (_first == null) { _first = (_last = diagNode); return; } _last.Next = diagNode; _last = diagNode; } } public object Get(string key) { for (DiagNode<KeyValuePair<string, object>> diagNode = _first; diagNode != null; diagNode = diagNode.Next) { if (diagNode.Value.Key == key) { return diagNode.Value.Value; } } return null; } public void Remove(string key) { lock (this) { if (_first == null) { return; } if (_first.Value.Key == key) { _first = _first.Next; if (_first == null) { _last = null; } return; } DiagNode<KeyValuePair<string, object>> diagNode = _first; while (diagNode.Next != null) { if (diagNode.Next.Value.Key == key) { if (_last == diagNode.Next) { _last = diagNode; } diagNode.Next = diagNode.Next.Next; break; } diagNode = diagNode.Next; } } } public void Set(KeyValuePair<string, object> value) { if (value.Value == null) { Remove(value.Key); return; } lock (this) { for (DiagNode<KeyValuePair<string, object>> diagNode = _first; diagNode != null; diagNode = diagNode.Next) { if (diagNode.Value.Key == value.Key) { diagNode.Value = value; return; } } DiagNode<KeyValuePair<string, object>> diagNode2 = new DiagNode<KeyValuePair<string, object>>(value); if (_first == null) { _first = (_last = diagNode2); return; } _last.Next = diagNode2; _last = diagNode2; } } public DiagEnumerator<KeyValuePair<string, object>> GetEnumerator() { return new DiagEnumerator<KeyValuePair<string, object>>(_first); } IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerable<KeyValuePair<string, string>> EnumerateStringValues() { for (DiagNode<KeyValuePair<string, object>> current = _first; current != null; current = current.Next) { if (current.Value.Value is string || current.Value.Value == null) { yield return new KeyValuePair<string, string>(current.Value.Key, (string)current.Value.Value); } } } public override string ToString() { lock (this) { if (_first == null) { return string.Empty; } if (_stringBuilder == null) { _stringBuilder = new StringBuilder(); } _stringBuilder.Append(_first.Value.Key); _stringBuilder.Append(':'); _stringBuilder.Append(_first.Value.Value); for (DiagNode<KeyValuePair<string, object>> next = _first.Next; next != null; next = next.Next) { _stringBuilder.Append(", "); _stringBuilder.Append(next.Value.Key); _stringBuilder.Append(':'); _stringBuilder.Append(next.Value.Value); } string result = _stringBuilder.ToString(); _stringBuilder.Clear(); return result; } } } [Flags] private enum State : byte { None = 0, FormatUnknown = 0, FormatHierarchical = 1, FormatW3C = 2, FormatFlags = 3, IsStopped = 0x80 } private static readonly IEnumerable<KeyValuePair<string, string>> s_emptyBaggageTags = new KeyValuePair<string, string>[0]; private static readonly IEnumerable<KeyValuePair<string, object>> s_emptyTagObjects = new KeyValuePair<string, object>[0]; private static readonly IEnumerable<ActivityLink> s_emptyLinks = new ActivityLink[0]; private static readonly IEnumerable<ActivityEvent> s_emptyEvents = new ActivityEvent[0]; private static readonly ActivitySource s_defaultSource = new ActivitySource(string.Empty); private const byte ActivityTraceFlagsIsSet = 128; private const int RequestIdMaxLength = 1024; private static readonly string s_uniqSuffix = $"-{GetRandomNumber():x}."; private static long s_currentRootId = (uint)GetRandomNumber(); private static ActivityIdFormat s_defaultIdFormat; private string _traceState; private State _state; private int _currentChildId; private string _id; private string _rootId; private string _parentId; private string _parentSpanId; private string _traceId; private string _spanId; private byte _w3CIdFlags; private byte _parentTraceFlags; private TagsLinkedList _tags; private BaggageLinkedList _baggage; private DiagLinkedList<ActivityLink> _links; private DiagLinkedList<ActivityEvent> _events; private Dictionary<string, object> _customProperties; private string _displayName; private ActivityStatusCode _statusCode; private string _statusDescription; private Activity _previousActiveActivity; private static readonly AsyncLocal<Activity> s_current = new AsyncLocal<Activity>(); public static bool ForceDefaultIdFormat { get; set; } public ActivityStatusCode Status => _statusCode; public string? StatusDescription => _statusDescription; public bool HasRemoteParent { get; private set; } public ActivityKind Kind { get; private set; } public string OperationName { get; } public string DisplayName { get { return _displayName ?? OperationName; } set { _displayName = value ?? throw new ArgumentNullException("value"); } } public ActivitySource Source { get; private set; } public Activity? Parent { get; private set; } public TimeSpan Duration { get; private set; } public DateTime StartTimeUtc { get; private set; } public string? Id { get { if (_id == null && _spanId != null) { Span<char> buffer = stackalloc char[2]; System.HexConverter.ToCharsBuffer((byte)(0xFFFFFF7Fu & _w3CIdFlags), buffer, 0, System.HexConverter.Casing.Lower); string value = "00-" + _traceId + "-" + _spanId + "-" + buffer; Interlocked.CompareExchange(ref _id, value, null); } return _id; } } public string? ParentId { get { if (_parentId == null) { if (_parentSpanId != null) { Span<char> buffer = stackalloc char[2]; System.HexConverter.ToCharsBuffer((byte)(0xFFFFFF7Fu & _parentTraceFlags), buffer, 0, System.HexConverter.Casing.Lower); string value = "00-" + _traceId + "-" + _parentSpanId + "-" + buffer; Interlocked.CompareExchange(ref _parentId, value, null); } else if (Parent != null) { Interlocked.CompareExchange(ref _parentId, Parent.Id, null); } } return _parentId; } } public string? RootId { get { if (_rootId == null) { string text = null; if (Id != null) { text = GetRootId(Id); } else if (ParentId != null) { text = GetRootId(ParentId); } if (text != null) { Interlocked.CompareExchange(ref _rootId, text, null); } } return _rootId; } } public IEnumerable<KeyValuePair<string, string?>> Tags => _tags?.EnumerateStringValues() ?? s_emptyBaggageTags; public IEnumerable<KeyValuePair<string, object?>> TagObjects { get { IEnumerable<KeyValuePair<string, object>> tags = _tags; return tags ?? s_emptyTagObjects; } } public IEnumerable<ActivityEvent> Events { get { IEnumerable<ActivityEvent> events = _events; return events ?? s_emptyEvents; } } public IEnumerable<ActivityLink> Links { get { IEnumerable<ActivityLink> links = _links; return links ?? s_emptyLinks; } } public IEnumerable<KeyValuePair<string, string?>> Baggage { get { for (Activity activity2 = this; activity2 != null; activity2 = activity2.Parent) { if (activity2._baggage != null) { return Iterate(activity2); } } return s_emptyBaggageTags; static IEnumerable<KeyValuePair<string, string>> Iterate(Activity activity) { do { if (activity._baggage != null) { for (DiagNode<KeyValuePair<string, string>> current = activity._baggage.First; current != null; current = current.Next) { yield return current.Value; } } activity = activity.Parent; } while (activity != null); } } } public ActivityContext Context => new ActivityContext(TraceId, SpanId, ActivityTraceFlags, TraceStateString); public string? TraceStateString { get { for (Activity activity = this; activity != null; activity = activity.Parent) { string traceState = activity._traceState; if (traceState != null) { return traceState; } } return null; } set { _traceState = value; } } public ActivitySpanId SpanId { get { if (_spanId == null && _id != null && IdFormat == ActivityIdFormat.W3C) { string value = ActivitySpanId.CreateFromString(_id.AsSpan(36, 16)).ToHexString(); Interlocked.CompareExchange(ref _spanId, value, null); } return new ActivitySpanId(_spanId); } } public ActivityTraceId TraceId { get { if (_traceId == null) { TrySetTraceIdFromParent(); } return new ActivityTraceId(_traceId); } } public bool Recorded => (ActivityTraceFlags & ActivityTraceFlags.Recorded) != 0; public bool IsAllDataRequested { get; set; } public ActivityTraceFlags ActivityTraceFlags { get { if (!W3CIdFlagsSet) { TrySetTraceFlagsFromParent(); } return (ActivityTraceFlags)(-129 & (int)_w3CIdFlags); } set { _w3CIdFlags = (byte)(0x80u | (byte)value); } } public ActivitySpanId ParentSpanId { get { if (_parentSpanId == null) { string text = null; if (_parentId != null && IsW3CId(_parentId)) { try { text = ActivitySpanId.CreateFromString(_parentId.AsSpan(36, 16)).ToHexString(); } catch { } } else if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C) { text = Parent.SpanId.ToHexString(); } if (text != null) { Interlocked.CompareExchange(ref _parentSpanId, text, null); } } return new ActivitySpanId(_parentSpanId); } } public static Func<ActivityTraceId>? TraceIdGenerator { get; set; } public static ActivityIdFormat DefaultIdFormat { get { if (s_defaultIdFormat == ActivityIdFormat.Unknown) { s_defaultIdFormat = ActivityIdFormat.Hierarchical; } return s_defaultIdFormat; } set { if (ActivityIdFormat.Hierarchical > value || value > ActivityIdFormat.W3C) { throw new ArgumentException(System.SR.ActivityIdFormatInvalid); } s_defaultIdFormat = value; } } private bool W3CIdFlagsSet => (_w3CIdFlags & 0x80) != 0; public bool IsStopped { get { return (_state & State.IsStopped) != 0; } private set { if (value) { _state |= State.IsStopped; } else { _state &= ~State.IsStopped; } } } public ActivityIdFormat IdFormat { get { return (ActivityIdFormat)(_state & State.FormatFlags); } private set { _state = (_state & ~State.FormatFlags) | (State)((byte)value & 3u); } } public static Activity? Current { get { return s_current.Value; } set { if (ValidateSetCurrent(value)) { SetCurrent(value); } } } public static event EventHandler<ActivityChangedEventArgs>? CurrentChanged; public Activity SetStatus(ActivityStatusCode code, string? description = null) { _statusCode = code; _statusDescription = ((code == ActivityStatusCode.Error) ? description : null); return this; } public Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects() { return new Enumerator<KeyValuePair<string, object>>(_tags?.First); } public Enumerator<ActivityEvent> EnumerateEvents() { return new Enumerator<ActivityEvent>(_events?.First); } public Enumerator<ActivityLink> EnumerateLinks() { return new Enumerator<ActivityLink>(_links?.First); } public string? GetBaggageItem(string key) { foreach (KeyValuePair<string, string> item in Baggage) { if (key == item.Key) { return item.Value; } } return null; } public object? GetTagItem(string key) { return _tags?.Get(key) ?? null; } public Activity(string operationName) { Source = s_defaultSource; IsAllDataRequested = true; if (string.IsNullOrEmpty(operationName)) { NotifyError(new ArgumentException(System.SR.OperationNameInvalid)); } OperationName = operationName ?? string.Empty; } public Activity AddTag(string key, string? value) { return AddTag(key, (object?)value); } public Activity AddTag(string key, object? value) { KeyValuePair<string, object> keyValuePair = new KeyValuePair<string, object>(key, value); if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(keyValuePair), null) != null) { _tags.Add(keyValuePair); } return this; } public Activity SetTag(string key, object? value) { KeyValuePair<string, object> keyValuePair = new KeyValuePair<string, object>(key, value); if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(keyValuePair, set: true), null) != null) { _tags.Set(keyValuePair); } return this; } public Activity AddEvent(ActivityEvent e) { if (_events != null || Interlocked.CompareExchange(ref _events, new DiagLinkedList<ActivityEvent>(e), null) != null) { _events.Add(e); } return this; } public Activity AddBaggage(string key, string? value) { KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>(key, value); if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(keyValuePair), null) != null) { _baggage.Add(keyValuePair); } return this; } public Activity SetBaggage(string key, string? value) { KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>(key, value); if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(keyValuePair, set: true), null) != null) { _baggage.Set(keyValuePair); } return this; } public Activity SetParentId(string parentId) { if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(System.SR.ActivitySetParentAlreadyStarted)); } else if (Parent != null) { NotifyError(new InvalidOperationException(System.SR.SetParentIdOnActivityWithParent)); } else if (ParentId != null || _parentSpanId != null) { NotifyError(new InvalidOperationException(System.SR.ParentIdAlreadySet)); } else if (string.IsNullOrEmpty(parentId)) { NotifyError(new ArgumentException(System.SR.ParentIdInvalid)); } else { _parentId = parentId; } return this; } public Activity SetParentId(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags activityTraceFlags = ActivityTraceFlags.None) { if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(System.SR.ActivitySetParentAlreadyStarted)); } else if (Parent != null) { NotifyError(new InvalidOperationException(System.SR.SetParentIdOnActivityWithParent)); } else if (ParentId != null || _parentSpanId != null) { NotifyError(new InvalidOperationException(System.SR.ParentIdAlreadySet)); } else { _traceId = traceId.ToHexString(); _parentSpanId = spanId.ToHexString(); ActivityTraceFlags = activityTraceFlags; _parentTraceFlags = (byte)activityTraceFlags; } return this; } public Activity SetStartTime(DateTime startTimeUtc) { if (startTimeUtc.Kind != DateTimeKind.Utc) { NotifyError(new InvalidOperationException(System.SR.StartTimeNotUtc)); } else { StartTimeUtc = startTimeUtc; } return this; } public Activity SetEndTime(DateTime endTimeUtc) { if (endTimeUtc.Kind != DateTimeKind.Utc) { NotifyError(new InvalidOperationException(System.SR.EndTimeNotUtc)); } else { Duration = endTimeUtc - StartTimeUtc; if (Duration.Ticks <= 0) { Duration = new TimeSpan(1L); } } return this; } public Activity Start() { if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(System.SR.ActivityStartAlreadyStarted)); } else { _previousActiveActivity = Current; if (_parentId == null && _parentSpanId == null && _previousActiveActivity != null) { Parent = _previousActiveActivity; } if (StartTimeUtc == default(DateTime)) { StartTimeUtc = GetUtcNow(); } if (IdFormat == ActivityIdFormat.Unknown) { IdFormat = (ForceDefaultIdFormat ? DefaultIdFormat : ((Parent != null) ? Parent.IdFormat : ((_parentSpanId != null) ? ActivityIdFormat.W3C : ((_parentId == null) ? DefaultIdFormat : ((!IsW3CId(_parentId)) ? ActivityIdFormat.Hierarchical : ActivityIdFormat.W3C))))); } if (IdFormat == ActivityIdFormat.W3C) { GenerateW3CId(); } else { _id = GenerateHierarchicalId(); } SetCurrent(this); Source.NotifyActivityStart(this); } return this; } public void Stop() { if (_id == null && _spanId == null) { NotifyError(new InvalidOperationException(System.SR.ActivityNotStarted)); } else if (!IsStopped) { IsStopped = true; if (Duration == TimeSpan.Zero) { SetEndTime(GetUtcNow()); } Source.NotifyActivityStop(this); SetCurrent(_previousActiveActivity); } } public Activity SetIdFormat(ActivityIdFormat format) { if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(System.SR.SetFormatOnStartedActivity)); } else { IdFormat = format; } return this; } private static bool IsW3CId(string id) { if (id.Length == 55 && (('0' <= id[0] && id[0] <= '9') || ('a' <= id[0] && id[0] <= 'f')) && (('0' <= id[1] && id[1] <= '9') || ('a' <= id[1] && id[1] <= 'f'))) { if (id[0] == 'f') { return id[1] != 'f'; } return true; } return false; } internal static bool TryConvertIdToContext(string traceParent, string traceState, bool isRemote, out ActivityContext context) { context = default(ActivityContext); if (!IsW3CId(traceParent)) { return false; } ReadOnlySpan<char> idData = traceParent.AsSpan(3, 32); ReadOnlySpan<char> idData2 = traceParent.AsSpan(36, 16); if (!ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData) || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData2) || !System.HexConverter.IsHexLowerChar(traceParent[53]) || !System.HexConverter.IsHexLowerChar(traceParent[54])) { return false; } context = new ActivityContext(new ActivityTraceId(idData.ToString()), new ActivitySpanId(idData2.ToString()), (ActivityTraceFlags)ActivityTraceId.HexByteFromChars(traceParent[53], traceParent[54]), traceState, isRemote); return true; } public void Dispose() { if (!IsStopped) { Stop(); } Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } public void SetCustomProperty(string propertyName, object? propertyValue) { if (_customProperties == null) { Interlocked.CompareExchange(ref _customProperties, new Dictionary<string, object>(), null); } lock (_customProperties) { if (propertyValue == null) { _customProperties.Remove(propertyName); } else { _customProperties[propertyName] = propertyValue; } } } public object? GetCustomProperty(string propertyName) { if (_customProperties == null) { return null; } lock (_customProperties) { object value; return _customProperties.TryGetValue(propertyName, out value) ? value : null; } } internal static Activity Create(ActivitySource source, string name, ActivityKind kind, string parentId, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, DateTimeOffset startTime, ActivityTagsCollection samplerTags, ActivitySamplingResult request, bool startIt, ActivityIdFormat idFormat, string traceState) { Activity activity = new Activity(name); activity.Source = source; activity.Kind = kind; activity.IdFormat = idFormat; activity._traceState = traceState; if (links != null) { using IEnumerator<ActivityLink> enumerator = links.GetEnumerator(); if (enumerator.MoveNext()) { activity._links = new DiagLinkedList<ActivityLink>(enumerator); } } if (tags != null) { using IEnumerator<KeyValuePair<string, object>> enumerator2 = tags.GetEnumerator(); if (enumerator2.MoveNext()) { activity._tags = new TagsLinkedList(enumerator2); } } if (samplerTags != null) { if (activity._tags == null) { activity._tags = new TagsLinkedList(samplerTags); } else { activity._tags.Add(samplerTags); } } if (parentId != null) { activity._parentId = parentId; } else if (parentContext != default(ActivityContext)) { activity._traceId = parentContext.TraceId.ToString(); if (parentContext.SpanId != default(ActivitySpanId)) { activity._parentSpanId = parentContext.SpanId.ToString(); } activity.ActivityTraceFlags = parentContext.TraceFlags; activity._parentTraceFlags = (byte)parentContext.TraceFlags; activity.HasRemoteParent = parentContext.IsRemote; } activity.IsAllDataRequested = request == ActivitySamplingResult.AllData || request == ActivitySamplingResult.AllDataAndRecorded; if (request == ActivitySamplingResult.AllDataAndRecorded) { activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded; } if (startTime != default(DateTimeOffset)) { activity.StartTimeUtc = startTime.UtcDateTime; } if (startIt) { activity.Start(); } return activity; } private void GenerateW3CId() { if (_traceId == null && !TrySetTraceIdFromParent()) { _traceId = (TraceIdGenerator?.Invoke() ?? ActivityTraceId.CreateRandom()).ToHexString(); } if (!W3CIdFlagsSet) { TrySetTraceFlagsFromParent(); } _spanId = ActivitySpanId.CreateRandom().ToHexString(); } private static void NotifyError(Exception exception) { try { throw exception; } catch { } } private string GenerateHierarchicalId() { if (Parent != null) { return AppendSuffix(Parent.Id, Interlocked.Increment(ref Parent._currentChildId).ToString(), '.'); } if (ParentId != null) { string text = ((ParentId[0] == '|') ? ParentId : ("|" + ParentId)); char c = text[text.Length - 1]; if (c != '.' && c != '_') { text += "."; } return AppendSuffix(text, Interlocked.Increment(ref s_currentRootId).ToString("x"), '_'); } return GenerateRootId(); } private string GetRootId(string id) { if (IdFormat == ActivityIdFormat.W3C) { return id.Substring(3, 32); } int num = id.IndexOf('.'); if (num < 0) { num = id.Length; } int num2 = ((id[0] == '|') ? 1 : 0); return id.Substring(num2, num - num2); } private string AppendSuffix(string parentId, string suffix, char delimiter) { if (parentId.Length + suffix.Length < 1024) { return parentId + suffix + delimiter; } int num = 1015; while (num > 1 && parentId[num - 1] != '.' && parentId[num - 1] != '_') { num--; } if (num == 1) { return GenerateRootId(); } string text = ((int)GetRandomNumber()).ToString("x8"); return parentId.Substring(0, num) + text + "#"; } private unsafe static long GetRandomNumber() { Guid guid = Guid.NewGuid(); return *(long*)(&guid); } private static bool ValidateSetCurrent(Activity activity) { bool flag = activity == null || (activity.Id != null && !activity.IsStopped); if (!flag) { NotifyError(new InvalidOperationException(System.SR.ActivityNotRunning)); } return flag; } private bool TrySetTraceIdFromParent() { if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C) { _traceId = Parent.TraceId.ToHexString(); } else if (_parentId != null && IsW3CId(_parentId)) { try { _traceId = ActivityTraceId.CreateFromString(_parentId.AsSpan(3, 32)).ToHexString(); } catch { } } return _traceId != null; } private void TrySetTraceFlagsFromParent() { if (W3CIdFlagsSet) { return; } if (Parent != null) { ActivityTraceFlags = Parent.ActivityTraceFlags; } else if (_parentId != null && IsW3CId(_parentId)) { if (System.HexConverter.IsHexLowerChar(_parentId[53]) && System.HexConverter.IsHexLowerChar(_parentId[54])) { _w3CIdFlags = (byte)(ActivityTraceId.HexByteFromChars(_parentId[53], _parentId[54]) | 0x80u); } else { _w3CIdFlags = 128; } } } private static void SetCurrent(Activity activity) { EventHandler<ActivityChangedEventArgs> currentChanged = Activity.CurrentChanged; if (currentChanged == null) { s_current.Value = activity; return; } Activity value = s_current.Value; s_current.Value = activity; currentChanged(null, new ActivityChangedEventArgs(value, activity)); } private static string GenerateRootId() { return $"|{Interlocked.Increment(ref s_currentRootId):x}{s_uniqSuffix}"; } internal static DateTime GetUtcNow() { return DateTime.UtcNow; } } [Flags] public enum ActivityTraceFlags { None = 0, Recorded = 1 } public enum ActivityIdFormat { Unknown, Hierarchical, W3C } public readonly struct ActivityTraceId : IEquatable<ActivityTraceId> { private readonly string _hexString; internal ActivityTraceId(string hexString) { _hexString = hexString; } public static ActivityTraceId CreateRandom() { Span<byte> span = stackalloc byte[16]; SetToRandomBytes(span); return CreateFromBytes(span); } public static ActivityTraceId CreateFromBytes(ReadOnlySpan<byte> idData) { if (idData.Length != 16) { throw new ArgumentOutOfRangeException("idData"); } return new ActivityTraceId(System.HexConverter.ToString(idData, System.HexConverter.Casing.Lower)); } public static ActivityTraceId CreateFromUtf8String(ReadOnlySpan<byte> idData) { return new ActivityTraceId(idData); } public static ActivityTraceId CreateFromString(ReadOnlySpan<char> idData) { if (idData.Length != 32 || !IsLowerCaseHexAndNotAllZeros(idData)) { throw new ArgumentOutOfRangeException("idData"); } return new ActivityTraceId(idData.ToString()); } public string ToHexString() { return _hexString ?? "00000000000000000000000000000000"; } public override string ToString() { return ToHexString(); } public static bool operator ==(ActivityTraceId traceId1, ActivityTraceId traceId2) { return traceId1._hexString == traceId2._hexString; } public static bool operator !=(ActivityTraceId traceId1, ActivityTraceId traceId2) { return traceId1._hexString != traceId2._hexString; } public bool Equals(ActivityTraceId traceId) { return _hexString == traceId._hexString; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ActivityTraceId activityTraceId) { return _hexString == activityTraceId._hexString; } return false; } public override int GetHashCode() { return ToHexString().GetHashCode(); } private ActivityTraceId(ReadOnlySpan<byte> idData) { if (idData.Length != 32) { throw new ArgumentOutOfRangeException("idData"); } Span<ulong> span = stackalloc ulong[2]; if (!Utf8Parser.TryParse(idData.Slice(0, 16), out span[0], out int bytesConsumed, 'x')) { _hexString = CreateRandom()._hexString; return; } if (!Utf8Parser.TryParse(idData.Slice(16, 16), out span[1], out bytesConsumed, 'x')) { _hexString = CreateRandom()._hexString; return; } if (BitConverter.IsLittleEndian) { span[0] = BinaryPrimitives.ReverseEndianness(span[0]); span[1] = BinaryPrimitives.ReverseEndianness(span[1]); } _hexString = System.HexConverter.ToString(MemoryMarshal.AsBytes(span), System.HexConverter.Casing.Lower); } public void CopyTo(Span<byte> destination) { SetSpanFromHexChars(ToHexString().AsSpan(), destination); } internal static void SetToRandomBytes(Span<byte> outBytes) { RandomNumberGenerator current = RandomNumberGenerator.Current; Unsafe.WriteUnaligned(ref outBytes[0], current.Next()); if (outBytes.Length == 16) { Unsafe.WriteUnaligned(ref outBytes[8], current.Next()); } } internal static void SetSpanFromHexChars(ReadOnlySpan<char> charData, Span<byte> outBytes) { for (int i = 0; i < outBytes.Length; i++) { outBytes[i] = HexByteFromChars(charData[i * 2], charData[i * 2 + 1]); } } internal static byte HexByteFromChars(char char1, char char2) { int num = System.HexConverter.FromLowerChar(char1); int num2 = System.HexConverter.FromLowerChar(char2); if ((num | num2) == 255) { throw new ArgumentOutOfRangeException("idData"); } return (byte)((num << 4) | num2); } internal static bool IsLowerCaseHexAndNotAllZeros(ReadOnlySpan<char> idData) { bool result = false; for (int i = 0; i < idData.Length; i++) { char c = idData[i]; if (!System.HexConverter.IsHexLowerChar(c)) { return false; } if (c != '0') { result = true; } } return result; } } public readonly struct ActivitySpanId : IEquatable<ActivitySpanId> { private readonly string _hexString; internal ActivitySpanId(string hexString) { _hexString = hexString; } public unsafe static ActivitySpanId CreateRandom() { ulong num = default(ulong); ActivityTraceId.SetToRandomBytes(new Span<byte>(&num, 8)); return new ActivitySpanId(System.HexConverter.ToString(new ReadOnlySpan<byte>(&num, 8), System.HexConverter.Casing.Lower)); } public static ActivitySpanId CreateFromBytes(ReadOnlySpan<byte> idData) { if (idData.Length != 8) { throw new ArgumentOutOfRangeException("idData"); } return new ActivitySpanId(System.HexConverter.ToString(idData, System.HexConverter.Casing.Lower)); } public static ActivitySpanId CreateFromUtf8String(ReadOnlySpan<byte> idData) { return new ActivitySpanId(idData); } public static ActivitySpanId CreateFromString(ReadOnlySpan<char> idData) { if (idData.Length != 16 || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData)) { throw new ArgumentOutOfRangeException("idData"); } return new ActivitySpanId(idData.ToString()); } public string ToHexString() { return _hexString ?? "0000000000000000"; } public override string ToString() { return ToHexString(); } public static bool operator ==(ActivitySpanId spanId1, ActivitySpanId spandId2) { return spanId1._hexString == spandId2._hexString; } public static bool operator !=(ActivitySpanId spanId1, ActivitySpanId spandId2) { return spanId1._hexString != spandId2._hexString; } public bool Equals(ActivitySpanId spanId) { return _hexString == spanId._hexString; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ActivitySpanId activitySpanId) { return _hexString == activitySpanId._hexString; } return false; } public override int GetHashCode() { return ToHexString().GetHashCode(); } private unsafe ActivitySpanId(ReadOnlySpan<byte> idData) { if (idData.Length != 16) { throw new ArgumentOutOfRangeException("idData"); } if (!Utf8Parser.TryParse(idData, out ulong value, out int _, 'x')) { _hexString = CreateRandom()._hexString; return; } if (BitConverter.IsLittleEndian) { value = BinaryPrimitives.ReverseEndianness(value); } _hexString = System.HexConverter.ToString(new ReadOnlySpan<byte>(&value, 8), System.HexConverter.Casing.Lower); } public void CopyTo(Span<byte> destination) { ActivityTraceId.SetSpanFromHexChars(ToHexString().AsSpan(), destination); } } public enum ActivityStatusCode { Unset, Ok, Error } public class ActivityTagsCollection : IDictionary<string, object?>, ICollection<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable { public struct Enumerator : IEnumerator<KeyValuePair<string, object?>>, IEnumerator, IDisposable { private List<KeyValuePair<string, object>>.Enumerator _enumerator; public KeyValuePair<string, object?> Current => _enumerator.Current; object IEnumerator.Current => ((IEnumerator)_enumerator).Current; internal Enumerator(List<KeyValuePair<string, object>> list) { _enumerator = list.GetEnumerator(); } public void Dispose() { _enumerator.Dispose(); } public bool MoveNext() { return _enumerator.MoveNext(); } void IEnumerator.Reset() { ((IEnumerator)_enumerator).Reset(); } } private readonly List<KeyValuePair<string, object>> _list = new List<KeyValuePair<string, object>>(); public object? this[string key] { get { int num = FindIndex(key); if (num >= 0) { return _list[num].Value; } return null; } set { if (key == null) { throw new ArgumentNullException("key"); } int num = FindIndex(key); if (value == null) { if (num >= 0) { _list.RemoveAt(num); } } else if (num >= 0) { _list[num] = new KeyValuePair<string, object>(key, value); } else { _list.Add(new KeyValuePair<string, object>(key, value)); } } } public ICollection<string> Keys { get { List<string> list = new List<string>(_list.Count); foreach (KeyValuePair<string, object> item in _list) { list.Add(item.Key); } return list; } } public ICollection<object?> Values { get { List<object> list = new List<object>(_list.Count); foreach (KeyValuePair<string, object> item in _list) { list.Add(item.Value); } return list; } } public bool IsReadOnly => false; public int Count => _list.Count; public ActivityTagsCollection() { } public ActivityTagsCollection(IEnumerable<KeyValuePair<string, object?>> list) { if (list == null) { throw new ArgumentNullException("list"); } foreach (KeyValuePair<string, object> item in list) { if (item.Key != null) { this[item.Key] = item.Value; } } } public void Add(string key, object? value) { if (key == null) { throw new ArgumentNullException("key"); } int num = FindIndex(key); if (num >= 0) { throw new InvalidOperationException(System.SR.Format(System.SR.KeyAlreadyExist, key)); } _list.Add(new KeyValuePair<string, object>(key, value)); } public void Add(KeyValuePair<string, object?> item) { if (item.Key == null) { throw new ArgumentNullException("item"); } int num = FindIndex(item.Key); if (num >= 0) { throw new InvalidOperationException(System.SR.Format(System.SR.KeyAlreadyExist, item.Key)); } _list.Add(item); } public void Clear() { _list.Clear(); } public bool Contains(KeyValuePair<string, object?> item) { return _list.Contains(item); } public bool ContainsKey(string key) { return FindIndex(key) >= 0; } public void CopyTo(KeyValuePair<string, object?>[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { return new Enumerator(_list); } public Enumerator GetEnumerator() { return new Enumerator(_list); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_list); } public bool Remove(string key) { if (key == null) { throw new ArgumentNullException("key"); } int num = FindIndex(key); if (num >= 0) { _list.RemoveAt(num); return true; } return false; } public bool Remove(KeyValuePair<string, object?> item) { return _list.Remove(item); } public bool TryGetValue(string key, out object? value) { int num = FindIndex(key); if (num >= 0) { value = _list[num].Value; return true; } value = null; return false; } private int FindIndex(string key) { for (int i = 0; i < _list.Count; i++) { if (_list[i].Key == key) { return i; } } return -1; } } public readonly struct ActivityContext : IEquatable<ActivityContext> { public ActivityTraceId TraceId { get; } public ActivitySpanId SpanId { get; } public ActivityTraceFlags TraceFlags { get; } public string? TraceState { get; } public bool IsRemote { get; } public ActivityContext(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags traceFlags, string? traceState = null, bool isRemote = false) { TraceId = traceId; SpanId = spanId; TraceFlags = traceFlags; TraceState = traceState; IsRemote = isRemote; } public static bool TryParse(string? traceParent, string? traceState, bool isRemote, out ActivityContext context) { if (traceParent == null) { context = default(ActivityContext); return false; } return Activity.TryConvertIdToContext(traceParent, traceState, isRemote, out context); } public static bool TryParse(string? traceParent, string? traceState, out ActivityContext context) { return TryParse(traceParent, traceState, isRemote: false, out context); } public static ActivityContext Parse(string traceParent, string? traceState) { if (traceParent == null) { throw new ArgumentNullException("traceParent"); } if (!Activity.TryConvertIdToContext(traceParent, traceState, isRemote: false, out var context)) { throw new ArgumentException(System.SR.InvalidTraceParent); } return context; } public bool Equals(ActivityContext value) { if (SpanId.Equals(value.SpanId) && TraceId.Equals(value.TraceId) && TraceFlags == value.TraceFlags && TraceState == value.TraceState) { return IsRemote == value.IsRemote; } return false; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is ActivityContext value)) { return false; } return Equals(value); } public static bool operator ==(ActivityContext left, ActivityContext right) { return left.Equals(right); } public static bool operator !=(ActivityContext left, ActivityContext right) { return !(left == right); } public override int GetHashCode() { if (this == default(ActivityContext)) { return 0; } int num = 5381; num = (num << 5) + num + TraceId.GetHashCode(); num = (num << 5) + num + SpanId.GetHashCode(); num = (int)((num << 5) + num + TraceFlags); return (num << 5) + num + ((TraceState != null) ? TraceState.GetHashCode() : 0); } } public readonly struct ActivityCreationOptions<T> { private readonly ActivityTagsCollection _samplerTags; private readonly ActivityContext _context; private readonly string _traceState; public ActivitySource Source { get; } public string Name { get; } public ActivityKind Kind { get; } public T Parent { get; } public IEnumerable<KeyValuePair<string, object?>>? Tags { get; } public IEnumerable<ActivityLink>? Links { get; } public ActivityTagsCollection SamplingTags { get { if (_samplerTags == null) { Unsafe.AsRef(in _samplerTags) = new ActivityTagsCollection(); } return _samplerTags; } } public ActivityTraceId TraceId { get { if (Parent is ActivityContext && IdFormat == ActivityIdFormat.W3C && _context == default(ActivityContext)) { ActivityTraceId traceId = Activity.TraceIdGenerator?.Invoke() ?? ActivityTraceId.CreateRandom(); Unsafe.AsRef(in _context) = new ActivityContext(traceId, default(ActivitySpanId), ActivityTraceFlags.None); } return _context.TraceId; } } public string? TraceState { get { return _traceState; } init { _traceState = value; } } internal ActivityIdFormat IdFormat { get; } internal ActivityCreationOptions(ActivitySource source, string name, T parent, ActivityKind kind, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, ActivityIdFormat idFormat) { Source = source; Name = name; Kind = kind; Parent = parent; Tags = tags; Links = links; IdFormat = idFormat; if (IdFormat == ActivityIdFormat.Unknown && Activity.ForceDefaultIdFormat) { IdFormat = Activity.DefaultIdFormat; } _samplerTags = null; _traceState = null; if (parent is ActivityContext) { object obj = parent; ActivityContext activityContext = (ActivityContext)((obj is ActivityContext) ? obj : null); if (activityContext != default(ActivityContext)) { _context = activityContext; if (IdFormat == ActivityIdFormat.Unknown) { IdFormat = ActivityIdFormat.W3C; } _traceState = activityContext.TraceState; return; } } if ((object)parent is string traceParent) { if (IdFormat != ActivityIdFormat.Hierarchical) { if (ActivityContext.TryParse(traceParent, null, out _context)) { IdFormat = ActivityIdFormat.W3C; } if (IdFormat == ActivityIdFormat.Unknown) { IdFormat = ActivityIdFormat.Hierarchical; } } else { _context = default(ActivityContext); } } else { _context = default(ActivityContext); if (IdFormat == ActivityIdFormat.Unknown) { IdFormat = ((Activity.Current != null) ? Activity.Current.IdFormat : Activity.DefaultIdFormat); } } } internal void SetTraceState(string traceState) { Unsafe.AsRef(in _traceState) = traceState; } internal ActivityTagsCollection GetSamplingTags() { return _samplerTags; } internal ActivityContext GetContext() { return _context; } } public enum ActivitySamplingResult { None, PropagationData, AllData, AllDataAndRecorded } public readonly struct ActivityEvent { private static readonly IEnumerable<KeyValuePair<string, object>> s_emptyTags = Array.Empty<KeyValuePair<string, object>>(); private readonly Activity.TagsLinkedList _tags; public string Name { get; } public DateTimeOffset Timestamp { get; } public IEnumerable<KeyValuePair<string, object?>> Tags { get { IEnumerable<KeyValuePair<string, object>> tags = _tags; return tags ?? s_emptyTags; } } public ActivityEvent(string name) : this(name, DateTimeOffset.UtcNow) { } public ActivityEvent(string name, DateTimeOffset timestamp = default(DateTimeOffset), ActivityTagsCollection? tags = null) { Name = name ?? string.Empty; Timestamp = ((timestamp != default(DateTimeOffset)) ? timestamp : DateTimeOffset.UtcNow); _tags = ((tags != null && tags.Count > 0) ? new Activity.TagsLinkedList(tags) : null); } public Activity.Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects() { return new Activity.Enumerator<KeyValuePair<string, object>>(_tags?.First); } } public enum ActivityKind { Internal, Server, Client, Producer, Consumer } public readonly struct ActivityLink : IEquatable<ActivityLink> { private readonly Activity.TagsLinkedList _tags; public ActivityContext Context { get; } public IEnumerable<KeyValuePair<string, object?>>? Tags => _tags; public ActivityLink(ActivityContext context, ActivityTagsCollection? tags = null) { Context = context; _tags = ((tags != null && tags.Count > 0) ? new Activity.TagsLinkedList(tags) : null); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ActivityLink value) { return Equals(value); } return false; } public bool Equals(ActivityLink value) { if (Context == value.Context) { return value.Tags == Tags; } return false; } public static bool operator ==(ActivityLink left, ActivityLink right) { return left.Equals(right); } public static bool operator !=(ActivityLink left, ActivityLink right) { return !left.Equals(right); } public Activity.Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects() { return new Activity.Enumerator<KeyValuePair<string, object>>(_tags?.First); } public override int GetHashCode() { if (this == default(ActivityLink)) { return 0; } int num = 5381; num = (num << 5) + num + Context.GetHashCode(); if (Tags != null) { foreach (KeyValuePair<string, object> tag in Tags) { num = (num << 5) + num + tag.Key.GetHashCode(); if (tag.Value != null) { num = (num << 5) + num + tag.Value.GetHashCode(); } } } return num; } } public delegate ActivitySamplingResult SampleActivity<T>(ref ActivityCreationOptions<T> options); public sealed class ActivityListener : IDisposable { public Action<Activity>? ActivityStarted { get; set; } public Action<Activity>? ActivityStopped { get; set; } public Func<ActivitySource, bool>? ShouldListenTo { get; set; } public SampleActivity<string>? SampleUsingParentId { get; set; } public SampleActivity<ActivityContext>? Sample { get; set; } public void Dispose() { ActivitySource.DetachListener(this); } } public sealed class ActivitySource : IDisposable { internal delegate void Function<T, TParent>(T item, ref ActivityCreationOptions<TParent> data, ref ActivitySamplingResult samplingResult, ref ActivityCreationOptions<ActivityContext> dataWithContext); private static readonly SynchronizedList<ActivitySource> s_activeSources = new SynchronizedList<ActivitySource>(); private static readonly SynchronizedList<ActivityListener> s_allListeners = new SynchronizedList<ActivityListener>(); private SynchronizedList<ActivityListener> _listeners; public string Name { get; } public string? Version { get; } public ActivitySource(string name, string? version = "") { Name = name ?? throw new ArgumentNullException("name"); Version = version; s_activeSources.Add(this); if (s_allListeners.Count > 0) { s_allListeners.EnumWithAction(delegate(ActivityListener listener, object source) { Func<ActivitySource, bool> shouldListenTo = listener.ShouldListenTo; if (shouldListenTo != null) { ActivitySource activitySource = (ActivitySource)source; if (shouldListenTo(activitySource)) { activitySource.AddListener(listener); } } }, this); } GC.KeepAlive(DiagnosticSourceEventSource.Log); } public bool HasListeners() { SynchronizedList<ActivityListener> listeners = _listeners; if (listeners != null) { return listeners.Count > 0; } return false; } public Activity? CreateActivity(string name, ActivityKind kind) { return CreateActivity(name, kind, default(ActivityContext), null, null, null, default(DateTimeOffset), startIt: false); } public Activity? CreateActivity(string name, ActivityKind kind, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, ActivityIdFormat idFormat = ActivityIdFormat.Unknown) { return CreateActivity(name, kind, parentContext, null, tags, links, default(DateTimeOffset), startIt: false, idFormat); } public Activity? CreateActivity(string name, ActivityKind kind, string? parentId, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, ActivityIdFormat idFormat = ActivityIdFormat.Unknown) { return CreateActivity(name, kind, default(ActivityContext), parentId, tags, links, default(DateTimeOffset), startIt: false, idFormat); } public Activity? StartActivity([CallerMemberName] string name = "", ActivityKind kind = ActivityKind.Internal) { return CreateActivity(name, kind, default(ActivityContext), null, null, null, default(DateTimeOffset)); } public Activity? StartActivity(string name, ActivityKind kind, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset)) { return CreateActivity(name, kind, parentContext, null, tags, links, startTime); } public Activity? StartActivity(string name, ActivityKind kind, string? parentId, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset)) { return CreateActivity(name, kind, default(ActivityContext), parentId, tags, links, startTime); } public Activity? StartActivity(ActivityKind kind, ActivityContext parentContext = default(ActivityContext), IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset), [CallerMemberName] string name = "") { return CreateActivity(name, kind, parentContext, null, tags, links, startTime); } private Activity CreateActivity(string name, ActivityKind kind, ActivityContext context, string parentId, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, DateTimeOffset startTime, bool startIt = true, ActivityIdFormat idFormat = ActivityIdFormat.Unknown) { SynchronizedList<ActivityListener> listeners = _listeners; if (listeners == null || listeners.Count == 0) { return null; } Activity result2 = null; ActivitySamplingResult samplingResult = ActivitySamplingResult.None; ActivityTagsCollection activityTagsCollection; string traceState; if (parentId != null) { ActivityCreationOptions<string> activityCreationOptions = default(ActivityCreationOptions<string>); ActivityCreationOptions<ActivityContext> dataWithContext2 = default(ActivityCreationOptions<ActivityContext>); activityCreationOptions = new ActivityCreationOptions<string>(this, name, parentId, kind, tags, links, idFormat); if (activityCreationOptions.IdFormat == ActivityIdFormat.W3C) { dataWithContext2 = new ActivityCreationOptions<ActivityContext>(this, name, activityCreationOptions.GetContext(), kind, tags, links, ActivityIdFormat.W3C); } listeners.EnumWithFunc(delegate(ActivityListener listener, ref ActivityCreationOptions<string> data, ref ActivitySamplingResult result, ref ActivityCreationOptions<ActivityContext> dataWithContext) { SampleActivity<string> sampleUsingParentId = listener.SampleUsingParentId; if (sampleUsingParentId != null) { ActivitySamplingResult activitySamplingResult2 = sampleUsingParentId(ref data); dataWithContext.SetTraceState(data.TraceState); if (activitySamplingResult2 > result) { result = activitySamplingResult2; } } else if (data.IdFormat == ActivityIdFormat.W3C) { SampleActivity<ActivityContext> sample2 = listener.Sample; if (sample2 != null) { ActivitySamplingResult activitySamplingResult3 = sample2(ref dataWithContext); data.SetTraceState(dataWithContext.TraceState); if (activitySamplingResult3 > result) { result = activitySamplingResult3; } } } }, ref activityCreationOptions, ref samplingResult, ref dataWithContext2); if (context == default(ActivityContext)) { if (activityCreationOptions.GetContext() != default(ActivityContext)) { context = activityCreationOptions.GetContext(); parentId = null; } else if (dataWithContext2.GetContext() != default(ActivityContext)) { context = dataWithContext2.GetContext(); parentId = null; } } activityTagsCollection = activityCreationOptions.GetSamplingTags(); ActivityTagsCollection samplingTags = dataWithContext2.GetSamplingTags(); if (samplingTags != null) { if (activityTagsCollection == null) { activityTagsCollection = samplingTags; } else { foreach (KeyValuePair<string, object?> item in samplingTags) { activityTagsCollection.Add(item); } } } idFormat = activityCreationOptions.IdFormat; traceState = activityCreationOptions.TraceState; } else { bool flag = context == default(ActivityContext) && Activity.Current != null; ActivityCreationOptions<ActivityContext> data2 = new ActivityCreationOptions<ActivityContext>(this, name, flag ? Activity.Current.Context : context, kind, tags, links, idFormat); listeners.EnumWithFunc(delegate(ActivityListener listener, ref ActivityCreationOptions<ActivityContext> data, ref ActivitySamplingResult result, ref ActivityCreationOptions<ActivityContext> unused) { SampleActivity<ActivityContext> sample = listener.Sample; if (sample != null) { ActivitySamplingResult activitySamplingResult = sample(ref data); if (activitySamplingResult > result) { result = activitySamplingResult; } } }, ref data2, ref samplingResult, ref data2); if (!flag) { context = data2.GetContext(); } activityTagsCollection = data2.GetSamplingTags(); idFormat = data2.IdFormat; traceState = data2.TraceState; } if (samplingResult != 0) { result2 = Activity.Create(this, name, kind, parentId, context, tags, links, startTime, activityTagsCollection, samplingResult, startIt, idFormat, traceState); } return result2; } public void Dispose() { _listeners = null; s_activeSources.Remove(this); } public static void AddActivityListener(ActivityListener listener) { if (listener == null) { throw new ArgumentNullException("listener"); } if (!s_allListeners.AddIfNotExist(listener)) { return; } s_activeSources.EnumWithAction(delegate(ActivitySource source, object obj) { Func<ActivitySource, bool> shouldListenTo = ((ActivityListener)obj).ShouldListenTo; if (shouldListenTo != null && shouldListenTo(source)) { source.AddListener((ActivityListener)obj); } }, listener); } internal void AddListener(ActivityListener listener) { if (_listeners == null) { Interlocked.CompareExchange(ref _listeners, new SynchronizedList<ActivityListener>(), null); } _listeners.AddIfNotExist(listener); } internal static void DetachListener(ActivityListener listener) { s_allListeners.Remove(listener); s_activeSources.EnumWithAction(delegate(ActivitySource source, object obj) { source._listeners?.Remove((ActivityListener)obj); }, listener); } internal void NotifyActivityStart(Activity activity) { SynchronizedList<ActivityListener> listeners = _listeners; if (listeners != null && listeners.Count > 0) { listeners.EnumWithAction(delegate(ActivityListener listener, object obj) { listener.ActivityStarted?.Invoke((Activity)obj); }, activity); } } internal void NotifyActivityStop(Activity activity) { SynchronizedList<ActivityListener> listeners = _listeners; if (listeners != null && listeners.Count > 0) { listeners.EnumWithAction(delegate(ActivityListener listener, object obj) { listener.ActivityStopped?.Invoke((Activity)obj); }, activity); } } } internal sealed class SynchronizedList<T> { private readonly List<T> _list; private uint _version; public int Count => _list.Count; public SynchronizedList() { _list = new List<T>(); } public void Add(T item) { lock (_list) { _list.Add(item); _version++; } } public bool AddIfNotExist(T item) { lock (_list) { if (!_list.Contains(item)) { _list.Add(item); _version++; return true; } return false; } } public bool Remove(T item) { lock (_list) { if (_list.Remove(item)) { _version++; return true; } return false; } } public void EnumWithFunc<TParent>(ActivitySource.Function<T, TParent> func, ref ActivityCreationOptions<TParent> data, ref ActivitySamplingResult samplingResult, ref ActivityCreationOptions<ActivityContext> dataWithContext) { uint version = _version; int num = 0; while (num < _list.Count) { T item; lock (_list) { if (version != _version) { version = _version; num = 0; continue; } item = _list[num]; num++; goto IL_004f; } IL_004f: func(item, ref data, ref samplingResult, ref dataWithContext); } } public void EnumWithAction(Action<T, object> action, object arg) { uint version = _version; int num = 0; while (num < _list.Count) { T arg2; lock (_list) { if (version != _version) { version = _version; num = 0; continue; } arg2 = _list[num]; num++; goto IL_004f; } IL_004f: action(arg2, arg); } } } public abstract class DiagnosticSource { internal const string WriteRequiresUnreferencedCode = "The type of object being written to DiagnosticSource cannot be discovered statically."; internal const string WriteOfTRequiresUnreferencedCode = "Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed."; [RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")] public abstract void Write(string name, object? value); [RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")] public void Write<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name, T value) { Write(name, (object?)value); } public abstract bool IsEnabled(string name); public virtual bool IsEnabled(string name, object? arg1, object? arg2 = null) { return IsEnabled(name); } [RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")] public Activity StartActivity(Activity activity, object? args) { activity.Start(); Write(activity.OperationName + ".Start", args); return activity; } [RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")] public Activity StartActivity<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(Activity activity, T args) { return StartActivity(activity, (object?)args); } [RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")] public void StopActivity(Activity activity, object? args) { if (activity.Duration == TimeSpan.Zero) { activity.SetEndTime(Activity.GetUtcNow()); } Write(activity.OperationName + ".Stop", args); activity.Stop(); } [RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")] public void StopActivity<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(Activity activity, T args) { StopActivity(activity, (object?)args); } public virtual void OnActivityImport(Activity activity, object? payload) { } public virtual void OnActivityExport(Activity activity, object? payload) { } } public class DiagnosticListener : DiagnosticSource, IObservable<KeyValuePair<string, object?>>, IDisposable { private sealed class DiagnosticSubscription : IDisposable { internal IObserver<KeyValuePair<string, object>> Observer; internal Predicate<string> IsEnabled1Arg; internal Func<string, object, object, bool> IsEnabled3Arg; internal Action<Activity, object> OnActivityImport; internal Action<Activity, object> OnActivityExport; internal DiagnosticListener Owner; internal DiagnosticSubscription Next; public void Dispose() { DiagnosticSubscription subscriptions; DiagnosticSubscription value; do { subscriptions = Owner._subscriptions; value = Remove(subscriptions, this); } while (Interlocked.CompareExchange(ref Owner._subscriptions, value, subscriptions) != subscriptions); } private static DiagnosticSubscription Remove(DiagnosticSubscription subscriptions, DiagnosticSubscription subscription) { if (subscriptions == null) { return null; } if (subscriptions.Observer == subscription.Observer && subscriptions.IsEnabled1Arg == subscription.IsEnabled1Arg && subscriptions.IsEnabled3Arg == subscription.IsEnabled3Arg) { return subscriptions.Next; } return new DiagnosticSubscription { Observer = subscriptions.Observer, Owner = subscriptions.Owner, IsEnabled1Arg = subscriptions.IsEnabled1Arg, IsEnabled3Arg = subscriptions.IsEnabled3Arg, Next = Remove(subscriptions.Next, subscription) }; } } private sealed class AllListenerObservable : IObservable<DiagnosticListener> { internal sealed class AllListenerSubscription : IDisposable { private readonly AllListenerObservable _owner; internal readonly IObserver<DiagnosticListener> Subscriber; internal AllListenerSubscription Next; internal AllListenerSubscription(AllListenerObservable owner, IObserver<DiagnosticListener> subscriber, AllListenerSubscription next) { _owner = owner; Subscriber = subscriber; Next = next; } public void Dispose() { if (_owner.Remove(this)) { Subscriber.OnCompleted(); } } } private AllListenerSubscription _subscriptions; public IDisposable Subscribe(IObserver<DiagnosticListener> observer) { lock (s_allListenersLock) { for (DiagnosticListener diagnosticListener = s_allListeners; diagnosticListener != null; diagnosticListener = diagnosticListener._next) { observer.OnNext(diagnosticListener); } _subscriptions = new AllListenerSubscription(this, observer, _subscriptions); return _subscriptions; } } internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener) { for (AllListenerSubscription allListenerSubscription = _subscriptions; allListenerSubscription != null; allListenerSubscription = allListenerSubscription.Next) { allListenerSubscription.Subscriber.OnNext(diagnosticListener); } } private bool Remove(AllListenerSubscription subscription) { lock (s_allListenersLock) { if (_subscriptions == subscription) { _subscriptions = subscription.Next; return true; } if (_subscriptions != null) { AllListenerSubscription allListenerSubscription = _subscriptions; while (allListenerSubscription.Next != null) { if (allListenerSubscription.Next == subscription) { allListenerSubscription.Next = allListenerSubscription.Next.Next; return true; } allListenerSubscription = allListenerSubscription.Next; } } return false; } } } private volatile DiagnosticSubscription _subscriptions; private DiagnosticListener _next; private bool _disposed; private static DiagnosticListener s_allListeners; private static volatile AllListenerObservable s_allListenerObservable; private static readonly object s_allListenersLock = new object(); public static IObservable<DiagnosticListener> AllListeners => s_allListenerObservable ?? Interlocked.CompareExchange(ref s_allListenerObservable, new AllListenerObservable(), null) ?? s_allListenerObservable; public string Name { get; private set; } public override void OnActivityImport(Activity activity, object? payload) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { diagnosticSubscription.OnActivityImport?.Invoke(activity, payload); } } public override void OnActivityExport(Activity activity, object? payload) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { diagnosticSubscription.OnActivityExport?.Invoke(activity, payload); } } public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer, Func<string, object?, object?, bool>? isEnabled, Action<Activity, object?>? onActivityImport = null, Action<Activity, object?>? onActivityExport = null) { if (isEnabled != null) { return SubscribeInternal(observer, (string name) => IsEnabled(name, null), isEnabled, onActivityImport, onActivityExport); } return SubscribeInternal(observer, null, null, onActivityImport, onActivityExport); } public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer, Predicate<string>? isEnabled) { if (isEnabled == null) { return SubscribeInternal(observer, null, null, null, null); } Predicate<string> localIsEnabled = isEnabled; return SubscribeInternal(observer, isEnabled, (string name, object arg1, object arg2) => localIsEnabled(name), null, null); } public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer, Func<string, object?, object?, bool>? isEnabled) { if (isEnabled != null) { return SubscribeInternal(observer, (string name) => IsEnabled(name, null), isEnabled, null, null); } return SubscribeInternal(observer, null, null, null, null); } public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer) { return SubscribeInternal(observer, null, null, null, null); } public DiagnosticListener(string name) { Name = name; lock (s_allListenersLock) { s_allListenerObservable?.OnNewDiagnosticListener(this); _next = s_allListeners; s_allListeners = this; } GC.KeepAlive(DiagnosticSourceEventSource.Log); } public virtual void Dispose() { lock (s_allListenersLock) { if (_disposed) { return; } _disposed = true; if (s_allListeners == this) { s_allListeners = s_allListeners._next; } else { for (DiagnosticListener next = s_allListeners; next != null; next = next._next) { if (next._next == this) { next._next = _next; break; } } } _next = null; } DiagnosticSubscription location = null; Interlocked.Exchange(ref location, _subscriptions); while (location != null) { location.Observer.OnCompleted(); location = location.Next; } } public override string ToString() { return Name ?? string.Empty; } public bool IsEnabled() { return _subscriptions != null; } public override bool IsEnabled(string name) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { if (diagnosticSubscription.IsEnabled1Arg == null || diagnosticSubscription.IsEnabled1Arg(name)) { return true; } } return false; } public override bool IsEnabled(string name, object? arg1, object? arg2 = null) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { if (diagnosticSubscription.IsEnabled3Arg == null || diagnosticSubscription.IsEnabled3Arg(name, arg1, arg2)) { return true; } } return false; } [RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")] public override void Write(string name, object? value) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { diagnosticSubscription.Observer.OnNext(new KeyValuePair<string, object>(name, value)); } } private DiagnosticSubscription SubscribeInternal(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled1Arg, Func<string, object, object, bool> isEnabled3Arg, Action<Activity, object> onActivityImport, Action<Activity, object> onActivityExport) { if (_disposed) { return new DiagnosticSubscription { Owner = this }; } DiagnosticSubscription diagnosticSubscription = new DiagnosticSubscription { Observer = observer, IsEnabled1Arg = isEnabled1Arg, IsEnabled3Arg = isEnabled3Arg, OnActivityImport = onActivityImport, OnActivityExport = onActivityExport, Owner = this, Next = _subscriptions }; while (Interlocked.CompareExchange(ref _subscriptions, diagnosticSubscription, diagnosticSubscription.Next) != diagnosticSubscription.Next) { diagnosticSubscription.Next = _subscriptions; } return diagnosticSubscription; } } [EventSource(Name = "Microsoft-Diagnostics-DiagnosticSource")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2113:ReflectionToRequiresUnreferencedCode", Justification = "In EventSource, EnsureDescriptorsInitialized's use of GetType preserves methods on Delegate and MulticastDelegate because the nested type OverrideEventProvider's base type EventProvider defines a delegate. This includes Delegate and MulticastDelegate methods which require unreferenced code, but EnsureDescriptorsInitialized does not access these members and is safe to call.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2115:ReflectionToDynamicallyAccessedMembers", Justification = "In EventSource, EnsureDescriptorsInitialized's use of GetType preserves methods on Delegate and MulticastDelegate because the nested type OverrideEventProvider's base type EventProvider defines a delegate. This includes Delegate and MulticastDelegate methods which have dynamically accessed members requirements, but EnsureDescriptorsInitialized does not access these members and is safe to call.")] internal sealed class DiagnosticSourceEventSource : EventSource { public static class Keywords { public const EventKeywords Messages = (EventKeywords)1L; public const EventKeywords Events = (EventKeywords)2L; public const EventKeywords IgnoreShortCutKeywords = (EventKeywords)2048L; public const EventKeywords AspNetCoreHosting = (EventKeywords)4096L; public const EventKeywords EntityFrameworkCoreCommands = (EventKeywords)8192L; } [Flags] internal enum ActivityEvents { None = 0, ActivityStart = 1, ActivityStop = 2, All = 3 } internal sealed class FilterAndTransform { public FilterAndTransform Next; internal const string c_ActivitySourcePrefix = "[AS]"; private IDisposable _diagnosticsListenersSubscription; private Subscriptions _liveSubscriptions; private readonly bool _noImplicitTransforms; private ImplicitTransformEntry _firstImplicitTransformsEntry; private ConcurrentDictionary<Type, TransformSpec> _implicitTransformsTable; private readonly TransformSpec _explicitTransforms; private readonly DiagnosticSourceEventSource _eventSource; internal string SourceName { get; set; } internal string ActivityName { get; set; } internal ActivityEvents Events { get; set; } internal ActivitySamplingResult SamplingResult { get; set; } public static void CreateFilterAndTransformList(ref FilterAndTransform specList, string filterAndPayloadSpecs, DiagnosticSourceEventSource eventSource) { DestroyFilterAndTransformList(ref specList, eventSource); if (filterAndPayloadSpecs == null) { filterAndPayloadSpecs = ""; } int num = filterAndPayloadSpecs.Length; while (true) { if (0 < num && char.IsWhiteSpace(filterAndPayloadSpecs[num - 1])) { num--; continue; } int num2 = filterAndPayloadSpecs.LastIndexOf('\n', num - 1, num); int i = 0; if (0 <= num2) { i = num2 + 1; } for (; i < num && char.IsWhiteSpace(filterAndPayloadSpecs[i]); i++) { } if (IsActivitySourceEntry(filterAndPayloadSpecs, i, num)) { AddNewActivitySourceTransform(filterAndPayloadSpecs, i, num, eventSource); } else { specList = new FilterAndTransform(filterAndPayloadSpecs, i, num, eventSource, specList); } num = num2; if (num < 0) { break; } } if (eventSource._activitySourceSpecs != null) { NormalizeActivitySourceSpecsList(eventSource); CreateActivityListener(eventSource); } } public static void DestroyFilterAndTransformList(ref FilterAndTransform specList, DiagnosticSourceEventSource eventSource) { eventSource._activityListener?.Dispose(); eventSource._activityListener = null; eventSource._activitySourceSpecs = null; FilterAndTransform filterAndTransform = specList; specList = null; while (filterAndTransform != null) { filterAndTransform.Dispose(); filterAndTransform = filterAndTransform.Next; } } public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, DiagnosticSourceEventSource eventSource, FilterAndTransform next) { FilterAndTransform filterAndTransform = this; Next = next; _eventSource = eventSource; string listenerNameFilter = null; string eventNameFilter = null; string text = null; int num = startIdx; int num2 = endIdx; int num3 = filterAndPayloadSpec.IndexOf(':', startIdx, endIdx - startIdx); if (0 <= num3) { num2 = num3; num = num3 + 1; } int num4 = filterAndPayloadSpec.IndexOf('/', startIdx, num2 - startIdx); if (0 <= num4) { listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, num4 - startIdx); int num5 = filterAndPayloadSpec.IndexOf('@', num4 + 1, num2 - num4 - 1); if (0 <= num5) { text = filterAndPayloadSpec.Substring(num5 + 1, num2 - num5 - 1); eventNameFilter = filterAndPayloadSpec.Substring(num4 + 1, num5 - num4 - 1); } else { eventNameFilter = filterAndPayloadSpec.Substring(num4 + 1, num2 - num4 - 1); } } else if (startIdx < num2) { listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, num2 - startIdx); } _eventSource.Message("DiagnosticSource: Enabling '" + (listenerNameFilter ?? "*") + "/" + (eventNameFilter ?? "*") + "'"); if (num < endIdx && filterAndPayloadSpec[num] == '-') { _eventSource.Message("DiagnosticSource: suppressing implicit transforms."); _noImplicitTransforms = true; num++; } if (num < endIdx) { while (true) { int num6 = num; int num7 = filterAndPayloadSpec.LastIndexOf(';', endIdx - 1, endIdx - num); if (0 <= num7) { num6 = num7 + 1; } if (num6 < endIdx) { if (_eventSource.IsEnabled(EventLevel.Informational, (EventKeywords)1L)) { _eventSource.Message("DiagnosticSource: Parsing Explicit Transform '" + filterAndPayloadSpec.Substring(num6, endIdx - num6) + "'"); } _explicitTransforms = new TransformSpec(filterAndPayloadSpec, num6, endIdx, _explicitTransforms); } if (num == num6) { break; } endIdx = num7; } } Action<string, string, IEnumerable<KeyValuePair<string, string>>> writeEvent = null; if (text != null && text.Contains("Activity")) { writeEvent = text switch { "Activity1Start" => _eventSource.Activity1Start, "Activity1Stop" => _eventSource.Activity1Stop, "Activity2Start" => _eventSource.Activity2Start, "Activity2Stop" => _eventSource.Activity2Stop, "RecursiveActivity1Start" => _eventSource.RecursiveActivity1Start, "RecursiveActivity1Stop" => _eventSource.RecursiveActivity1Stop, _ => null, }; if (writeEvent == null) { _eventSource.Message("DiagnosticSource: Could not find Event to log Activity " + text); } } if (writeEvent == null) { writeEvent = _eventSource.Event; } _diagnosticsListenersSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(delegate(DiagnosticListener newListener) { if (listenerNameFilter == null || listenerNameFilter == newListener.Name) { filterAndTransform._eventSource.NewDiagnosticListener(newListener.Name); Predicate<string> isEnabled = null; if (eventNameFilter != null) { isEnabled = (string eventName) => eventNameFilter == eventName; } IDisposable subscription = newListener.Subscribe(new CallbackObserver<KeyValuePair<string, object>>(OnEventWritten), isEnabled); filterAndTransform._liveSubscriptions = new Subscriptions(subscription, filterAndTransform._liveSubscriptions); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "DiagnosticSource.Write is marked with RequiresUnreferencedCode.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2119", Justification = "DAM on EventSource references this compiler-generated local function which calls a method that requires unreferenced code. EventSource will not access this local function.")] void OnEventWritten(KeyValuePair<string, object> evnt) { if (eventNameFilter == null || !(eventNameFilter != evnt.Key)) { List<KeyValuePair<string, string>> arg = filterAndTransform.Morph(evnt.Value); string key = evnt.Key; writeEvent(newListener.Name, key, arg); } } })); } internal FilterAndTransform(string filterAndPayloadSpec, int endIdx, int colonIdx, string activitySourceName, string activityName, ActivityEvents events, ActivitySamplingResult samplingResult, DiagnosticSourceEventSource eventSource) { _eventSource =
plugins/System.Memory.dll
Decompiled 2 hours 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.Runtime.Versioning; 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: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: CLSCompliant(true)] [assembly: AssemblyDefaultAlias("System.Memory")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("System.Memory")] [assembly: AssemblyFileVersion("4.600.325.20307")] [assembly: AssemblyInformationalVersion("4.6.3+f62ca0009b038cab4725a720f386623a969d73ad")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Memory")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/maintenance-packages")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.2.0")] [module: UnverifiableCode] [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] 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 RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Memory { internal static class SR { } } namespace System { [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)); } } } internal struct MutableDecimal { public uint Flags; public uint High; public uint Low; public uint Mid; private const uint SignMask = 2147483648u; private const uint ScaleMask = 16711680u; private const int ScaleShift = 16; public bool IsNegative { get { return (Flags & 0x80000000u) != 0; } set { Flags = (Flags & 0x7FFFFFFFu) | (value ? 2147483648u : 0u); } } public int Scale { get { return (byte)(Flags >> 16); } set { Flags = (Flags & 0xFF00FFFFu) | (uint)(value << 16); } } } internal struct NUInt { private unsafe readonly void* _value; private unsafe NUInt(uint value) { _value = (void*)value; } private unsafe NUInt(ulong value) { _value = (void*)value; } public static implicit operator NUInt(uint value) { return new NUInt(value); } public unsafe static implicit operator IntPtr(NUInt value) { return (IntPtr)value._value; } public static explicit operator NUInt(int value) { return new NUInt((uint)value); } public unsafe static explicit operator void*(NUInt value) { return value._value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static NUInt operator *(NUInt left, NUInt right) { if (sizeof(IntPtr) != 4) { return new NUInt((ulong)left._value * (ulong)right._value); } return new NUInt((uint)((int)left._value * (int)right._value)); } } 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(); } } [StructLayout(LayoutKind.Sequential)] internal sealed class Pinnable<T> { public T Data; } [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); } } 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); } } [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; ref TComparable reference = ref comparable; TComparable val = default(TComparable); if (val == null) { val = reference; reference = ref val; } int num4 = reference.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 (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) { continue; } goto IL_0254; } if (Vector.IsHardwareAccelerated && (void*)intPtr != null) { intPtr2 = (IntPtr)((int)(void*)intPtr & ~(Vector<byte>.Count - 1)); Vector<byte> vector = GetVector(value); for (; (nuint)(void*)intPtr2 > (nuint)(Vector<byte>.Count - 1); intPtr2 -= Vector<byte>.Count) { Vector<byte> vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr - Vector<byte>.Count))); if (Vector<byte>.Zero.Equals(vector2)) { intPtr -= Vector<byte>.Count; continue; } return (int)intPtr - Vector<byte>.Count + LocateLastFoundByte(vector2); } if ((void*)intPtr != null) { intPtr2 = intPtr; continue; } } return -1; IL_0254: return (int)(void*)intPtr; IL_026a: return (int)(void*)(intPtr + 2); IL_0278: return (int)(void*)(intPtr + 3); IL_025c: return (int)(void*)(intPtr + 1); } return (int)(void*)(intPtr + 7); } public unsafe static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, 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; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2) { goto IL_02ff; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2) { goto IL_0307; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2) { goto IL_0315; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); if (value0 == num2 || value1 == num2) { break; } intPtr += 8; continue; } return (int)(void*)(intPtr + 6); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 4); } goto IL_0323; } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2) { goto IL_02ff; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2) { goto IL_0307; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2) { goto IL_0315; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 == num2 || value1 == num2) { goto IL_0323; } intPtr += 4; } while ((void*)intPtr2 != null) { intPtr2 -= 1; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 != num2 && value1 != num2) { intPtr += 1; continue; } goto IL_02ff; } if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) { intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector<byte>.Count - 1)); Vector<byte> vector = GetVector(value0); Vector<byte> vector2 = GetVector(value1); for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector<byte>.Count) { Vector<byte> left = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr)); Vector<byte> vector3 = Vector.BitwiseOr(Vector.Equals(left, vector), Vector.Equals(left, vector2)); if (!Vector<byte>.Zero.Equals(vector3)) { return (int)(void*)intPtr + LocateFirstFoundByte(vector3); } } if ((int)(void*)intPtr < length) { intPtr2 = (IntPtr)(length - (int)(void*)intPtr); continue; } } return -1; IL_02ff: return (int)(void*)intPtr; IL_0315: return (int)(void*)(intPtr + 2); IL_0307: return (int)(void*)(intPtr + 1); IL_0323: return (int)(void*)(intPtr + 3); } return (int)(void*)(intPtr + 7); } public unsafe static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, 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; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_0393; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_039b; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_03a9; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.A
plugins/System.Runtime.CompilerServices.Unsafe.dll
Decompiled 2 hours agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Microsoft.CodeAnalysis; [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: CLSCompliant(false)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyFileVersion("6.100.225.20307")] [assembly: AssemblyInformationalVersion("6.1.2")] [assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyVersion("6.0.0.0")] namespace System.Runtime.CompilerServices { public static class Unsafe { [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T Read<T>(void* source) { return Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T ReadUnaligned<T>(void* source) { return Unsafe.ReadUnaligned<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T ReadUnaligned<T>(ref byte source) { return Unsafe.ReadUnaligned<T>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Write<T>(void* destination, T value) { Unsafe.Write(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void WriteUnaligned<T>(void* destination, T value) { Unsafe.WriteUnaligned(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void WriteUnaligned<T>(ref byte destination, T value) { Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(void* destination, ref T source) { Unsafe.Write(destination, source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(ref T destination, void* source) { destination = Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* AsPointer<T>(ref T value) { return Unsafe.AsPointer(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void SkipInit<T>(out T value) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static int SizeOf<T>() { return Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T As<T>(object o) where T : class { return (T)o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T AsRef<T>(void* source) { return ref *(T*)source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AsRef<T>(in T source) { return ref source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref TTo As<TFrom, TTo>(ref TFrom source) { return ref Unsafe.As<TFrom, TTo>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Unbox<T>(object box) where T : struct { return ref (T)box; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, int elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Add<T>(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, int elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Subtract<T>(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static IntPtr ByteOffset<T>(ref T origin, ref T target) { return Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool AreSame<T>(ref T left, ref T right) { return Unsafe.AreSame(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressGreaterThan<T>(ref T left, ref T right) { return Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressLessThan<T>(ref T left, ref T right) { return Unsafe.IsAddressLessThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsNullRef<T>(ref T source) { return Unsafe.AsPointer(ref source) == null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T NullRef<T>() { return ref *(T*)null; } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { internal sealed class IsReadOnlyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] A_0) { TransformFlags = A_0; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } }
plugins/TwitchLib.Client.dll
Decompiled 2 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Timers; using Microsoft.Extensions.Logging; using TwitchLib.Client.Enums; using TwitchLib.Client.Enums.Internal; using TwitchLib.Client.Events; using TwitchLib.Client.Exceptions; using TwitchLib.Client.Interfaces; using TwitchLib.Client.Internal; using TwitchLib.Client.Internal.Parsing; using TwitchLib.Client.Manager; using TwitchLib.Client.Models; using TwitchLib.Client.Models.Internal; using TwitchLib.Communication.Clients; using TwitchLib.Communication.Events; using TwitchLib.Communication.Interfaces; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2022")] [assembly: AssemblyDescription("Client component of TwitchLib. This component allows you to access Twitch chat and whispers, as well as the events that are sent over this connection.")] [assembly: AssemblyFileVersion("3.3.1")] [assembly: AssemblyInformationalVersion("3.3.1")] [assembly: AssemblyProduct("TwitchLib.Client")] [assembly: AssemblyTitle("TwitchLib.Client")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.Client")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("3.3.1.0")] namespace TwitchLib.Client { public class TwitchClient : ITwitchClient { private IClient _client; private MessageEmoteCollection _channelEmotes = new MessageEmoteCollection(); private readonly ICollection<char> _chatCommandIdentifiers = new HashSet<char>(); private readonly ICollection<char> _whisperCommandIdentifiers = new HashSet<char>(); private readonly Queue<JoinedChannel> _joinChannelQueue = new Queue<JoinedChannel>(); private readonly ILogger<TwitchClient> _logger; private readonly ClientProtocol _protocol; private bool _currentlyJoiningChannels; private Timer _joinTimer; private List<KeyValuePair<string, DateTime>> _awaitingJoins; private readonly IrcParser _ircParser; private readonly JoinedChannelManager _joinedChannelManager; private readonly List<string> _hasSeenJoinedChannels = new List<string>(); private string _lastMessageSent; public Version Version => Assembly.GetEntryAssembly().GetName().Version; public bool IsInitialized => _client != null; public IReadOnlyList<JoinedChannel> JoinedChannels => _joinedChannelManager.GetJoinedChannels(); public string TwitchUsername { get; private set; } public WhisperMessage PreviousWhisper { get; private set; } public bool IsConnected { get { if (!IsInitialized || _client == null) { return false; } return _client.IsConnected; } } public MessageEmoteCollection ChannelEmotes => _channelEmotes; public bool DisableAutoPong { get; set; } public bool WillReplaceEmotes { get; set; } public ConnectionCredentials ConnectionCredentials { get; private set; } public bool AutoReListenOnException { get; set; } public event EventHandler<OnAnnouncementArgs> OnAnnouncement; public event EventHandler<OnVIPsReceivedArgs> OnVIPsReceived; public event EventHandler<OnLogArgs> OnLog; public event EventHandler<OnConnectedArgs> OnConnected; public event EventHandler<OnJoinedChannelArgs> OnJoinedChannel; public event EventHandler<OnIncorrectLoginArgs> OnIncorrectLogin; public event EventHandler<OnChannelStateChangedArgs> OnChannelStateChanged; public event EventHandler<OnUserStateChangedArgs> OnUserStateChanged; public event EventHandler<OnMessageReceivedArgs> OnMessageReceived; public event EventHandler<OnWhisperReceivedArgs> OnWhisperReceived; public event EventHandler<OnMessageSentArgs> OnMessageSent; public event EventHandler<OnWhisperSentArgs> OnWhisperSent; public event EventHandler<OnChatCommandReceivedArgs> OnChatCommandReceived; public event EventHandler<OnWhisperCommandReceivedArgs> OnWhisperCommandReceived; public event EventHandler<OnUserJoinedArgs> OnUserJoined; public event EventHandler<OnModeratorJoinedArgs> OnModeratorJoined; public event EventHandler<OnModeratorLeftArgs> OnModeratorLeft; public event EventHandler<OnMessageClearedArgs> OnMessageCleared; public event EventHandler<OnNewSubscriberArgs> OnNewSubscriber; public event EventHandler<OnReSubscriberArgs> OnReSubscriber; public event EventHandler<OnPrimePaidSubscriberArgs> OnPrimePaidSubscriber; public event EventHandler<OnExistingUsersDetectedArgs> OnExistingUsersDetected; public event EventHandler<OnUserLeftArgs> OnUserLeft; public event EventHandler<OnDisconnectedEventArgs> OnDisconnected; public event EventHandler<OnConnectionErrorArgs> OnConnectionError; public event EventHandler<OnChatClearedArgs> OnChatCleared; public event EventHandler<OnUserTimedoutArgs> OnUserTimedout; public event EventHandler<OnLeftChannelArgs> OnLeftChannel; public event EventHandler<OnUserBannedArgs> OnUserBanned; public event EventHandler<OnModeratorsReceivedArgs> OnModeratorsReceived; public event EventHandler<OnChatColorChangedArgs> OnChatColorChanged; public event EventHandler<OnSendReceiveDataArgs> OnSendReceiveData; public event EventHandler<OnRaidNotificationArgs> OnRaidNotification; public event EventHandler<OnGiftedSubscriptionArgs> OnGiftedSubscription; public event EventHandler<OnCommunitySubscriptionArgs> OnCommunitySubscription; public event EventHandler<OnContinuedGiftedSubscriptionArgs> OnContinuedGiftedSubscription; public event EventHandler<OnMessageThrottledEventArgs> OnMessageThrottled; public event EventHandler<OnWhisperThrottledEventArgs> OnWhisperThrottled; public event EventHandler<OnErrorEventArgs> OnError; public event EventHandler<OnReconnectedEventArgs> OnReconnected; public event EventHandler<OnRequiresVerifiedEmailArgs> OnRequiresVerifiedEmail; public event EventHandler<OnRequiresVerifiedPhoneNumberArgs> OnRequiresVerifiedPhoneNumber; public event EventHandler<OnRateLimitArgs> OnRateLimit; public event EventHandler<OnDuplicateArgs> OnDuplicate; public event EventHandler<OnBannedEmailAliasArgs> OnBannedEmailAlias; public event EventHandler OnSelfRaidError; public event EventHandler OnNoPermissionError; public event EventHandler OnRaidedChannelIsMatureAudience; public event EventHandler<OnFailureToReceiveJoinConfirmationArgs> OnFailureToReceiveJoinConfirmation; public event EventHandler<OnFollowersOnlyArgs> OnFollowersOnly; public event EventHandler<OnSubsOnlyArgs> OnSubsOnly; public event EventHandler<OnEmoteOnlyArgs> OnEmoteOnly; public event EventHandler<OnSuspendedArgs> OnSuspended; public event EventHandler<OnBannedArgs> OnBanned; public event EventHandler<OnSlowModeArgs> OnSlowMode; public event EventHandler<OnR9kModeArgs> OnR9kMode; public event EventHandler<OnUserIntroArgs> OnUserIntro; public event EventHandler<OnUnaccountedForArgs> OnUnaccountedFor; public TwitchClient(IClient client = null, ClientProtocol protocol = 1, ILogger<TwitchClient> logger = null) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) _logger = logger; _client = client; _protocol = protocol; _joinedChannelManager = new JoinedChannelManager(); _ircParser = new IrcParser(); } public void Initialize(ConnectionCredentials credentials, string channel = null, char chatCommandIdentifier = '!', char whisperCommandIdentifier = '!', bool autoReListenOnExceptions = true) { if (channel != null && channel[0] == '#') { channel = channel.Substring(1); } initializeHelper(credentials, new List<string> { channel }, chatCommandIdentifier, whisperCommandIdentifier, autoReListenOnExceptions); } public void Initialize(ConnectionCredentials credentials, List<string> channels, char chatCommandIdentifier = '!', char whisperCommandIdentifier = '!', bool autoReListenOnExceptions = true) { channels = channels.Select((string x) => (x[0] != '#') ? x : x.Substring(1)).ToList(); initializeHelper(credentials, channels, chatCommandIdentifier, whisperCommandIdentifier, autoReListenOnExceptions); } private void initializeHelper(ConnectionCredentials credentials, List<string> channels, char chatCommandIdentifier = '!', char whisperCommandIdentifier = '!', bool autoReListenOnExceptions = true) { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Expected O, but got Unknown Log($"TwitchLib-TwitchClient initialized, assembly version: {Assembly.GetExecutingAssembly().GetName().Version}"); ConnectionCredentials = credentials; TwitchUsername = ConnectionCredentials.TwitchUsername; if (chatCommandIdentifier != 0) { _chatCommandIdentifiers.Add(chatCommandIdentifier); } if (whisperCommandIdentifier != 0) { _whisperCommandIdentifiers.Add(whisperCommandIdentifier); } AutoReListenOnException = autoReListenOnExceptions; if (channels != null && channels.Count > 0) { int i; for (i = 0; i < channels.Count; i++) { if (!string.IsNullOrEmpty(channels[i])) { if (((IEnumerable<JoinedChannel>)JoinedChannels).FirstOrDefault((Func<JoinedChannel, bool>)((JoinedChannel x) => x.Channel.ToLower() == channels[i])) != null) { return; } _joinChannelQueue.Enqueue(new JoinedChannel(channels[i])); } } } InitializeClient(); } private void InitializeClient() { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown if (_client == null) { ClientProtocol protocol = _protocol; if ((int)protocol != 0) { if ((int)protocol == 1) { _client = (IClient)new WebSocketClient((IClientOptions)null); } } else { _client = (IClient)new TcpClient((IClientOptions)null); } } _client.OnConnected += _client_OnConnected; _client.OnMessage += _client_OnMessage; _client.OnDisconnected += _client_OnDisconnected; _client.OnFatality += _client_OnFatality; _client.OnMessageThrottled += _client_OnMessageThrottled; _client.OnWhisperThrottled += _client_OnWhisperThrottled; _client.OnReconnected += _client_OnReconnected; } internal void RaiseEvent(string eventName, object args = null) { Delegate[] invocationList = (GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this) as MulticastDelegate).GetInvocationList(); foreach (Delegate @delegate in invocationList) { @delegate.Method.Invoke(@delegate.Target, (args == null) ? new object[2] { this, new EventArgs() } : new object[2] { this, args }); } } public void SendRaw(string message) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (!IsInitialized) { HandleNotInitialized(); } Log("Writing: " + message); _client.Send(message); this.OnSendReceiveData?.Invoke(this, new OnSendReceiveDataArgs { Direction = (SendReceiveDirection)0, Data = message }); } private void SendTwitchMessage(JoinedChannel channel, string message, string replyToId = null, bool dryRun = false) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown if (!IsInitialized) { HandleNotInitialized(); } if (channel == null || message == null || dryRun) { return; } if (message.Length > 500) { LogError("Message length has exceeded the maximum character count. (500)"); return; } OutboundChatMessage val = new OutboundChatMessage { Channel = channel.Channel, Username = ConnectionCredentials.TwitchUsername, Message = message }; if (replyToId != null) { val.ReplyToId = replyToId; } _lastMessageSent = message; _client.Send(((object)val).ToString()); } public void SendMessage(JoinedChannel channel, string message, bool dryRun = false) { SendTwitchMessage(channel, message, null, dryRun); } public void SendMessage(string channel, string message, bool dryRun = false) { SendMessage(GetJoinedChannel(channel), message, dryRun); } public void SendReply(JoinedChannel channel, string replyToId, string message, bool dryRun = false) { SendTwitchMessage(channel, message, replyToId, dryRun); } public void SendReply(string channel, string replyToId, string message, bool dryRun = false) { SendReply(GetJoinedChannel(channel), replyToId, message, dryRun); } public void SendWhisper(string receiver, string message, bool dryRun = false) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown if (!IsInitialized) { HandleNotInitialized(); } if (!dryRun) { OutboundWhisperMessage val = new OutboundWhisperMessage { Receiver = receiver, Username = ConnectionCredentials.TwitchUsername, Message = message }; _client.SendWhisper(((object)val).ToString()); this.OnWhisperSent?.Invoke(this, new OnWhisperSentArgs { Receiver = receiver, Message = message }); } } public bool Connect() { if (!IsInitialized) { HandleNotInitialized(); } Log("Connecting to: " + ConnectionCredentials.TwitchWebsocketURI); _joinedChannelManager.Clear(); if (_client.Open()) { Log("Should be connected!"); return true; } return false; } public void Disconnect() { Log("Disconnect Twitch Chat Client..."); if (!IsInitialized) { HandleNotInitialized(); } _client.Close(true); _joinedChannelManager.Clear(); PreviousWhisper = null; } public void Reconnect() { if (!IsInitialized) { HandleNotInitialized(); } Log("Reconnecting to Twitch"); _client.Reconnect(); } public void AddChatCommandIdentifier(char identifier) { if (!IsInitialized) { HandleNotInitialized(); } _chatCommandIdentifiers.Add(identifier); } public void RemoveChatCommandIdentifier(char identifier) { if (!IsInitialized) { HandleNotInitialized(); } _chatCommandIdentifiers.Remove(identifier); } public void AddWhisperCommandIdentifier(char identifier) { if (!IsInitialized) { HandleNotInitialized(); } _whisperCommandIdentifiers.Add(identifier); } public void RemoveWhisperCommandIdentifier(char identifier) { if (!IsInitialized) { HandleNotInitialized(); } _whisperCommandIdentifiers.Remove(identifier); } public void SetConnectionCredentials(ConnectionCredentials credentials) { if (!IsInitialized) { HandleNotInitialized(); } if (IsConnected) { throw new IllegalAssignmentException("While the client is connected, you are unable to change the connection credentials. Please disconnect first and then change them."); } ConnectionCredentials = credentials; } public void JoinChannel(string channel, bool overrideCheck = false) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown if (!IsInitialized) { HandleNotInitialized(); } if (!IsConnected) { HandleNotConnected(); } if (((IEnumerable<JoinedChannel>)JoinedChannels).FirstOrDefault((Func<JoinedChannel, bool>)((JoinedChannel x) => x.Channel.ToLower() == channel && !overrideCheck)) == null) { if (channel[0] == '#') { channel = channel.Substring(1); } _joinChannelQueue.Enqueue(new JoinedChannel(channel)); if (!_currentlyJoiningChannels) { QueueingJoinCheck(); } } } public JoinedChannel GetJoinedChannel(string channel) { if (!IsInitialized) { HandleNotInitialized(); } if (JoinedChannels.Count == 0) { throw new BadStateException("Must be connected to at least one channel."); } if (channel[0] == '#') { channel = channel.Substring(1); } return _joinedChannelManager.GetJoinedChannel(channel); } public void LeaveChannel(string channel) { if (!IsInitialized) { HandleNotInitialized(); } channel = channel.ToLower(); if (channel[0] == '#') { channel = channel.Substring(1); } Log("Leaving channel: " + channel); if (_joinedChannelManager.GetJoinedChannel(channel) != null) { _client.Send(Rfc2812.Part("#" + channel)); } } public void LeaveChannel(JoinedChannel channel) { if (!IsInitialized) { HandleNotInitialized(); } LeaveChannel(channel.Channel); } public void OnReadLineTest(string rawIrc) { if (!IsInitialized) { HandleNotInitialized(); } HandleIrcMessage(_ircParser.ParseIrcMessage(rawIrc)); } private void _client_OnWhisperThrottled(object sender, OnWhisperThrottledEventArgs e) { this.OnWhisperThrottled?.Invoke(sender, e); } private void _client_OnMessageThrottled(object sender, OnMessageThrottledEventArgs e) { this.OnMessageThrottled?.Invoke(sender, e); } private void _client_OnFatality(object sender, OnFatalErrorEventArgs e) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown this.OnConnectionError?.Invoke(this, new OnConnectionErrorArgs { BotUsername = TwitchUsername, Error = new ErrorEvent { Message = e.Reason } }); } private void _client_OnDisconnected(object sender, OnDisconnectedEventArgs e) { this.OnDisconnected?.Invoke(sender, e); } private void _client_OnReconnected(object sender, OnReconnectedEventArgs e) { foreach (JoinedChannel joinedChannel in _joinedChannelManager.GetJoinedChannels()) { if (!string.Equals(joinedChannel.Channel, TwitchUsername, StringComparison.CurrentCultureIgnoreCase)) { _joinChannelQueue.Enqueue(joinedChannel); } } _joinedChannelManager.Clear(); this.OnReconnected?.Invoke(sender, e); } private void _client_OnMessage(object sender, OnMessageEventArgs e) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) string[] separator = new string[1] { "\r\n" }; string[] array = e.Message.Split(separator, StringSplitOptions.None); foreach (string text in array) { if (text.Length > 1) { Log("Received: " + text); this.OnSendReceiveData?.Invoke(this, new OnSendReceiveDataArgs { Direction = (SendReceiveDirection)1, Data = text }); HandleIrcMessage(_ircParser.ParseIrcMessage(text)); } } } private void _client_OnConnected(object sender, object e) { _client.Send(Rfc2812.Pass(ConnectionCredentials.TwitchOAuth)); _client.Send(Rfc2812.Nick(ConnectionCredentials.TwitchUsername)); _client.Send(Rfc2812.User(ConnectionCredentials.TwitchUsername, 0, ConnectionCredentials.TwitchUsername)); if (ConnectionCredentials.Capabilities.Membership) { _client.Send("CAP REQ twitch.tv/membership"); } if (ConnectionCredentials.Capabilities.Commands) { _client.Send("CAP REQ twitch.tv/commands"); } if (ConnectionCredentials.Capabilities.Tags) { _client.Send("CAP REQ twitch.tv/tags"); } if (_joinChannelQueue != null && _joinChannelQueue.Count > 0) { QueueingJoinCheck(); } } private void QueueingJoinCheck() { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown if (_joinChannelQueue.Count > 0) { _currentlyJoiningChannels = true; JoinedChannel val = _joinChannelQueue.Dequeue(); Log("Joining channel: " + val.Channel); _client.Send(Rfc2812.Join("#" + val.Channel.ToLower())); _joinedChannelManager.AddJoinedChannel(new JoinedChannel(val.Channel)); StartJoinedChannelTimer(val.Channel); } else { Log("Finished channel joining queue."); } } private void StartJoinedChannelTimer(string channel) { if (_joinTimer == null) { _joinTimer = new Timer(1000.0); _joinTimer.Elapsed += JoinChannelTimeout; _awaitingJoins = new List<KeyValuePair<string, DateTime>>(); } _awaitingJoins.Add(new KeyValuePair<string, DateTime>(channel.ToLower(), DateTime.Now)); if (!_joinTimer.Enabled) { _joinTimer.Start(); } } private void JoinChannelTimeout(object sender, ElapsedEventArgs e) { if (_awaitingJoins.Any()) { List<KeyValuePair<string, DateTime>> list = _awaitingJoins.Where((KeyValuePair<string, DateTime> x) => (DateTime.Now - x.Value).TotalSeconds > 5.0).ToList(); if (!list.Any()) { return; } _awaitingJoins.RemoveAll((KeyValuePair<string, DateTime> x) => (DateTime.Now - x.Value).TotalSeconds > 5.0); { foreach (KeyValuePair<string, DateTime> item in list) { _joinedChannelManager.RemoveJoinedChannel(item.Key.ToLowerInvariant()); this.OnFailureToReceiveJoinConfirmation?.Invoke(this, new OnFailureToReceiveJoinConfirmationArgs { Exception = new FailureToReceiveJoinConfirmationException(item.Key) }); } return; } } _joinTimer.Stop(); _currentlyJoiningChannels = false; QueueingJoinCheck(); } private void HandleIrcMessage(IrcMessage ircMessage) { //IL_0041: 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) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Expected I4, but got Unknown if (ircMessage.Message.Contains("Login authentication failed")) { this.OnIncorrectLogin?.Invoke(this, new OnIncorrectLoginArgs { Exception = new ErrorLoggingInException(ircMessage.ToString(), TwitchUsername) }); return; } IrcCommand command = ircMessage.Command; switch ((int)command) { case 1: HandlePrivMsg(ircMessage); break; case 2: HandleNotice(ircMessage); break; case 3: if (!DisableAutoPong) { SendRaw("PONG"); } break; case 4: break; case 5: HandleJoin(ircMessage); break; case 6: HandlePart(ircMessage); break; case 7: HandleClearChat(ircMessage); break; case 8: HandleClearMsg(ircMessage); break; case 9: HandleUserState(ircMessage); break; case 17: Handle004(); break; case 18: Handle353(ircMessage); break; case 19: Handle366(); break; case 23: HandleWhisper(ircMessage); break; case 24: HandleRoomState(ircMessage); break; case 25: Reconnect(); break; case 27: HandleUserNotice(ircMessage); break; case 28: HandleMode(ircMessage); break; case 13: HandleCap(ircMessage); break; default: this.OnUnaccountedFor?.Invoke(this, new OnUnaccountedForArgs { BotUsername = TwitchUsername, Channel = null, Location = "HandleIrcMessage", RawIRC = ircMessage.ToString() }); UnaccountedFor(ircMessage.ToString()); break; case 10: case 14: case 15: case 16: case 20: case 21: case 22: break; } } private void HandlePrivMsg(IrcMessage ircMessage) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Expected O, but got Unknown ChatMessage val = new ChatMessage(TwitchUsername, ircMessage, ref _channelEmotes, WillReplaceEmotes); foreach (JoinedChannel item in JoinedChannels.Where((JoinedChannel x) => string.Equals(x.Channel, ircMessage.Channel, StringComparison.InvariantCultureIgnoreCase))) { item.HandleMessage(val); } this.OnMessageReceived?.Invoke(this, new OnMessageReceivedArgs { ChatMessage = val }); if (ircMessage.Tags.TryGetValue("msg-id", out var value) && value == "user-intro") { this.OnUserIntro?.Invoke(this, new OnUserIntroArgs { ChatMessage = val }); } if (_chatCommandIdentifiers != null && _chatCommandIdentifiers.Count != 0 && !string.IsNullOrEmpty(val.Message) && _chatCommandIdentifiers.Contains(val.Message[0])) { ChatCommand command = new ChatCommand(val); this.OnChatCommandReceived?.Invoke(this, new OnChatCommandReceivedArgs { Command = command }); } } private void HandleNotice(IrcMessage ircMessage) { if (ircMessage.Message.Contains("Improperly formatted auth")) { this.OnIncorrectLogin?.Invoke(this, new OnIncorrectLoginArgs { Exception = new ErrorLoggingInException(ircMessage.ToString(), TwitchUsername) }); return; } if (!ircMessage.Tags.TryGetValue("msg-id", out var value)) { this.OnUnaccountedFor?.Invoke(this, new OnUnaccountedForArgs { BotUsername = TwitchUsername, Channel = ircMessage.Channel, Location = "NoticeHandling", RawIRC = ircMessage.ToString() }); UnaccountedFor(ircMessage.ToString()); } switch (value) { case "color_changed": this.OnChatColorChanged?.Invoke(this, new OnChatColorChangedArgs { Channel = ircMessage.Channel }); break; case "room_mods": this.OnModeratorsReceived?.Invoke(this, new OnModeratorsReceivedArgs { Channel = ircMessage.Channel, Moderators = ircMessage.Message.Replace(" ", "").Split(new char[1] { ':' })[1].Split(new char[1] { ',' }).ToList() }); break; case "no_mods": this.OnModeratorsReceived?.Invoke(this, new OnModeratorsReceivedArgs { Channel = ircMessage.Channel, Moderators = new List<string>() }); break; case "no_permission": this.OnNoPermissionError?.Invoke(this, null); break; case "raid_error_self": this.OnSelfRaidError?.Invoke(this, null); break; case "raid_notice_mature": this.OnRaidedChannelIsMatureAudience?.Invoke(this, null); break; case "msg_banned_email_alias": this.OnBannedEmailAlias?.Invoke(this, new OnBannedEmailAliasArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_channel_suspended": _awaitingJoins.RemoveAll((KeyValuePair<string, DateTime> x) => x.Key.ToLower() == ircMessage.Channel); _joinedChannelManager.RemoveJoinedChannel(ircMessage.Channel); QueueingJoinCheck(); this.OnFailureToReceiveJoinConfirmation?.Invoke(this, new OnFailureToReceiveJoinConfirmationArgs { Exception = new FailureToReceiveJoinConfirmationException(ircMessage.Channel, ircMessage.Message) }); break; case "msg_requires_verified_phone_number": this.OnRequiresVerifiedPhoneNumber?.Invoke(this, new OnRequiresVerifiedPhoneNumberArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_verified_email": this.OnRequiresVerifiedEmail?.Invoke(this, new OnRequiresVerifiedEmailArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "no_vips": this.OnVIPsReceived?.Invoke(this, new OnVIPsReceivedArgs { Channel = ircMessage.Channel, VIPs = new List<string>() }); break; case "vips_success": this.OnVIPsReceived?.Invoke(this, new OnVIPsReceivedArgs { Channel = ircMessage.Channel, VIPs = ircMessage.Message.Replace(" ", "").Replace(".", "").Split(new char[1] { ':' })[1].Split(new char[1] { ',' }).ToList() }); break; case "msg_ratelimit": this.OnRateLimit?.Invoke(this, new OnRateLimitArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_duplicate": this.OnDuplicate?.Invoke(this, new OnDuplicateArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_followersonly": this.OnFollowersOnly?.Invoke(this, new OnFollowersOnlyArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_subsonly": this.OnSubsOnly?.Invoke(this, new OnSubsOnlyArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_emoteonly": this.OnEmoteOnly?.Invoke(this, new OnEmoteOnlyArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_suspended": this.OnSuspended?.Invoke(this, new OnSuspendedArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_banned": this.OnBanned?.Invoke(this, new OnBannedArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_slowmode": this.OnSlowMode?.Invoke(this, new OnSlowModeArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; case "msg_r9k": this.OnR9kMode?.Invoke(this, new OnR9kModeArgs { Channel = ircMessage.Channel, Message = ircMessage.Message }); break; default: this.OnUnaccountedFor?.Invoke(this, new OnUnaccountedForArgs { BotUsername = TwitchUsername, Channel = ircMessage.Channel, Location = "NoticeHandling", RawIRC = ircMessage.ToString() }); UnaccountedFor(ircMessage.ToString()); break; } } private void HandleJoin(IrcMessage ircMessage) { this.OnUserJoined?.Invoke(this, new OnUserJoinedArgs { Channel = ircMessage.Channel, Username = ircMessage.User }); } private void HandlePart(IrcMessage ircMessage) { if (string.Equals(TwitchUsername, ircMessage.User, StringComparison.InvariantCultureIgnoreCase)) { _joinedChannelManager.RemoveJoinedChannel(ircMessage.Channel); _hasSeenJoinedChannels.Remove(ircMessage.Channel); this.OnLeftChannel?.Invoke(this, new OnLeftChannelArgs { BotUsername = TwitchUsername, Channel = ircMessage.Channel }); } else { this.OnUserLeft?.Invoke(this, new OnUserLeftArgs { Channel = ircMessage.Channel, Username = ircMessage.User }); } } private void HandleClearChat(IrcMessage ircMessage) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown string value; if (string.IsNullOrWhiteSpace(ircMessage.Message)) { this.OnChatCleared?.Invoke(this, new OnChatClearedArgs { Channel = ircMessage.Channel }); } else if (ircMessage.Tags.TryGetValue("ban-duration", out value)) { UserTimeout userTimeout = new UserTimeout(ircMessage); this.OnUserTimedout?.Invoke(this, new OnUserTimedoutArgs { UserTimeout = userTimeout }); } else { UserBan userBan = new UserBan(ircMessage); this.OnUserBanned?.Invoke(this, new OnUserBannedArgs { UserBan = userBan }); } } private void HandleClearMsg(IrcMessage ircMessage) { this.OnMessageCleared?.Invoke(this, new OnMessageClearedArgs { Channel = ircMessage.Channel, Message = ircMessage.Message, TargetMessageId = ircMessage.ToString().Split(new char[1] { '=' })[3].Split(new char[1] { ';' })[0], TmiSentTs = ircMessage.ToString().Split(new char[1] { '=' })[4].Split(new char[1] { ' ' })[0] }); } private void HandleUserState(IrcMessage ircMessage) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown UserState val = new UserState(ircMessage); if (!_hasSeenJoinedChannels.Contains(val.Channel.ToLowerInvariant())) { _hasSeenJoinedChannels.Add(val.Channel.ToLowerInvariant()); this.OnUserStateChanged?.Invoke(this, new OnUserStateChangedArgs { UserState = val }); } else { this.OnMessageSent?.Invoke(this, new OnMessageSentArgs { SentMessage = new SentMessage(val, _lastMessageSent) }); } } private void Handle004() { this.OnConnected?.Invoke(this, new OnConnectedArgs { BotUsername = TwitchUsername }); } private void Handle353(IrcMessage ircMessage) { this.OnExistingUsersDetected?.Invoke(this, new OnExistingUsersDetectedArgs { Channel = ircMessage.Channel, Users = ircMessage.Message.Split(new char[1] { ' ' }).ToList() }); } private void Handle366() { _currentlyJoiningChannels = false; QueueingJoinCheck(); } private void HandleWhisper(IrcMessage ircMessage) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown WhisperMessage val2 = (PreviousWhisper = new WhisperMessage(ircMessage, TwitchUsername)); this.OnWhisperReceived?.Invoke(this, new OnWhisperReceivedArgs { WhisperMessage = val2 }); if (_whisperCommandIdentifiers != null && _whisperCommandIdentifiers.Count != 0 && !string.IsNullOrEmpty(val2.Message) && _whisperCommandIdentifiers.Contains(val2.Message[0])) { WhisperCommand command = new WhisperCommand(val2); this.OnWhisperCommandReceived?.Invoke(this, new OnWhisperCommandReceivedArgs { Command = command }); return; } this.OnUnaccountedFor?.Invoke(this, new OnUnaccountedForArgs { BotUsername = TwitchUsername, Channel = ircMessage.Channel, Location = "WhispergHandling", RawIRC = ircMessage.ToString() }); UnaccountedFor(ircMessage.ToString()); } private void HandleRoomState(IrcMessage ircMessage) { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown if (ircMessage.Tags.Count > 2) { KeyValuePair<string, DateTime> item = _awaitingJoins.FirstOrDefault((KeyValuePair<string, DateTime> x) => x.Key == ircMessage.Channel); _awaitingJoins.Remove(item); this.OnJoinedChannel?.Invoke(this, new OnJoinedChannelArgs { BotUsername = TwitchUsername, Channel = ircMessage.Channel }); } this.OnChannelStateChanged?.Invoke(this, new OnChannelStateChangedArgs { ChannelState = new ChannelState(ircMessage), Channel = ircMessage.Channel }); } private void HandleUserNotice(IrcMessage ircMessage) { //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: Expected O, but got Unknown //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Expected O, but got Unknown //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_0302: Expected O, but got Unknown //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Expected O, but got Unknown //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Expected O, but got Unknown //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Expected O, but got Unknown //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Expected O, but got Unknown //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Expected O, but got Unknown if (!ircMessage.Tags.TryGetValue("msg-id", out var value)) { this.OnUnaccountedFor?.Invoke(this, new OnUnaccountedForArgs { BotUsername = TwitchUsername, Channel = ircMessage.Channel, Location = "UserNoticeHandling", RawIRC = ircMessage.ToString() }); UnaccountedFor(ircMessage.ToString()); return; } switch (value) { case "announcement": { Announcement announcement = new Announcement(ircMessage); this.OnAnnouncement?.Invoke(this, new OnAnnouncementArgs { Announcement = announcement, Channel = ircMessage.Channel }); break; } case "raid": { RaidNotification raidNotification = new RaidNotification(ircMessage); this.OnRaidNotification?.Invoke(this, new OnRaidNotificationArgs { Channel = ircMessage.Channel, RaidNotification = raidNotification }); break; } case "resub": { ReSubscriber reSubscriber = new ReSubscriber(ircMessage); this.OnReSubscriber?.Invoke(this, new OnReSubscriberArgs { ReSubscriber = reSubscriber, Channel = ircMessage.Channel }); break; } case "subgift": { GiftedSubscription giftedSubscription2 = new GiftedSubscription(ircMessage); this.OnGiftedSubscription?.Invoke(this, new OnGiftedSubscriptionArgs { GiftedSubscription = giftedSubscription2, Channel = ircMessage.Channel }); break; } case "submysterygift": { CommunitySubscription giftedSubscription = new CommunitySubscription(ircMessage); this.OnCommunitySubscription?.Invoke(this, new OnCommunitySubscriptionArgs { GiftedSubscription = giftedSubscription, Channel = ircMessage.Channel }); break; } case "giftpaidupgrade": { ContinuedGiftedSubscription continuedGiftedSubscription = new ContinuedGiftedSubscription(ircMessage); this.OnContinuedGiftedSubscription?.Invoke(this, new OnContinuedGiftedSubscriptionArgs { ContinuedGiftedSubscription = continuedGiftedSubscription, Channel = ircMessage.Channel }); break; } case "sub": { Subscriber subscriber = new Subscriber(ircMessage); this.OnNewSubscriber?.Invoke(this, new OnNewSubscriberArgs { Subscriber = subscriber, Channel = ircMessage.Channel }); break; } case "primepaidupgrade": { PrimePaidSubscriber primePaidSubscriber = new PrimePaidSubscriber(ircMessage); this.OnPrimePaidSubscriber?.Invoke(this, new OnPrimePaidSubscriberArgs { PrimePaidSubscriber = primePaidSubscriber, Channel = ircMessage.Channel }); break; } default: this.OnUnaccountedFor?.Invoke(this, new OnUnaccountedForArgs { BotUsername = TwitchUsername, Channel = ircMessage.Channel, Location = "UserNoticeHandling", RawIRC = ircMessage.ToString() }); UnaccountedFor(ircMessage.ToString()); break; } } private void HandleMode(IrcMessage ircMessage) { if (ircMessage.Message.StartsWith("+o")) { this.OnModeratorJoined?.Invoke(this, new OnModeratorJoinedArgs { Channel = ircMessage.Channel, Username = ircMessage.Message.Split(new char[1] { ' ' })[1] }); } else if (ircMessage.Message.StartsWith("-o")) { this.OnModeratorLeft?.Invoke(this, new OnModeratorLeftArgs { Channel = ircMessage.Channel, Username = ircMessage.Message.Split(new char[1] { ' ' })[1] }); } } private void HandleCap(IrcMessage ircMessage) { } private void UnaccountedFor(string ircString) { Log("Unaccounted for: " + ircString + " (please create a TwitchLib GitHub issue :P)"); } private void Log(string message, bool includeDate = false, bool includeTime = false) { string arg = ((includeDate && includeTime) ? $"{DateTime.UtcNow}" : ((!includeDate) ? (DateTime.UtcNow.ToShortTimeString() ?? "") : (DateTime.UtcNow.ToShortDateString() ?? ""))); if (includeDate || includeTime) { _logger?.LogInformation($"[TwitchLib, {Assembly.GetExecutingAssembly().GetName().Version} - {arg}] {message}"); } else { _logger?.LogInformation($"[TwitchLib, {Assembly.GetExecutingAssembly().GetName().Version}] {message}"); } EventHandler<OnLogArgs> onLog = this.OnLog; if (onLog != null) { OnLogArgs onLogArgs = new OnLogArgs(); ConnectionCredentials connectionCredentials = ConnectionCredentials; onLogArgs.BotUsername = ((connectionCredentials != null) ? connectionCredentials.TwitchUsername : null); onLogArgs.Data = message; onLogArgs.DateTime = DateTime.UtcNow; onLog(this, onLogArgs); } } private void LogError(string message, bool includeDate = false, bool includeTime = false) { string arg = ((includeDate && includeTime) ? $"{DateTime.UtcNow}" : ((!includeDate) ? (DateTime.UtcNow.ToShortTimeString() ?? "") : (DateTime.UtcNow.ToShortDateString() ?? ""))); if (includeDate || includeTime) { _logger?.LogError($"[TwitchLib, {Assembly.GetExecutingAssembly().GetName().Version} - {arg}] {message}"); } else { _logger?.LogError($"[TwitchLib, {Assembly.GetExecutingAssembly().GetName().Version}] {message}"); } EventHandler<OnLogArgs> onLog = this.OnLog; if (onLog != null) { OnLogArgs onLogArgs = new OnLogArgs(); ConnectionCredentials connectionCredentials = ConnectionCredentials; onLogArgs.BotUsername = ((connectionCredentials != null) ? connectionCredentials.TwitchUsername : null); onLogArgs.Data = message; onLogArgs.DateTime = DateTime.UtcNow; onLog(this, onLogArgs); } } public void SendQueuedItem(string message) { if (!IsInitialized) { HandleNotInitialized(); } _client.Send(message); } protected static void HandleNotInitialized() { throw new ClientNotInitializedException("The twitch client has not been initialized and cannot be used. Please call Initialize();"); } protected static void HandleNotConnected() { throw new ClientNotConnectedException("In order to perform this action, the client must be connected to Twitch. To confirm connection, try performing this action in or after the OnConnected event has been fired."); } } } namespace TwitchLib.Client.Manager { internal class JoinedChannelManager { private readonly ConcurrentDictionary<string, JoinedChannel> _joinedChannels; public JoinedChannelManager() { _joinedChannels = new ConcurrentDictionary<string, JoinedChannel>(StringComparer.OrdinalIgnoreCase); } public void AddJoinedChannel(JoinedChannel joinedChannel) { _joinedChannels.TryAdd(joinedChannel.Channel, joinedChannel); } public JoinedChannel GetJoinedChannel(string channel) { _joinedChannels.TryGetValue(channel, out var value); return value; } public IReadOnlyList<JoinedChannel> GetJoinedChannels() { return _joinedChannels.Values.ToList().AsReadOnly(); } public void RemoveJoinedChannel(string channel) { _joinedChannels.TryRemove(channel, out var _); } public void Clear() { _joinedChannels.Clear(); } } } namespace TwitchLib.Client.Internal { public sealed class Rfc2812 { private static readonly Regex NicknameRegex = new Regex("^[A-Za-z\\[\\]\\\\`_^{|}][A-Za-z0-9\\[\\]\\\\`_\\-^{|}]+$", RegexOptions.Compiled); private Rfc2812() { } public static bool IsValidNickname(string nickname) { if (!string.IsNullOrEmpty(nickname)) { return NicknameRegex.Match(nickname).Success; } return false; } public static string Pass(string password) { return "PASS " + password; } public static string Nick(string nickname) { return "NICK " + nickname; } public static string User(string username, int usermode, string realname) { return $"USER {username} {usermode} * :{realname}"; } public static string Oper(string name, string password) { return "OPER " + name + " " + password; } public static string Privmsg(string destination, string message) { return "PRIVMSG " + destination + " :" + message; } public static string Notice(string destination, string message) { return "NOTICE " + destination + " :" + message; } public static string Join(string channel) { return "JOIN " + channel; } public static string Join(string[] channels) { return "JOIN " + string.Join(",", channels); } public static string Join(string channel, string key) { return "JOIN " + channel + " " + key; } public static string Join(string[] channels, string[] keys) { return "JOIN " + string.Join(",", channels) + " " + string.Join(",", keys); } public static string Part(string channel) { return "PART " + channel; } public static string Part(string[] channels) { return "PART " + string.Join(",", channels); } public static string Part(string channel, string partmessage) { return "PART " + channel + " :" + partmessage; } public static string Part(string[] channels, string partmessage) { return "PART " + string.Join(",", channels) + " :" + partmessage; } public static string Kick(string channel, string nickname) { return "KICK " + channel + " " + nickname; } public static string Kick(string channel, string nickname, string comment) { return "KICK " + channel + " " + nickname + " :" + comment; } public static string Kick(string[] channels, string nickname) { return "KICK " + string.Join(",", channels) + " " + nickname; } public static string Kick(string[] channels, string nickname, string comment) { return "KICK " + string.Join(",", channels) + " " + nickname + " :" + comment; } public static string Kick(string channel, string[] nicknames) { return "KICK " + channel + " " + string.Join(",", nicknames); } public static string Kick(string channel, string[] nicknames, string comment) { return "KICK " + channel + " " + string.Join(",", nicknames) + " :" + comment; } public static string Kick(string[] channels, string[] nicknames) { return "KICK " + string.Join(",", channels) + " " + string.Join(",", nicknames); } public static string Kick(string[] channels, string[] nicknames, string comment) { return "KICK " + string.Join(",", channels) + " " + string.Join(",", nicknames) + " :" + comment; } public static string Motd() { return "MOTD"; } public static string Motd(string target) { return "MOTD " + target; } public static string Lusers() { return "LUSERS"; } public static string Lusers(string mask) { return "LUSER " + mask; } public static string Lusers(string mask, string target) { return "LUSER " + mask + " " + target; } public static string Version() { return "VERSION"; } public static string Version(string target) { return "VERSION " + target; } public static string Stats() { return "STATS"; } public static string Stats(string query) { return "STATS " + query; } public static string Stats(string query, string target) { return "STATS " + query + " " + target; } public static string Links() { return "LINKS"; } public static string Links(string servermask) { return "LINKS " + servermask; } public static string Links(string remoteserver, string servermask) { return "LINKS " + remoteserver + " " + servermask; } public static string Time() { return "TIME"; } public static string Time(string target) { return "TIME " + target; } public static string Connect(string targetserver, string port) { return "CONNECT " + targetserver + " " + port; } public static string Connect(string targetserver, string port, string remoteserver) { return "CONNECT " + targetserver + " " + port + " " + remoteserver; } public static string Trace() { return "TRACE"; } public static string Trace(string target) { return "TRACE " + target; } public static string Admin() { return "ADMIN"; } public static string Admin(string target) { return "ADMIN " + target; } public static string Info() { return "INFO"; } public static string Info(string target) { return "INFO " + target; } public static string Servlist() { return "SERVLIST"; } public static string Servlist(string mask) { return "SERVLIST " + mask; } public static string Servlist(string mask, string type) { return "SERVLIST " + mask + " " + type; } public static string Squery(string servicename, string servicetext) { return "SQUERY " + servicename + " :" + servicename; } public static string List() { return "LIST"; } public static string List(string channel) { return "LIST " + channel; } public static string List(string[] channels) { return "LIST " + string.Join(",", channels); } public static string List(string channel, string target) { return "LIST " + channel + " " + target; } public static string List(string[] channels, string target) { return "LIST " + string.Join(",", channels) + " " + target; } public static string Names() { return "NAMES"; } public static string Names(string channel) { return "NAMES " + channel; } public static string Names(string[] channels) { return "NAMES " + string.Join(",", channels); } public static string Names(string channel, string target) { return "NAMES " + channel + " " + target; } public static string Names(string[] channels, string target) { return "NAMES " + string.Join(",", channels) + " " + target; } public static string Topic(string channel) { return "TOPIC " + channel; } public static string Topic(string channel, string newtopic) { return "TOPIC " + channel + " :" + newtopic; } public static string Mode(string target) { return "MODE " + target; } public static string Mode(string target, string newmode) { return "MODE " + target + " " + newmode + target + " " + newmode; } public static string Mode(string target, string[] newModes, string[] newModeParameters) { if (newModes == null) { throw new ArgumentNullException("newModes"); } if (newModeParameters == null) { throw new ArgumentNullException("newModeParameters"); } if (newModes.Length != newModeParameters.Length) { throw new ArgumentException("newModes and newModeParameters must have the same size."); } StringBuilder stringBuilder = new StringBuilder(newModes.Length); StringBuilder stringBuilder2 = new StringBuilder(); if (newModes.Length > 3) { throw new ArgumentOutOfRangeException("Length", newModes.Length, $"Mode change list is too large (> {3})."); } for (int i = 0; i <= newModes.Length; i += 3) { for (int j = 0; j < 3 && i + j < newModes.Length; j++) { stringBuilder.Append(newModes[i + j]); } for (int k = 0; k < 3 && i + k < newModeParameters.Length; k++) { stringBuilder2.Append(newModeParameters[i + k]); stringBuilder2.Append(" "); } } if (stringBuilder2.Length <= 0) { return Mode(target, stringBuilder.ToString()); } stringBuilder2.Length--; stringBuilder.Append(" "); stringBuilder.Append((object?)stringBuilder2); return Mode(target, stringBuilder.ToString()); } public static string Service(string nickname, string distribution, string info) { return "SERVICE " + nickname + " * " + distribution + " * * :" + info; } public static string Invite(string nickname, string channel) { return "INVITE " + nickname + " " + channel; } public static string Who() { return "WHO"; } public static string Who(string mask) { return "WHO " + mask; } public static string Who(string mask, bool ircop) { if (!ircop) { return "WHO " + mask; } return "WHO " + mask + " o"; } public static string Whois(string mask) { return "WHOIS " + mask; } public static string Whois(string[] masks) { return "WHOIS " + string.Join(",", masks); } public static string Whois(string target, string mask) { return "WHOIS " + target + " " + mask; } public static string Whois(string target, string[] masks) { return "WHOIS " + target + " " + string.Join(",", masks); } public static string Whowas(string nickname) { return "WHOWAS " + nickname; } public static string Whowas(string[] nicknames) { return "WHOWAS " + string.Join(",", nicknames); } public static string Whowas(string nickname, string count) { return "WHOWAS " + nickname + " " + count + " "; } public static string Whowas(string[] nicknames, string count) { return "WHOWAS " + string.Join(",", nicknames) + " " + count + " "; } public static string Whowas(string nickname, string count, string target) { return "WHOWAS " + nickname + " " + count + " " + target; } public static string Whowas(string[] nicknames, string count, string target) { return "WHOWAS " + string.Join(",", nicknames) + " " + count + " " + target; } public static string Kill(string nickname, string comment) { return "KILL " + nickname + " :" + comment; } public static string Ping(string server) { return "PING " + server; } public static string Ping(string server, string server2) { return "PING " + server + " " + server2; } public static string Pong(string server) { return "PONG " + server; } public static string Pong(string server, string server2) { return "PONG " + server + " " + server2; } public static string Error(string errormessage) { return "ERROR :" + errormessage; } public static string Away() { return "AWAY"; } public static string Away(string awaytext) { return "AWAY :" + awaytext; } public static string Rehash() { return "REHASH"; } public static string Die() { return "DIE"; } public static string Restart() { return "RESTART"; } public static string Summon(string user) { return "SUMMON " + user; } public static string Summon(string user, string target) { return "SUMMON " + user + " " + target + user + " " + target; } public static string Summon(string user, string target, string channel) { return "SUMMON " + user + " " + target + " " + channel; } public static string Users() { return "USERS"; } public static string Users(string target) { return "USERS " + target; } public static string Wallops(string wallopstext) { return "WALLOPS :" + wallopstext; } public static string Userhost(string nickname) { return "USERHOST " + nickname; } public static string Userhost(string[] nicknames) { return "USERHOST " + string.Join(" ", nicknames); } public static string Ison(string nickname) { return "ISON " + nickname; } public static string Ison(string[] nicknames) { return "ISON " + string.Join(" ", nicknames); } public static string Quit() { return "QUIT"; } public static string Quit(string quitmessage) { return "QUIT :" + quitmessage; } public static string Squit(string server, string comment) { return "SQUIT " + server + " :" + comment; } } } namespace TwitchLib.Client.Internal.Parsing { internal class IrcParser { private enum ParserState { STATE_NONE, STATE_V3, STATE_PREFIX, STATE_COMMAND, STATE_PARAM, STATE_TRAILING } public IrcMessage ParseIrcMessage(string raw) { //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_068c: Unknown result type (might be due to invalid IL or missing references) //IL_064f: Unknown result type (might be due to invalid IL or missing references) //IL_0691: Unknown result type (might be due to invalid IL or missing references) //IL_065f: Unknown result type (might be due to invalid IL or missing references) //IL_06f0: Unknown result type (might be due to invalid IL or missing references) //IL_06b4: Unknown result type (might be due to invalid IL or missing references) //IL_0728: Unknown result type (might be due to invalid IL or missing references) //IL_073d: Unknown result type (might be due to invalid IL or missing references) //IL_0743: Expected O, but got Unknown //IL_06ba: Unknown result type (might be due to invalid IL or missing references) //IL_06cc: Unknown result type (might be due to invalid IL or missing references) //IL_06d8: Unknown result type (might be due to invalid IL or missing references) //IL_06e4: Unknown result type (might be due to invalid IL or missing references) //IL_0680: Unknown result type (might be due to invalid IL or missing references) //IL_06f6: Unknown result type (might be due to invalid IL or missing references) //IL_06de: Unknown result type (might be due to invalid IL or missing references) //IL_06c0: Unknown result type (might be due to invalid IL or missing references) //IL_0696: Unknown result type (might be due to invalid IL or missing references) //IL_0667: Unknown result type (might be due to invalid IL or missing references) //IL_0657: Unknown result type (might be due to invalid IL or missing references) //IL_06ae: Unknown result type (might be due to invalid IL or missing references) //IL_06a8: Unknown result type (might be due to invalid IL or missing references) //IL_06fc: Unknown result type (might be due to invalid IL or missing references) //IL_06d2: Unknown result type (might be due to invalid IL or missing references) //IL_06c6: Unknown result type (might be due to invalid IL or missing references) //IL_06ea: Unknown result type (might be due to invalid IL or missing references) //IL_0677: Unknown result type (might be due to invalid IL or missing references) //IL_066f: Unknown result type (might be due to invalid IL or missing references) //IL_06a2: Unknown result type (might be due to invalid IL or missing references) //IL_0686: Unknown result type (might be due to invalid IL or missing references) //IL_069c: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, string> dictionary = new Dictionary<string, string>(); ParserState parserState = ParserState.STATE_NONE; int[] array = new int[6]; int[] array2 = new int[6]; for (int i = 0; i < raw.Length; i++) { array2[(int)parserState] = i - array[(int)parserState] - 1; if (parserState == ParserState.STATE_NONE && raw[i] == '@') { parserState = ParserState.STATE_V3; i = (array[(int)parserState] = i + 1); int num = i; string text = null; for (; i < raw.Length; i++) { if (raw[i] == '=') { text = raw.Substring(num, i - num); num = i + 1; } else if (raw[i] == ';') { if (text == null) { dictionary[raw.Substring(num, i - num)] = "1"; } else { dictionary[text] = raw.Substring(num, i - num); } num = i + 1; } else if (raw[i] == ' ') { if (text == null) { dictionary[raw.Substring(num, i - num)] = "1"; } else { dictionary[text] = raw.Substring(num, i - num); } break; } } } else if (parserState < ParserState.STATE_PREFIX && raw[i] == ':') { parserState = ParserState.STATE_PREFIX; i = (array[(int)parserState] = i + 1); } else if (parserState < ParserState.STATE_COMMAND) { parserState = ParserState.STATE_COMMAND; array[(int)parserState] = i; } else { if (parserState < ParserState.STATE_TRAILING && raw[i] == ':') { parserState = ParserState.STATE_TRAILING; i = (array[(int)parserState] = i + 1); break; } if ((parserState < ParserState.STATE_TRAILING && raw[i] == '+') || (parserState < ParserState.STATE_TRAILING && raw[i] == '-')) { parserState = ParserState.STATE_TRAILING; array[(int)parserState] = i; break; } if (parserState == ParserState.STATE_COMMAND) { parserState = ParserState.STATE_PARAM; array[(int)parserState] = i; } } for (; i < raw.Length && raw[i] != ' '; i++) { } } array2[(int)parserState] = raw.Length - array[(int)parserState]; string text2 = raw.Substring(array[3], array2[3]); IrcCommand val = (IrcCommand)0; switch (text2) { case "PRIVMSG": val = (IrcCommand)1; break; case "NOTICE": val = (IrcCommand)2; break; case "PING": val = (IrcCommand)3; break; case "PONG": val = (IrcCommand)4; break; case "CLEARCHAT": val = (IrcCommand)7; break; case "CLEARMSG": val = (IrcCommand)8; break; case "USERSTATE": val = (IrcCommand)9; break; case "GLOBALUSERSTATE": val = (IrcCommand)10; break; case "NICK": val = (IrcCommand)11; break; case "JOIN": val = (IrcCommand)5; break; case "PART": val = (IrcCommand)6; break; case "PASS": val = (IrcCommand)12; break; case "CAP": val = (IrcCommand)13; break; case "001": val = (IrcCommand)14; break; case "002": val = (IrcCommand)15; break; case "003": val = (IrcCommand)16; break; case "004": val = (IrcCommand)17; break; case "353": val = (IrcCommand)18; break; case "366": val = (IrcCommand)19; break; case "372": val = (IrcCommand)20; break; case "375": val = (IrcCommand)21; break; case "376": val = (IrcCommand)22; break; case "WHISPER": val = (IrcCommand)23; break; case "SERVERCHANGE": val = (IrcCommand)26; break; case "RECONNECT": val = (IrcCommand)25; break; case "ROOMSTATE": val = (IrcCommand)24; break; case "USERNOTICE": val = (IrcCommand)27; break; case "MODE": val = (IrcCommand)28; break; } string text3 = raw.Substring(array[4], array2[4]); string text4 = raw.Substring(array[5], array2[5]); string text5 = raw.Substring(array[2], array2[2]); return new IrcMessage(val, new string[2] { text3, text4 }, text5, dictionary); } } } namespace TwitchLib.Client.Interfaces { public interface ITwitchClient { bool AutoReListenOnException { get; set; } MessageEmoteCollection ChannelEmotes { get; } ConnectionCredentials ConnectionCredentials { get; } bool DisableAutoPong { get; set; } bool IsConnected { get; } bool IsInitialized { get; } IReadOnlyList<JoinedChannel> JoinedChannels { get; } WhisperMessage PreviousWhisper { get; } string TwitchUsername { get; } bool WillReplaceEmotes { get; set; } event EventHandler<OnChannelStateChangedArgs> OnChannelStateChanged; event EventHandler<OnChatClearedArgs> OnChatCleared; event EventHandler<OnChatColorChangedArgs> OnChatColorChanged; event EventHandler<OnChatCommandReceivedArgs> OnChatCommandReceived; event EventHandler<OnConnectedArgs> OnConnected; event EventHandler<OnConnectionErrorArgs> OnConnectionError; event EventHandler<OnDisconnectedEventArgs> OnDisconnected; event EventHandler<OnExistingUsersDetectedArgs> OnExistingUsersDetected; event EventHandler<OnGiftedSubscriptionArgs> OnGiftedSubscription; event EventHandler<OnIncorrectLoginArgs> OnIncorrectLogin; event EventHandler<OnJoinedChannelArgs> OnJoinedChannel; event EventHandler<OnLeftChannelArgs> OnLeftChannel; event EventHandler<OnLogArgs> OnLog; event EventHandler<OnMessageReceivedArgs> OnMessageReceived; event EventHandler<OnMessageSentArgs> OnMessageSent; event EventHandler<OnModeratorJoinedArgs> OnModeratorJoined; event EventHandler<OnModeratorLeftArgs> OnModeratorLeft; event EventHandler<OnModeratorsReceivedArgs> OnModeratorsReceived; event EventHandler<OnNewSubscriberArgs> OnNewSubscriber; event EventHandler<OnRaidNotificationArgs> OnRaidNotification; event EventHandler<OnReSubscriberArgs> OnReSubscriber; event EventHandler<OnSendReceiveDataArgs> OnSendReceiveData; event EventHandler<OnUserBannedArgs> OnUserBanned; event EventHandler<OnUserJoinedArgs> OnUserJoined; event EventHandler<OnUserLeftArgs> OnUserLeft; event EventHandler<OnUserStateChangedArgs> OnUserStateChanged; event EventHandler<OnUserTimedoutArgs> OnUserTimedout; event EventHandler<OnWhisperCommandReceivedArgs> OnWhisperCommandReceived; event EventHandler<OnWhisperReceivedArgs> OnWhisperReceived; event EventHandler<OnWhisperSentArgs> OnWhisperSent; event EventHandler<OnMessageThrottledEventArgs> OnMessageThrottled; event EventHandler<OnWhisperThrottledEventArgs> OnWhisperThrottled; event EventHandler<OnErrorEventArgs> OnError; event EventHandler<OnReconnectedEventArgs> OnReconnected; event EventHandler<OnVIPsReceivedArgs> OnVIPsReceived; event EventHandler<OnCommunitySubscriptionArgs> OnCommunitySubscription; event EventHandler<OnMessageClearedArgs> OnMessageCleared; event EventHandler<OnRequiresVerifiedEmailArgs> OnRequiresVerifiedEmail; event EventHandler<OnRequiresVerifiedPhoneNumberArgs> OnRequiresVerifiedPhoneNumber; event EventHandler<OnBannedEmailAliasArgs> OnBannedEmailAlias; event EventHandler<OnUserIntroArgs> OnUserIntro; event EventHandler<OnAnnouncementArgs> OnAnnouncement; void Initialize(ConnectionCredentials credentials, string channel = null, char chatCommandIdentifier = '!', char whisperCommandIdentifier = '!', bool autoReListenOnExceptions = true); void Initialize(ConnectionCredentials credentials, List<string> channels, char chatCommandIdentifier = '!', char whisperCommandIdentifier = '!', bool autoReListenOnExceptions = true); void SetConnectionCredentials(ConnectionCredentials credentials); void AddChatCommandIdentifier(char identifier); void AddWhisperCommandIdentifier(char identifier); void RemoveChatCommandIdentifier(char identifier); void RemoveWhisperCommandIdentifier(char identifier); bool Connect(); void Disconnect(); void Reconnect(); JoinedChannel GetJoinedChannel(string channel); void JoinChannel(string channel, bool overrideCheck = false); void LeaveChannel(JoinedChannel channel); void LeaveChannel(string channel); void OnReadLineTest(string rawIrc); void SendMessage(JoinedChannel channel, string message, bool dryRun = false); void SendMessage(string channel, string message, bool dryRun = false); void SendReply(JoinedChannel channel, string replyToId, string message, bool dryRun = false); void SendReply(string channel, string replyToId, string message, bool dryRun = false); void SendQueuedItem(string message); void SendRaw(string message); void SendWhisper(string receiver, string message, bool dryRun = false); } } namespace TwitchLib.Client.Extensions { public static class AnnoucementExt { public static void Announce(this ITwitchClient client, JoinedChannel channel, string message) { client.SendMessage(channel, ".announce " + message); } public static void Announce(this ITwitchClient client, string channel, string message) { client.SendMessage(channel, ".announce " + message); } } public static class BanUserExt { public static void BanUser(this ITwitchClient client, JoinedChannel channel, string viewer, string message = "", bool dryRun = false) { client.SendMessage(channel, ".ban " + viewer + " " + message); } public static void BanUser(this ITwitchClient client, string channel, string viewer, string message = "", bool dryRun = false) { JoinedChannel joinedChannel = client.GetJoinedChannel(channel); if (joinedChannel != null) { client.BanUser(joinedChannel, viewer, message, dryRun); } } } public static class ChangeChatColorExt { public static void ChangeChatColor(this ITwitchClient client, JoinedChannel channel, ChatColorPresets color) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) client.SendMessage(channel, $".color {color}"); } public static void ChangeChatColor(this ITwitchClient client, string channel, ChatColorPresets color) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) client.SendMessage(channel, $".color {color}"); } } public static class ClearChatExt { public static void ClearChat(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".clear"); } public static void ClearChat(this ITwitchClient client, string channel) { client.SendMessage(channel, ".clear"); } } public static class CommercialExt { public static void StartCommercial(this ITwitchClient client, JoinedChannel channel, CommercialLength length) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0086: Unknown result type (might be due to invalid IL or missing references) if ((int)length <= 90) { if ((int)length == 30) { client.SendMessage(channel, ".commercial 30"); return; } if ((int)length == 60) { client.SendMessage(channel, ".commercial 60"); return; } if ((int)length == 90) { client.SendMessage(channel, ".commercial 90"); return; } } else { if ((int)length == 120) { client.SendMessage(channel, ".commercial 120"); return; } if ((int)length == 150) { client.SendMessage(channel, ".commercial 150"); return; } if ((int)length == 180) { client.SendMessage(channel, ".commercial 180"); return; } } throw new ArgumentOutOfRangeException("length", length, null); } public static void StartCommercial(this ITwitchClient client, string channel, CommercialLength length) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0086: Unknown result type (might be due to invalid IL or missing references) if ((int)length <= 90) { if ((int)length == 30) { client.SendMessage(channel, ".commercial 30"); return; } if ((int)length == 60) { client.SendMessage(channel, ".commercial 60"); return; } if ((int)length == 90) { client.SendMessage(channel, ".commercial 90"); return; } } else { if ((int)length == 120) { client.SendMessage(channel, ".commercial 120"); return; } if ((int)length == 150) { client.SendMessage(channel, ".commercial 150"); return; } if ((int)length == 180) { client.SendMessage(channel, ".commercial 180"); return; } } throw new ArgumentOutOfRangeException("length", length, null); } } public static class DeleteMessageExt { public static void DeleteMessage(this ITwitchClient client, JoinedChannel channel, string messageId) { client.SendMessage(channel, ".delete " + messageId); } public static void DeleteMessage(this ITwitchClient client, string channel, string messageId) { client.SendMessage(channel, ".delete " + messageId); } public static void DeleteMessage(this ITwitchClient client, JoinedChannel channel, ChatMessage msg) { client.SendMessage(channel, ".delete " + msg.Id); } public static void DeleteMessage(this ITwitchClient client, string channel, ChatMessage msg) { client.SendMessage(channel, ".delete " + msg.Id); } } public static class EmoteOnlyExt { public static void EmoteOnlyOn(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".emoteonly"); } public static void EmoteOnlyOn(this ITwitchClient client, string channel) { client.SendMessage(channel, ".emoteonly"); } public static void EmoteOnlyOff(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".emoteonlyoff"); } public static void EmoteOnlyOff(this ITwitchClient client, string channel) { client.SendMessage(channel, ".emoteonlyoff"); } } public static class EventInvocationExt { public static void InvokeChannelStateChanged(this TwitchClient client, string channel, bool r9k, bool rituals, bool subOnly, int slowMode, bool emoteOnly, string broadcasterLanguage, TimeSpan followersOnly, bool mercury, string roomId) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown ChannelState channelState = new ChannelState(r9k, rituals, subOnly, slowMode, emoteOnly, broadcasterLanguage, channel, followersOnly, mercury, roomId); OnChannelStateChangedArgs args = new OnChannelStateChangedArgs { Channel = channel, ChannelState = channelState }; client.RaiseEvent("OnChannelStateChanged", args); } public static void InvokeChatCleared(this TwitchClient client, string channel) { OnChatClearedArgs args = new OnChatClearedArgs { Channel = channel }; client.RaiseEvent("OnChatCleared", args); } public static void InvokeChatCommandsReceived(this TwitchClient client, string botUsername, string userId, string userName, string displayName, string colorHex, Color color, EmoteSet emoteSet, string message, UserType userType, string channel, string id, bool isSubscriber, int subscribedMonthCount, string roomId, bool isTurbo, bool isModerator, bool isMe, bool isBroadcaster, bool isVip, bool isPartner, bool isStaff, Noisy noisy, string rawIrcMessage, string emoteReplacedMessage, List<KeyValuePair<string, string>> badges, CheerBadge cheerBadge, int bits, double bitsInDollars, string commandText, string argumentsAsString, List<string> argumentsAsList, char commandIdentifier) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Expected O, but got Unknown ChatMessage val = new ChatMessage(botUsername, userId, userName, displayName, colorHex, color, emoteSet, message, userType, channel, id, isSubscriber, subscribedMonthCount, roomId, isTurbo, isModerator, isMe, isBroadcaster, isVip, isPartner, isStaff, noisy, rawIrcMessage, emoteReplacedMessage, badges, cheerBadge, bits, bitsInDollars); OnChatCommandReceivedArgs args = new OnChatCommandReceivedArgs { Command = new ChatCommand(val, commandText, argumentsAsString, argumentsAsList, commandIdentifier) }; client.RaiseEvent("OnChatCommandReceived", args); } public static void InvokeConnected(this TwitchClient client, string autoJoinChannel, string botUsername) { OnConnectedArgs args = new OnConnectedArgs { AutoJoinChannel = autoJoinChannel, BotUsername = botUsername }; client.RaiseEvent("OnConnected", args); } public static void InvokeConnectionError(this TwitchClient client, string botUsername, ErrorEvent errorEvent) { OnConnectionErrorArgs args = new OnConnectionErrorArgs { BotUsername = botUsername, Error = errorEvent }; client.RaiseEvent("OnConnectionError", args); } public static void InvokeDisconnected(this TwitchClient client, string botUsername) { OnDisconnectedArgs args = new OnDisconnectedArgs { BotUsername = botUsername }; client.RaiseEvent("OnDisconnected", args); } public static void InvokeExistingUsersDetected(this TwitchClient client, string channel, List<string> users) { OnExistingUsersDetectedArgs args = new OnExistingUsersDetectedArgs { Channel = channel, Users = users }; client.RaiseEvent("OnExistingUsersDetected", args); } public static void InvokeGiftedSubscription(this TwitchClient client, List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string color, string displayName, string emotes, string id, string login, bool isModerator, string msgId, string msgParamMonths, string msgParamRecipientDisplayName, string msgParamRecipientId, string msgParamRecipientUserName, string msgParamSubPlanName, string msgMultiMonthGiftDuration, SubscriptionPlan msgParamSubPlan, string roomId, bool isSubscriber, string systemMsg, string systemMsgParsed, string tmiSentTs, bool isTurbo, UserType userType, string userId) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown OnGiftedSubscriptionArgs args = new OnGiftedSubscriptionArgs { GiftedSubscription = new GiftedSubscription(badges, badgeInfo, color, displayName, emotes, id, login, isModerator, msgId, msgParamMonths, msgParamRecipientDisplayName, msgParamRecipientId, msgParamRecipientUserName, msgParamSubPlanName, msgMultiMonthGiftDuration, msgParamSubPlan, roomId, isSubscriber, systemMsg, systemMsgParsed, tmiSentTs, isTurbo, userType, userId) }; client.RaiseEvent("OnGiftedSubscription", args); } public static void InvokeIncorrectLogin(this TwitchClient client, ErrorLoggingInException ex) { OnIncorrectLoginArgs args = new OnIncorrectLoginArgs { Exception = ex }; client.RaiseEvent("OnIncorrectLogin", args); } public static void InvokeJoinedChannel(this TwitchClient client, string botUsername, string channel) { OnJoinedChannelArgs args = new OnJoinedChannelArgs { BotUsername = botUsername, Channel = channel }; client.RaiseEvent("OnJoinedChannel", args); } public static void InvokeLeftChannel(this TwitchClient client, string botUsername, string channel) { OnLeftChannelArgs args = new OnLeftChannelArgs { BotUsername = botUsername, Channel = channel }; client.RaiseEvent("OnLeftChannel", args); } public static void InvokeLog(this TwitchClient client, string botUsername, string data, DateTime dateTime) { OnLogArgs args = new OnLogArgs { BotUsername = botUsername, Data = data, DateTime = dateTime }; client.RaiseEvent("OnLog", args); } public static void InvokeMessageReceived(this TwitchClient client, string botUsername, string userId, string userName, string displayName, string colorHex, Color color, EmoteSet emoteSet, string message, UserType userType, string channel, string id, bool isSubscriber, int subscribedMonthCount, string roomId, bool isTurbo, bool isModerator, bool isMe, bool isBroadcaster, bool isVip, bool isPartner, bool isStaff, Noisy noisy, string rawIrcMessage, string emoteReplacedMessage, List<KeyValuePair<string, string>> badges, CheerBadge cheerBadge, int bits, double bitsInDollars) { //IL_0013: 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) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown OnMessageReceivedArgs args = new OnMessageReceivedArgs { ChatMessage = new ChatMessage(botUsername, userId, userName, displayName, colorHex, color, emoteSet, message, userType, channel, id, isSubscriber, subscribedMonthCount, roomId, isTurbo, isModerator, isMe, isBroadcaster, isVip, isPartner, isStaff, noisy, rawIrcMessage, emoteReplacedMessage, badges, cheerBadge, bits, bitsInDollars) }; client.RaiseEvent("OnMessageReceived", args); } public static void InvokeMessageSent(this TwitchClient client, List<KeyValuePair<string, string>> badges, string channel, string colorHex, string displayName, string emoteSet, bool isModerator, bool isSubscriber, UserType userType, string message) { //IL_0011: 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_001f: Expected O, but got Unknown OnMessageSentArgs args = new OnMessageSentArgs { SentMessage = new SentMessage(badges, channel, colorHex, displayName, emoteSet, isModerator, isSubscriber, userType, message) }; client.RaiseEvent("OnMessageSent", args); } public static void InvokeModeratorJoined(this TwitchClient client, string channel, string username) { OnModeratorJoinedArgs args = new OnModeratorJoinedArgs { Channel = channel, Username = username }; client.RaiseEvent("OnModeratorJoined", args); } public static void InvokeModeratorLeft(this TwitchClient client, string channel, string username) { OnModeratorLeftArgs args = new OnModeratorLeftArgs { Channel = channel, Username = username }; client.RaiseEvent("OnModeratorLeft", args); } public static void InvokeModeratorsReceived(this TwitchClient client, string channel, List<string> moderators) { OnModeratorsReceivedArgs args = new OnModeratorsReceivedArgs { Channel = channel, Moderators = moderators }; client.RaiseEvent("OnModeratorsReceived", args); } public static void InvokeNewSubscriber(this TwitchClient client, List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string colorHex, Color color, string displayName, string emoteSet, string id, string login, string systemMessage, string msgId, string msgParamCumulativeMonths, string msgParamStreakMonths, bool msgParamShouldShareStreak, string systemMessageParsed, string resubMessage, SubscriptionPlan subscriptionPlan, string subscriptionPlanName, string roomId, string userId, bool isModerator, bool isTurbo, bool isSubscriber, bool isPartner, string tmiSentTs, UserType userType, string rawIrc, string channel) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown OnNewSubscriberArgs args = new OnNewSubscriberArgs { Subscriber = new Subscriber(badges, badgeInfo, colorHex, color, displayName, emoteSet, id, login, systemMessage, msgId, msgParamCumulativeMonths, msgParamStreakMonths, msgParamShouldShareStreak, systemMessageParsed, resubMessage, subscriptionPlan, subscriptionPlanName, roomId, userId, isModerator, isTurbo, isSubscriber, isPartner, tmiSentTs, userType, rawIrc, channel) }; client.RaiseEvent("OnNewSubscriber", args); } public static void InvokeRaidNotification(this TwitchClient client, string channel, List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string color, string displayName, string emotes, string id, string login, bool moderator, string msgId, string msgParamDisplayName, string msgParamLogin, string msgParamViewerCount, string roomId, bool subscriber, string systemMsg, string systemMsgParsed, string tmiSentTs, bool turbo, UserType userType, string userId) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown OnRaidNotificationArgs args = new OnRaidNotificationArgs { Channel = channel, RaidNotification = new RaidNotification(badges, badgeInfo, color, displayName, emotes, id, login, moderator, msgId, msgParamDisplayName, msgParamLogin, msgParamViewerCount, roomId, subscriber, systemMsg, systemMsgParsed, tmiSentTs, turbo, userType, userId) }; client.RaiseEvent("OnRaidNotification", args); } public static void InvokeReSubscriber(this TwitchClient client, List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string colorHex, Color color, string displayName, string emoteSet, string id, string login, string systemMessage, string msgId, string msgParamCumulativeMonths, string msgParamStreakMonths, bool msgParamShouldShareStreak, string systemMessageParsed, string resubMessage, SubscriptionPlan subscriptionPlan, string subscriptionPlanName, string roomId, string userId, bool isModerator, bool isTurbo, bool isSubscriber, bool isPartner, string tmiSentTs, UserType userType, string rawIrc, string channel) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown OnReSubscriberArgs args = new OnReSubscriberArgs { ReSubscriber = new ReSubscriber(badges, badgeInfo, colorHex, color, displayName, emoteSet, id, login, systemMessage, msgId, msgParamCumulativeMonths, msgParamStreakMonths, msgParamShouldShareStreak, systemMessageParsed, resubMessage, subscriptionPlan, subscriptionPlanName, roomId, userId, isModerator, isTurbo, isSubscriber, isPartner, tmiSentTs, userType, rawIrc, channel, 0) }; client.RaiseEvent("OnReSubscriber", args); } public static void InvokeSendReceiveData(this TwitchClient client, string data, SendReceiveDirection direction) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) OnSendReceiveDataArgs args = new OnSendReceiveDataArgs { Data = data, Direction = direction }; client.RaiseEvent("OnSendReceiveData", args); } public static void InvokeUserBanned(this TwitchClient client, string channel, string username, string banReason, string roomId, string targetUserId) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown OnUserBannedArgs args = new OnUserBannedArgs { UserBan = new UserBan(channel, username, banReason, roomId, targetUserId) }; client.RaiseEvent("OnUserBanned", args); } public static void InvokeUserJoined(this TwitchClient client, string channel, string username) { OnUserJoinedArgs args = new OnUserJoinedArgs { Channel = channel, Username = username }; client.RaiseEvent("OnUserJoined", args); } public static void InvokeUserLeft(this TwitchClient client, string channel, string username) { OnUserLeftArgs args = new OnUserLeftArgs { Channel = channel, Username = username }; client.RaiseEvent("OnUserLeft", args); } public static void InvokeUserStateChanged(this TwitchClient client, List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string colorHex, string displayName, string emoteSet, string channel, string id, bool isSubscriber, bool isModerator, UserType userType) { //IL_0015: 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) //IL_0021: Expected O, but got Unknown OnUserStateChangedArgs args = new OnUserStateChangedArgs { UserState = new UserState(badges, badgeInfo, colorHex, displayName, emoteSet, channel, id, isSubscriber, isModerator, userType) }; client.RaiseEvent("OnUserStateChanged", args); } public static void InvokeUserTimedout(this TwitchClient client, string channel, string username, string targetUserId, int timeoutDuration, string timeoutReason) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown OnUserTimedoutArgs args = new OnUserTimedoutArgs { UserTimeout = new UserTimeout(channel, username, targetUserId, timeoutDuration, timeoutReason) }; client.RaiseEvent("OnUserTimedout", args); } public static void InvokeWhisperCommandReceived(this TwitchClient client, List<KeyValuePair<string, string>> badges, string colorHex, Color color, string username, string displayName, EmoteSet emoteSet, string threadId, string messageId, string userId, bool isTurbo, string botUsername, string message, UserType userType, string commandText, string argumentsAsString, List<string> argumentsAsList, char commandIdentifier) { //IL_0015: 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) //IL_001d: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown WhisperMessage val = new WhisperMessage(badges, colorHex, color, username, displayName, emoteSet, threadId, messageId, userId, isTurbo, botUsername, message, userType); OnWhisperCommandReceivedArgs args = new OnWhisperCommandReceivedArgs { Command = new WhisperCommand(val, commandText, argumentsAsString, argumentsAsList, commandIdentifier) }; client.RaiseEvent("OnWhisperCommandReceived", args); } public static void InvokeWhisperReceived(this TwitchClient client, List<KeyValuePair<string, string>> badges, string colorHex, Color color, string username, string displayName, EmoteSet emoteSet, string threadId, string messageId, string userId, bool isTurbo, string botUsername, string message, UserType userType) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown OnWhisperReceivedArgs args = new OnWhisperReceivedArgs { WhisperMessage = new WhisperMessage(badges, colorHex, color, username, displayName, emoteSet, threadId, messageId, userId, isTurbo, botUsername, message, userType) }; client.RaiseEvent("OnWhisperReceived", args); } public static void InvokeWhisperSent(this TwitchClient client, string username, string receiver, string message) { OnWhisperSentArgs args = new OnWhisperSentArgs { Message = message, Receiver = receiver, Username = username }; client.RaiseEvent("OnWhisperSent", args); } } public static class FollowersOnlyExt { private const int MaximumDurationAllowedDays = 90; public static void FollowersOnlyOn(this ITwitchClient client, JoinedChannel channel, TimeSpan requiredFollowTime) { if (requiredFollowTime > TimeSpan.FromDays(90.0)) { throw new InvalidParameterException("The amount of time required to chat exceeded the maximum allowed by Twitch, which is 3 months.", client.TwitchUsername); } string text = $"{requiredFollowTime.Days}d {requiredFollowTime.Hours}h {requiredFollowTime.Minutes}m"; client.SendMessage(channel, ".followers " + text); } public static void FollowersOnlyOn(this ITwitchClient client, string channel, TimeSpan requiredFollowTime) { if (requiredFollowTime > TimeSpan.FromDays(90.0)) { throw new InvalidParameterException("The amount of time required to chat exceeded the maximum allowed by Twitch, which is 3 months.", client.TwitchUsername); } string text = $"{requiredFollowTime.Days}d {requiredFollowTime.Hours}h {requiredFollowTime.Minutes}m"; client.SendMessage(channel, ".followers " + text); } public static void FollowersOnlyOff(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".followersoff"); } public static void FollowersOnlyOff(this TwitchClient client, string channel) { client.SendMessage(channel, ".followersoff"); } } public static class GetChannelModeratorsExt { public static void GetChannelModerators(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".mods"); } public static void GetChannelModerators(this ITwitchClient client, string channel) { client.SendMessage(channel, ".mods"); } } public static class MarkerExt { public static void Marker(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".marker"); } public static void Marker(this ITwitchClient client, string channel) { client.SendMessage(channel, ".marker"); } } public static class ModExt { public static void Mod(this ITwitchClient client, JoinedChannel channel, string viewerToMod) { client.SendMessage(channel, ".mod " + viewerToMod); } public static void Mod(this ITwitchClient client, string channel, string viewerToMod) { client.SendMessage(channel, ".mod " + viewerToMod); } public static void Unmod(this ITwitchClient client, JoinedChannel channel, string viewerToUnmod) { client.SendMessage(channel, ".unmod " + viewerToUnmod); } public static void Unmod(this ITwitchClient client, string channel, string viewerToUnmod) { client.SendMessage(channel, ".unmod " + viewerToUnmod); } } public static class RaidExt { public static void Raid(this ITwitchClient client, JoinedChannel channel, string channelToRaid) { client.SendMessage(channel, ".raid " + channelToRaid); } public static void Raid(this ITwitchClient client, string channel, string channelToRaid) { client.SendMessage(channel, ".raid " + channelToRaid); } } public static class ReplyWhisperExt { public static void ReplyToLastWhisper(this ITwitchClient client, string message = "", bool dryRun = false) { if (client.PreviousWhisper != null) { client.SendWhisper(((TwitchLibMessage)client.PreviousWhisper).Username, message, dryRun); } } } public static class SlowModeExt { public static void SlowModeOn(this ITwitchClient client, JoinedChannel channel, TimeSpan messageCooldown) { if (messageCooldown > TimeSpan.FromDays(1.0)) { throw new InvalidParameterException("The message cooldown time supplied exceeded the maximum allowed by Twitch, which is 1 day.", client.TwitchUsername); } client.SendMessage(channel, $".slow {messageCooldown.TotalSeconds}"); } public static void SlowModeOn(this ITwitchClient client, string channel, TimeSpan messageCooldown) { if (messageCooldown > TimeSpan.FromDays(1.0)) { throw new InvalidParameterException("The message cooldown time supplied exceeded the maximum allowed by Twitch, which is 1 day.", client.TwitchUsername); } client.SendMessage(channel, $".slow {messageCooldown.TotalSeconds}"); } public static void SlowModeOff(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".slowoff"); } public static void SlowModeOff(this ITwitchClient client, string channel) { client.SendMessage(channel, ".slowoff"); } } public static class SubscribersOnly { public static void SubscribersOnlyOn(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".subscribers"); } public static void SubscribersOnlyOn(this ITwitchClient client, string channel) { client.SendMessage(channel, ".subscribers"); } public static void SubscribersOnlyOff(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".subscribersoff"); } public static void SubscribersOnlyOff(this ITwitchClient client, string channel) { client.SendMessage(channel, ".subscribersoff"); } } public static class TimeoutUserExt { public static void TimeoutUser(this ITwitchClient client, JoinedChannel channel, string viewer, TimeSpan duration, string message = "", bool dryRun = false) { client.SendMessage(channel, $".timeout {viewer} {duration.TotalSeconds} {message}", dryRun); } public static void TimeoutUser(this ITwitchClient client, string channel, string viewer, TimeSpan duration, string message = "", bool dryRun = false) { JoinedChannel joinedChannel = client.GetJoinedChannel(channel); if (joinedChannel != null) { client.TimeoutUser(joinedChannel, viewer, duration, message, dryRun); } } } public static class UnbanUserExt { public static void UnbanUser(this ITwitchClient client, JoinedChannel channel, string viewer, bool dryRun = false) { client.SendMessage(channel, ".unban " + viewer, dryRun); } public static void UnbanUser(this ITwitchClient client, string channel, string viewer, bool dryRun = false) { JoinedChannel joinedChannel = client.GetJoinedChannel(channel); if (joinedChannel != null) { client.UnbanUser(joinedChannel, viewer, dryRun); } } } public static class VIPExt { public static void VIP(this ITwitchClient client, JoinedChannel channel, string viewerToVIP) { client.SendMessage(channel, ".vip " + viewerToVIP); } public static void VIP(this ITwitchClient client, string channel, string viewerToVIP) { client.SendMessage(channel, ".vip " + viewerToVIP); } public static void UnVIP(this ITwitchClient client, JoinedChannel channel, string viewerToUnVIP) { client.SendMessage(channel, ".unvip " + viewerToUnVIP); } public static void UnVIP(this ITwitchClient client, string channel, string viewerToUnVIP) { client.SendMessage(channel, ".unvip " + viewerToUnVIP); } public static void GetVIPs(this ITwitchClient client, JoinedChannel channel) { client.SendMessage(channel, ".vips"); } public static void GetVIPs(this ITwitchClient client, string channel) { client.SendMessage(channel, ".vips"); } } } namespace TwitchLib.Client.Exceptions { public class BadListenException : Exception { public BadListenException(string eventName, string additionalDetails = "") : base(string.IsNullOrEmpty(additionalDetails) ? ("You are listening to event '" + eventName + "', which is not currently allowed. See details: " + additionalDetails) : ("You are listening to event '" + eventName + "', which is not currently allowed.")) { } } public class BadStateException : Exception { public BadStateException(string details) : base(details) { } } public class ClientNotConnectedException : Exception { public ClientNotConnectedException(string description) : base(description) { } } public class ClientNotInitializedException : Exception { public ClientNotInitializedException(string description) : base(description) { } } public class ErrorLoggingInException : Exception { public string Username { get; protected set; } public ErrorLoggingInException(string ircData, string twitchUsername) : base(ircData) { Username = twitchUsername; } } public class EventNotHandled : Exception { public EventNotHandled(string eventName, string additionalDetails = "") : base(string.IsNullOrEmpty(additionalDetails) ? ("To use this call, you must handle/subscribe to event: " + eventName) : ("To use this call, you must handle/subscribe to event: " + eventName + ", additional details: " + additionalDetails)) { } } public class FailureToReceiveJoinConfirmationException { public string Channel { get; protected set; } public string Details { get; protected set; }
plugins/TwitchLib.Client.Enums.dll
Decompiled 2 hours agousing System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021")] [assembly: AssemblyDescription("Project containing all of the enums used in TwitchLib.Client.")] [assembly: AssemblyFileVersion("3.3.1")] [assembly: AssemblyInformationalVersion("3.3.1")] [assembly: AssemblyProduct("TwitchLib.Client.Enums")] [assembly: AssemblyTitle("TwitchLib.Client.Enums")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.Client")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("3.3.1.0")] namespace TwitchLib.Client.Enums { public enum BadgeColor { Red = 10000, Blue = 5000, Green = 1000, Purple = 100, Gray = 1 } public enum ChatColorPresets { Blue, Coral, DodgerBlue, SpringGreen, YellowGreen, Green, OrangeRed, Red, GoldenRod, HotPink, CadetBlue, SeaGreen, Chocolate, BlueViolet, Firebrick } public enum ClientProtocol { TCP, WebSocket } public enum CommercialLength { Seconds30 = 30, Seconds60 = 60, Seconds90 = 90, Seconds120 = 120, Seconds150 = 150, Seconds180 = 180 } public enum Noisy { NotSet, True, False } public enum SendReceiveDirection { Sent, Received } public abstract class StringEnum { public string Value { get; } protected StringEnum(string value) { Value = value; } public override string ToString() { return Value; } } public enum SubscriptionPlan { NotSet, Prime, Tier1, Tier2, Tier3 } public enum ThrottleType { MessageTooShort, MessageTooLong } public enum UserType : byte { Viewer, Moderator, GlobalModerator, Broadcaster, Admin, Staff } } namespace TwitchLib.Client.Enums.Internal { public enum IrcCommand { Unknown, PrivMsg, Notice, Ping, Pong, Join, Part, ClearChat, ClearMsg, UserState, GlobalUserState, Nick, Pass, Cap, RPL_001, RPL_002, RPL_003, RPL_004, RPL_353, RPL_366, RPL_372, RPL_375, RPL_376, Whisper, RoomState, Reconnect, ServerChange, UserNotice, Mode } }
plugins/TwitchLib.Client.Models.dll
Decompiled 2 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using TwitchLib.Client.Enums; using TwitchLib.Client.Enums.Internal; using TwitchLib.Client.Models.Builders; using TwitchLib.Client.Models.Common; using TwitchLib.Client.Models.Extensions.NetCore; using TwitchLib.Client.Models.Extractors; using TwitchLib.Client.Models.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021")] [assembly: AssemblyDescription("Project contains all of the models used in TwitchLib.Client.")] [assembly: AssemblyFileVersion("3.3.1")] [assembly: AssemblyInformationalVersion("3.3.1")] [assembly: AssemblyProduct("TwitchLib.Client.Models")] [assembly: AssemblyTitle("TwitchLib.Client.Models")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.Client")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("3.3.1.0")] namespace TwitchLib.Client.Models { public class Announcement { public string Id { get; } public List<KeyValuePair<string, string>> Badges { get; } public List<KeyValuePair<string, string>> BadgeInfo { get; } public string SystemMessage { get; } public string SystemMessageParsed { get; } public bool IsBroadcaster { get; } public bool IsModerator { get; } public bool IsPartner { get; } public bool IsSubscriber { get; } public bool IsStaff { get; } public bool IsTurbo { get; } public string Login { get; } public string UserId { get; } public string RoomId { get; } public UserType UserType { get; } public string TmiSentTs { get; } public string EmoteSet { get; } public string RawIrc { get; } public string MsgId { get; } public string MsgParamColor { get; } public string ColorHex { get; } public Color Color { get; } public string Message { get; } public Announcement(IrcMessage ircMessage) { //IL_047c: Unknown result type (might be due to invalid IL or missing references) //IL_0485: Unknown result type (might be due to invalid IL or missing references) //IL_048e: Unknown result type (might be due to invalid IL or missing references) //IL_0497: Unknown result type (might be due to invalid IL or missing references) //IL_04a0: Unknown result type (might be due to invalid IL or missing references) RawIrc = ircMessage.ToString(); Message = ircMessage.Message; foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "badges": { Badges = Helpers.ParseBadges(text); using (List<KeyValuePair<string, string>>.Enumerator enumerator2 = Badges.GetEnumerator()) { while (enumerator2.MoveNext()) { switch (enumerator2.Current.Key) { case "broadcaster": IsBroadcaster = true; break; case "turbo": IsTurbo = true; break; case "moderator": IsModerator = true; break; case "subscriber": IsSubscriber = true; break; case "admin": IsStaff = true; break; case "staff": IsStaff = true; break; case "partner": IsPartner = true; break; } } } break; } case "badge-info": BadgeInfo = Helpers.ParseBadges(text); break; case "color": ColorHex = text; if (!string.IsNullOrEmpty(ColorHex)) { Color = TwitchLib.Client.Models.Extensions.NetCore.ColorTranslator.FromHtml(ColorHex); } break; case "msg-param-color": MsgParamColor = text; break; case "emotes": EmoteSet = text; break; case "id": Id = text; break; case "login": Login = text; break; case "msg-id": MsgId = text; break; case "room-id": RoomId = text; break; case "system-msg": SystemMessage = text; SystemMessageParsed = text.Replace("\\s", " "); break; case "tmi-sent-ts": TmiSentTs = text; break; case "user-id": UserId = text; break; case "user-type": switch (text) { case "mod": UserType = (UserType)1; break; case "global_mod": UserType = (UserType)2; break; case "admin": UserType = (UserType)4; break; case "staff": UserType = (UserType)5; break; default: UserType = (UserType)0; break; } break; } } } } public class ChannelState { public string BroadcasterLanguage { get; } public string Channel { get; } public bool? EmoteOnly { get; } public TimeSpan? FollowersOnly { get; } public bool Mercury { get; } public bool? R9K { get; } public bool? Rituals { get; } public string RoomId { get; } public int? SlowMode { get; } public bool? SubOnly { get; } public ChannelState(IrcMessage ircMessage) { foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "broadcaster-lang": BroadcasterLanguage = text; break; case "emote-only": EmoteOnly = Helpers.ConvertToBool(text); break; case "r9k": R9K = Helpers.ConvertToBool(text); break; case "rituals": Rituals = Helpers.ConvertToBool(text); break; case "slow": { int result2; bool flag = int.TryParse(text, out result2); SlowMode = (flag ? new int?(result2) : null); break; } case "subs-only": SubOnly = Helpers.ConvertToBool(text); break; case "followers-only": { if (int.TryParse(text, out var result) && result > -1) { FollowersOnly = TimeSpan.FromMinutes(result); } break; } case "room-id": RoomId = text; break; case "mercury": Mercury = Helpers.ConvertToBool(text); break; default: Console.WriteLine("[TwitchLib][ChannelState] Unaccounted for: " + key); break; } } Channel = ircMessage.Channel; } public ChannelState(bool r9k, bool rituals, bool subonly, int slowMode, bool emoteOnly, string broadcasterLanguage, string channel, TimeSpan followersOnly, bool mercury, string roomId) { R9K = r9k; Rituals = rituals; SubOnly = subonly; SlowMode = slowMode; EmoteOnly = emoteOnly; BroadcasterLanguage = broadcasterLanguage; Channel = channel; FollowersOnly = followersOnly; Mercury = mercury; RoomId = roomId; } } public class ChatCommand { public List<string> ArgumentsAsList { get; } public string ArgumentsAsString { get; } public ChatMessage ChatMessage { get; } public char CommandIdentifier { get; } public string CommandText { get; } public ChatCommand(ChatMessage chatMessage) { ChatCommand chatCommand = this; ChatMessage = chatMessage; string[] array = chatMessage.Message.Split(new char[1] { ' ' }); CommandText = ((array != null) ? array[0].Substring(1, chatMessage.Message.Split(new char[1] { ' ' })[0].Length - 1) : null) ?? chatMessage.Message.Substring(1, chatMessage.Message.Length - 1); object obj; if (!chatMessage.Message.Contains(" ")) { obj = ""; } else { string message = chatMessage.Message; string[] array2 = chatMessage.Message.Split(new char[1] { ' ' }); obj = message.Replace(((array2 != null) ? array2[0] : null) + " ", ""); } ArgumentsAsString = (string)obj; if (!chatMessage.Message.Contains("\"") || chatMessage.Message.Count((char x) => x == '"') % 2 == 1) { ArgumentsAsList = chatMessage.Message.Split(new char[1] { ' ' })?.Where((string arg) => arg != chatMessage.Message[0] + chatCommand.CommandText).ToList() ?? new List<string>(); } else { ArgumentsAsList = Helpers.ParseQuotesAndNonQuotes(ArgumentsAsString); } CommandIdentifier = chatMessage.Message[0]; } public ChatCommand(ChatMessage chatMessage, string commandText, string argumentsAsString, List<string> argumentsAsList, char commandIdentifier) { ChatMessage = chatMessage; CommandText = commandText; ArgumentsAsString = argumentsAsString; ArgumentsAsList = argumentsAsList; CommandIdentifier = commandIdentifier; } } public class ChatMessage : TwitchLibMessage { protected readonly MessageEmoteCollection _emoteCollection; public List<KeyValuePair<string, string>> BadgeInfo { get; } public int Bits { get; } public double BitsInDollars { get; } public string Channel { get; } public CheerBadge CheerBadge { get; } public string CustomRewardId { get; } public string EmoteReplacedMessage { get; } public string Id { get; } public bool IsBroadcaster { get; } public bool IsFirstMessage { get; } public bool IsHighlighted { get; internal set; } public bool IsMe { get; } public bool IsModerator { get; } public bool IsSkippingSubMode { get; internal set; } public bool IsSubscriber { get; } public bool IsVip { get; } public bool IsStaff { get; } public bool IsPartner { get; } public string Message { get; } public Noisy Noisy { get; } public string RoomId { get; } public int SubscribedMonthCount { get; } public string TmiSentTs { get; } public ChatReply ChatReply { get; } public ChatMessage(string botUsername, IrcMessage ircMessage, ref MessageEmoteCollection emoteCollection, bool replaceEmotes = false) { //IL_06f9: Unknown result type (might be due to invalid IL or missing references) base.BotUsername = botUsername; base.RawIrcMessage = ircMessage.ToString(); Message = ircMessage.Message; if (Message.Length > 0 && (byte)Message[0] == 1 && (byte)Message[Message.Length - 1] == 1 && Message.StartsWith("\u0001ACTION ") && Message.EndsWith("\u0001")) { Message = Message.Trim(new char[1] { '\u0001' }).Substring(7); IsMe = true; } _emoteCollection = emoteCollection; base.Username = ircMessage.User; Channel = ircMessage.Channel; foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "badges": base.Badges = Helpers.ParseBadges(text); foreach (KeyValuePair<string, string> badge in base.Badges) { switch (badge.Key) { case "bits": CheerBadge = new CheerBadge(int.Parse(badge.Value)); break; case "subscriber": if (SubscribedMonthCount == 0) { SubscribedMonthCount = int.Parse(badge.Value); } break; case "vip": IsVip = true; break; case "admin": IsStaff = true; break; case "staff": IsStaff = true; break; case "partner": IsPartner = true; break; } } break; case "badge-info": { BadgeInfo = Helpers.ParseBadges(text); KeyValuePair<string, string> keyValuePair = BadgeInfo.Find((KeyValuePair<string, string> b) => b.Key == "founder"); if (!keyValuePair.Equals(default(KeyValuePair<string, string>))) { IsSubscriber = true; SubscribedMonthCount = int.Parse(keyValuePair.Value); break; } KeyValuePair<string, string> keyValuePair2 = BadgeInfo.Find((KeyValuePair<string, string> b) => b.Key == "subscriber"); if (!keyValuePair2.Equals(default(KeyValuePair<string, string>))) { SubscribedMonthCount = int.Parse(keyValuePair2.Value); } break; } case "bits": Bits = int.Parse(text); BitsInDollars = ConvertBitsToUsd(Bits); break; case "color": base.ColorHex = text; if (!string.IsNullOrWhiteSpace(base.ColorHex)) { base.Color = TwitchLib.Client.Models.Extensions.NetCore.ColorTranslator.FromHtml(base.ColorHex); } break; case "custom-reward-id": CustomRewardId = text; break; case "display-name": base.DisplayName = text; break; case "emotes": base.EmoteSet = new EmoteSet(text, Message); break; case "first-msg": IsFirstMessage = text == "1"; break; case "id": Id = text; break; case "msg-id": handleMsgId(text); break; case "mod": IsModerator = Helpers.ConvertToBool(text); break; case "noisy": Noisy = (Noisy)(Helpers.ConvertToBool(text) ? 1 : 2); break; case "reply-parent-display-name": if (ChatReply == null) { ChatReply = new ChatReply(); } ChatReply.ParentDisplayName = text; break; case "reply-parent-msg-body": if (ChatReply == null) { ChatReply = new ChatReply(); } ChatReply.ParentMsgBody = text; break; case "reply-parent-msg-id": if (ChatReply == null) { ChatReply = new ChatReply(); } ChatReply.ParentMsgId = text; break; case "reply-parent-user-id": if (ChatReply == null) { ChatReply = new ChatReply(); } ChatReply.ParentUserId = text; break; case "reply-parent-user-login": if (ChatReply == null) { ChatReply = new ChatReply(); } ChatReply.ParentUserLogin = text; break; case "room-id": RoomId = text; break; case "subscriber": IsSubscriber = IsSubscriber || Helpers.ConvertToBool(text); break; case "tmi-sent-ts": TmiSentTs = text; break; case "turbo": base.IsTurbo = Helpers.ConvertToBool(text); break; case "user-id": base.UserId = text; break; case "user-type": switch (text) { case "mod": base.UserType = (UserType)1; break; case "global_mod": base.UserType = (UserType)2; break; case "admin": base.UserType = (UserType)4; IsStaff = true; break; case "staff": base.UserType = (UserType)5; IsStaff = true; break; default: base.UserType = (UserType)0; break; } break; } } if (base.EmoteSet != null && Message != null && base.EmoteSet.Emotes.Count > 0) { string[] array = base.EmoteSet.RawEmoteSetString.Split(new char[1] { '/' }); foreach (string text2 in array) { int num = text2.IndexOf(':'); int num2 = text2.IndexOf(','); if (num2 == -1) { num2 = text2.Length; } int num3 = text2.IndexOf('-'); if (num > 0 && num3 > num && num2 > num3 && int.TryParse(text2.Substring(num + 1, num3 - num - 1), out var result) && int.TryParse(text2.Substring(num3 + 1, num2 - num3 - 1), out var result2) && result >= 0 && result < result2 && result2 < Message.Length) { string id = text2.Substring(0, num); string text3 = Message.Substring(result, result2 - result + 1); _emoteCollection.Add(new MessageEmote(id, text3)); } } if (replaceEmotes) { EmoteReplacedMessage = _emoteCollection.ReplaceEmotes(Message); } } if (base.EmoteSet == null) { base.EmoteSet = new EmoteSet((string)null, Message); } if (string.IsNullOrEmpty(base.DisplayName)) { base.DisplayName = base.Username; } if (string.Equals(Channel, base.Username, StringComparison.InvariantCultureIgnoreCase)) { base.UserType = (UserType)3; IsBroadcaster = true; } if (Channel.Split(new char[1] { ':' }).Length == 3 && string.Equals(Channel.Split(new char[1] { ':' })[1], base.UserId, StringComparison.InvariantCultureIgnoreCase)) { base.UserType = (UserType)3; IsBroadcaster = true; } } public ChatMessage(string botUsername, string userId, string userName, string displayName, string colorHex, Color color, EmoteSet emoteSet, string message, UserType userType, string channel, string id, bool isSubscriber, int subscribedMonthCount, string roomId, bool isTurbo, bool isModerator, bool isMe, bool isBroadcaster, bool isVip, bool isPartner, bool isStaff, Noisy noisy, string rawIrcMessage, string emoteReplacedMessage, List<KeyValuePair<string, string>> badges, CheerBadge cheerBadge, int bits, double bitsInDollars) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) base.BotUsername = botUsername; base.UserId = userId; base.DisplayName = displayName; base.ColorHex = colorHex; base.Color = color; base.EmoteSet = emoteSet; Message = message; base.UserType = userType; Channel = channel; Id = id; IsSubscriber = isSubscriber; SubscribedMonthCount = subscribedMonthCount; RoomId = roomId; base.IsTurbo = isTurbo; IsModerator = isModerator; IsMe = isMe; IsBroadcaster = isBroadcaster; IsVip = isVip; IsPartner = isPartner; IsStaff = isStaff; Noisy = noisy; base.RawIrcMessage = rawIrcMessage; EmoteReplacedMessage = emoteReplacedMessage; base.Badges = badges; CheerBadge = cheerBadge; Bits = bits; BitsInDollars = bitsInDollars; base.Username = userName; } private void handleMsgId(string val) { if (!(val == "highlighted-message")) { if (val == "skip-subs-mode-message") { IsSkippingSubMode = true; } } else { IsHighlighted = true; } } private static double ConvertBitsToUsd(int bits) { if (bits < 1500) { return (double)bits / 100.0 * 1.4; } if (bits < 5000) { return (double)bits / 1500.0 * 19.95; } if (bits < 10000) { return (double)bits / 5000.0 * 64.4; } if (bits < 25000) { return (double)bits / 10000.0 * 126.0; } return (double)bits / 25000.0 * 308.0; } } public class ChatReply { public string ParentDisplayName { get; internal set; } public string ParentMsgBody { get; internal set; } public string ParentMsgId { get; internal set; } public string ParentUserId { get; internal set; } public string ParentUserLogin { get; internal set; } } public class CheerBadge { public int CheerAmount { get; } public BadgeColor Color { get; } public CheerBadge(int cheerAmount) { //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) CheerAmount = cheerAmount; Color = GetColor(cheerAmount); } private BadgeColor GetColor(int cheerAmount) { if (cheerAmount < 10000) { if (cheerAmount < 5000) { if (cheerAmount < 1000) { if (cheerAmount >= 100) { return (BadgeColor)100; } return (BadgeColor)1; } return (BadgeColor)1000; } return (BadgeColor)5000; } return (BadgeColor)10000; } } public class CommunitySubscription { private const string AnonymousGifterUserId = "274598607"; public List<KeyValuePair<string, string>> Badges; public List<KeyValuePair<string, string>> BadgeInfo; public string Color; public string DisplayName; public string Emotes; public string Id; public string Login; public bool IsModerator; public bool IsAnonymous; public string MsgId; public int MsgParamMassGiftCount; public int MsgParamSenderCount; public SubscriptionPlan MsgParamSubPlan; public string RoomId; public bool IsSubscriber; public string SystemMsg; public string SystemMsgParsed; public string TmiSentTs; public bool IsTurbo; public string UserId; public UserType UserType; public string MsgParamMultiMonthGiftDuration; public CommunitySubscription(IrcMessage ircMessage) { //IL_03cb: Unknown result type (might be due to invalid IL or missing references) //IL_03d7: Unknown result type (might be due to invalid IL or missing references) //IL_04eb: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_04f4: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_04fd: Unknown result type (might be due to invalid IL or missing references) //IL_0506: Unknown result type (might be due to invalid IL or missing references) //IL_050f: Unknown result type (might be due to invalid IL or missing references) foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "badges": Badges = Helpers.ParseBadges(text); break; case "badge-info": BadgeInfo = Helpers.ParseBadges(text); break; case "color": Color = text; break; case "display-name": DisplayName = text; break; case "emotes": Emotes = text; break; case "id": Id = text; break; case "login": Login = text; break; case "mod": IsModerator = Helpers.ConvertToBool(text); break; case "msg-id": MsgId = text; break; case "msg-param-sub-plan": switch (text) { case "prime": MsgParamSubPlan = (SubscriptionPlan)1; break; case "1000": MsgParamSubPlan = (SubscriptionPlan)2; break; case "2000": MsgParamSubPlan = (SubscriptionPlan)3; break; case "3000": MsgParamSubPlan = (SubscriptionPlan)4; break; default: throw new ArgumentOutOfRangeException("ToLower"); } break; case "msg-param-mass-gift-count": MsgParamMassGiftCount = int.Parse(text); break; case "msg-param-sender-count": MsgParamSenderCount = int.Parse(text); break; case "room-id": RoomId = text; break; case "subscriber": IsSubscriber = Helpers.ConvertToBool(text); break; case "system-msg": SystemMsg = text; SystemMsgParsed = text.Replace("\\s", " ").Replace("\\n", ""); break; case "tmi-sent-ts": TmiSentTs = text; break; case "turbo": IsTurbo = Helpers.ConvertToBool(text); break; case "user-id": UserId = text; if (UserId == "274598607") { IsAnonymous = true; } break; case "user-type": switch (text) { case "mod": UserType = (UserType)1; break; case "global_mod": UserType = (UserType)2; break; case "admin": UserType = (UserType)4; break; case "staff": UserType = (UserType)5; break; default: UserType = (UserType)0; break; } break; case "msg-param-gift-months": MsgParamMultiMonthGiftDuration = text; break; } } } } public class ConnectionCredentials { public const string DefaultWebSocketUri = "wss://irc-ws.chat.twitch.tv:443"; public string TwitchWebsocketURI { get; } public string TwitchOAuth { get; } public string TwitchUsername { get; } public Capabilities Capabilities { get; } public ConnectionCredentials(string twitchUsername, string twitchOAuth, string twitchWebsocketURI = "wss://irc-ws.chat.twitch.tv:443", bool disableUsernameCheck = false, Capabilities capabilities = null) { if (!disableUsernameCheck && !new Regex("^([a-zA-Z0-9][a-zA-Z0-9_]{3,25})$").Match(twitchUsername).Success) { throw new Exception("Twitch username does not appear to be valid. " + twitchUsername); } TwitchUsername = twitchUsername.ToLower(); TwitchOAuth = twitchOAuth; if (!twitchOAuth.Contains(":")) { TwitchOAuth = "oauth:" + twitchOAuth.Replace("oauth", ""); } TwitchWebsocketURI = twitchWebsocketURI; if (capabilities == null) { capabilities = new Capabilities(); } Capabilities = capabilities; } } public class Capabilities { public bool Membership { get; } public bool Tags { get; } public bool Commands { get; } public Capabilities(bool membership = true, bool tags = true, bool commands = true) { Membership = membership; Tags = tags; Commands = commands; } } public class ContinuedGiftedSubscription { public List<KeyValuePair<string, string>> Badges { get; } public List<KeyValuePair<string, string>> BadgeInfo { get; } public string Color { get; } public string DisplayName { get; } public string Emotes { get; } public string Flags { get; } public string Id { get; } public string Login { get; } public bool IsModerator { get; } public string MsgId { get; } public string MsgParamSenderLogin { get; } public string MsgParamSenderName { get; } public string RoomId { get; } public bool IsSubscriber { get; } public string SystemMsg { get; } public string TmiSentTs { get; } public string UserId { get; } public UserType UserType { get; } public ContinuedGiftedSubscription(IrcMessage ircMessage) { //IL_03e7: Unknown result type (might be due to invalid IL or missing references) //IL_03f0: Unknown result type (might be due to invalid IL or missing references) //IL_03f9: Unknown result type (might be due to invalid IL or missing references) //IL_0402: Unknown result type (might be due to invalid IL or missing references) //IL_040b: Unknown result type (might be due to invalid IL or missing references) foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "system-msg": SystemMsg = text; break; case "flags": Flags = text; break; case "msg-param-sender-login": MsgParamSenderLogin = text; break; case "msg-param-sender-name": MsgParamSenderName = text; break; case "badges": Badges = Helpers.ParseBadges(text); break; case "badge-info": BadgeInfo = Helpers.ParseBadges(text); break; case "color": Color = text; break; case "display-name": DisplayName = text; break; case "emotes": Emotes = text; break; case "id": Id = text; break; case "login": Login = text; break; case "mod": IsModerator = Helpers.ConvertToBool(text); break; case "msg-id": MsgId = text; break; case "room-id": RoomId = text; break; case "subscriber": IsSubscriber = Helpers.ConvertToBool(text); break; case "tmi-sent-ts": TmiSentTs = text; break; case "user-id": UserId = text; break; case "user-type": switch (text) { case "mod": UserType = (UserType)1; break; case "global_mod": UserType = (UserType)2; break; case "admin": UserType = (UserType)4; break; case "staff": UserType = (UserType)5; break; default: UserType = (UserType)0; break; } break; } } } } public class Emote { public string Id { get; } public string Name { get; } public int StartIndex { get; } public int EndIndex { get; } public string ImageUrl { get; } public Emote(string emoteId, string name, int emoteStartIndex, int emoteEndIndex) { Id = emoteId; Name = name; StartIndex = emoteStartIndex; EndIndex = emoteEndIndex; ImageUrl = "https://static-cdn.jtvnw.net/emoticons/v1/" + emoteId + "/1.0"; } } public class EmoteSet { public List<Emote> Emotes { get; } public string RawEmoteSetString { get; } public EmoteSet(string rawEmoteSetString, string message) { RawEmoteSetString = rawEmoteSetString; EmoteExtractor emoteExtractor = new EmoteExtractor(); Emotes = emoteExtractor.Extract(rawEmoteSetString, message).ToList(); } public EmoteSet(IEnumerable<Emote> emotes, string emoteSetData) { RawEmoteSetString = emoteSetData; Emotes = emotes.ToList(); } } public class ErrorEvent { public string Message { get; set; } } public class GiftedSubscription { private const string AnonymousGifterUserId = "274598607"; public List<KeyValuePair<string, string>> Badges { get; } public List<KeyValuePair<string, string>> BadgeInfo { get; } public string Color { get; } public string DisplayName { get; } public string Emotes { get; } public string Id { get; } public bool IsModerator { get; } public bool IsSubscriber { get; } public bool IsTurbo { get; } public bool IsAnonymous { get; } public string Login { get; } public string MsgId { get; } public string MsgParamMonths { get; } public string MsgParamRecipientDisplayName { get; } public string MsgParamRecipientId { get; } public string MsgParamRecipientUserName { get; } public string MsgParamSubPlanName { get; } public SubscriptionPlan MsgParamSubPlan { get; } public string RoomId { get; } public string SystemMsg { get; } public string SystemMsgParsed { get; } public string TmiSentTs { get; } public string UserId { get; } public UserType UserType { get; } public string MsgParamMultiMonthGiftDuration { get; } public GiftedSubscription(IrcMessage ircMessage) { //IL_0467: Unknown result type (might be due to invalid IL or missing references) //IL_0473: Unknown result type (might be due to invalid IL or missing references) //IL_047f: Unknown result type (might be due to invalid IL or missing references) //IL_0565: Unknown result type (might be due to invalid IL or missing references) //IL_048b: Unknown result type (might be due to invalid IL or missing references) //IL_056e: Unknown result type (might be due to invalid IL or missing references) //IL_0577: Unknown result type (might be due to invalid IL or missing references) //IL_0580: Unknown result type (might be due to invalid IL or missing references) //IL_0589: Unknown result type (might be due to invalid IL or missing references) foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "badges": Badges = Helpers.ParseBadges(text); break; case "badge-info": BadgeInfo = Helpers.ParseBadges(text); break; case "color": Color = text; break; case "display-name": DisplayName = text; break; case "emotes": Emotes = text; break; case "id": Id = text; break; case "login": Login = text; break; case "mod": IsModerator = Helpers.ConvertToBool(text); break; case "msg-id": MsgId = text; break; case "msg-param-months": MsgParamMonths = text; break; case "msg-param-recipient-display-name": MsgParamRecipientDisplayName = text; break; case "msg-param-recipient-id": MsgParamRecipientId = text; break; case "msg-param-recipient-user-name": MsgParamRecipientUserName = text; break; case "msg-param-sub-plan-name": MsgParamSubPlanName = text; break; case "msg-param-sub-plan": switch (text) { case "prime": MsgParamSubPlan = (SubscriptionPlan)1; break; case "1000": MsgParamSubPlan = (SubscriptionPlan)2; break; case "2000": MsgParamSubPlan = (SubscriptionPlan)3; break; case "3000": MsgParamSubPlan = (SubscriptionPlan)4; break; default: throw new ArgumentOutOfRangeException("ToLower"); } break; case "room-id": RoomId = text; break; case "subscriber": IsSubscriber = Helpers.ConvertToBool(text); break; case "system-msg": SystemMsg = text; SystemMsgParsed = text.Replace("\\s", " ").Replace("\\n", ""); break; case "tmi-sent-ts": TmiSentTs = text; break; case "turbo": IsTurbo = Helpers.ConvertToBool(text); break; case "user-id": UserId = text; if (UserId == "274598607") { IsAnonymous = true; } break; case "user-type": switch (text) { case "mod": UserType = (UserType)1; break; case "global_mod": UserType = (UserType)2; break; case "admin": UserType = (UserType)4; break; case "staff": UserType = (UserType)5; break; default: UserType = (UserType)0; break; } break; case "msg-param-gift-months": MsgParamMultiMonthGiftDuration = text; break; } } } public GiftedSubscription(List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string color, string displayName, string emotes, string id, string login, bool isModerator, string msgId, string msgParamMonths, string msgParamRecipientDisplayName, string msgParamRecipientId, string msgParamRecipientUserName, string msgParamSubPlanName, string msgMultiMonthDuration, SubscriptionPlan msgParamSubPlan, string roomId, bool isSubscriber, string systemMsg, string systemMsgParsed, string tmiSentTs, bool isTurbo, UserType userType, string userId) { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) Badges = badges; BadgeInfo = badgeInfo; Color = color; DisplayName = displayName; Emotes = emotes; Id = id; Login = login; IsModerator = isModerator; MsgId = msgId; MsgParamMonths = msgParamMonths; MsgParamRecipientDisplayName = msgParamRecipientDisplayName; MsgParamRecipientId = msgParamRecipientId; MsgParamRecipientUserName = msgParamRecipientUserName; MsgParamSubPlanName = msgParamSubPlanName; MsgParamSubPlan = msgParamSubPlan; MsgParamMultiMonthGiftDuration = msgMultiMonthDuration; RoomId = roomId; IsSubscriber = isSubscriber; SystemMsg = systemMsg; SystemMsgParsed = systemMsgParsed; TmiSentTs = tmiSentTs; IsTurbo = isTurbo; UserType = userType; UserId = userId; } } public class JoinedChannel { public string Channel { get; } public ChannelState ChannelState { get; protected set; } public ChatMessage PreviousMessage { get; protected set; } public JoinedChannel(string channel) { Channel = channel; } public void HandleMessage(ChatMessage message) { PreviousMessage = message; } } public class MessageEmote { public delegate string ReplaceEmoteDelegate(MessageEmote caller); public enum EmoteSource { Twitch, FrankerFaceZ, BetterTwitchTv } public enum EmoteSize { Small, Medium, Large } public static readonly ReadOnlyCollection<string> TwitchEmoteUrls = new ReadOnlyCollection<string>(new string[3] { "https://static-cdn.jtvnw.net/emoticons/v1/{0}/1.0", "https://static-cdn.jtvnw.net/emoticons/v1/{0}/2.0", "https://static-cdn.jtvnw.net/emoticons/v1/{0}/3.0" }); public static readonly ReadOnlyCollection<string> FrankerFaceZEmoteUrls = new ReadOnlyCollection<string>(new string[3] { "//cdn.frankerfacez.com/emoticon/{0}/1", "//cdn.frankerfacez.com/emoticon/{0}/2", "//cdn.frankerfacez.com/emoticon/{0}/4" }); public static readonly ReadOnlyCollection<string> BetterTwitchTvEmoteUrls = new ReadOnlyCollection<string>(new string[3] { "//cdn.betterttv.net/emote/{0}/1x", "//cdn.betterttv.net/emote/{0}/2x", "//cdn.betterttv.net/emote/{0}/3x" }); private readonly string _id; private readonly string _text; private readonly string _escapedText; private readonly EmoteSource _source; private readonly EmoteSize _size; public string Id => _id; public string Text => _text; public EmoteSource Source => _source; public EmoteSize Size => _size; public string ReplacementString => ReplacementDelegate(this); public static ReplaceEmoteDelegate ReplacementDelegate { get; set; } = SourceMatchingReplacementText; public string EscapedText => _escapedText; public static string SourceMatchingReplacementText(MessageEmote caller) { int size = (int)caller.Size; return caller.Source switch { EmoteSource.BetterTwitchTv => string.Format(BetterTwitchTvEmoteUrls[size], caller.Id), EmoteSource.FrankerFaceZ => string.Format(FrankerFaceZEmoteUrls[size], caller.Id), EmoteSource.Twitch => string.Format(TwitchEmoteUrls[size], caller.Id), _ => caller.Text, }; } public MessageEmote(string id, string text, EmoteSource source = EmoteSource.Twitch, EmoteSize size = EmoteSize.Small, ReplaceEmoteDelegate replacementDelegate = null) { _id = id; _text = text; _escapedText = Regex.Escape(text); _source = source; _size = size; if (replacementDelegate != null) { ReplacementDelegate = replacementDelegate; } } } public class MessageEmoteCollection { public delegate bool EmoteFilterDelegate(MessageEmote emote); private readonly SortedList<string, MessageEmote> _emoteList; private const string BasePattern = "(\\b{0}\\b)"; private string _currentPattern; private Regex _regex; private readonly EmoteFilterDelegate _preferredFilter; private string CurrentPattern { get { return _currentPattern; } set { if (_currentPattern == null || !_currentPattern.Equals(value)) { _currentPattern = value; PatternChanged = true; } } } private Regex CurrentRegex { get { if (PatternChanged) { if (CurrentPattern != null) { _regex = new Regex(string.Format(CurrentPattern, "")); PatternChanged = false; } else { _regex = null; } } return _regex; } } private bool PatternChanged { get; set; } private EmoteFilterDelegate CurrentEmoteFilter { get; set; } = AllInclusiveEmoteFilter; public MessageEmoteCollection() { _emoteList = new SortedList<string, MessageEmote>(); _preferredFilter = AllInclusiveEmoteFilter; } public MessageEmoteCollection(EmoteFilterDelegate preferredFilter) : this() { _preferredFilter = preferredFilter; } public void Add(MessageEmote emote) { if (!_emoteList.TryGetValue(emote.Text, out var _)) { _emoteList.Add(emote.Text, emote); } if (CurrentPattern == null) { CurrentPattern = $"(\\b{emote.EscapedText}\\b)"; } else { CurrentPattern = CurrentPattern + "|" + $"(\\b{emote.EscapedText}\\b)"; } } public void Merge(IEnumerable<MessageEmote> emotes) { IEnumerator<MessageEmote> enumerator = emotes.GetEnumerator(); while (enumerator.MoveNext()) { Add(enumerator.Current); } enumerator.Dispose(); } public void Remove(MessageEmote emote) { if (_emoteList.ContainsKey(emote.Text)) { _emoteList.Remove(emote.Text); string text = "(^\\(\\\\b" + emote.EscapedText + "\\\\b\\)\\|?)"; string text2 = "(\\|\\(\\\\b" + emote.EscapedText + "\\\\b\\))"; string text3 = Regex.Replace(CurrentPattern, text + "|" + text2, ""); CurrentPattern = (text3.Equals("") ? null : text3); } } public void RemoveAll() { _emoteList.Clear(); CurrentPattern = null; } public string ReplaceEmotes(string originalMessage, EmoteFilterDelegate del = null) { if (CurrentRegex == null) { return originalMessage; } if (del != null && del != CurrentEmoteFilter) { CurrentEmoteFilter = del; } string result = CurrentRegex.Replace(originalMessage, GetReplacementString); CurrentEmoteFilter = _preferredFilter; return result; } public static bool AllInclusiveEmoteFilter(MessageEmote emote) { return true; } public static bool TwitchOnlyEmoteFilter(MessageEmote emote) { return emote.Source == MessageEmote.EmoteSource.Twitch; } private string GetReplacementString(Match m) { if (!_emoteList.ContainsKey(m.Value)) { return m.Value; } MessageEmote messageEmote = _emoteList[m.Value]; if (!CurrentEmoteFilter(messageEmote)) { return m.Value; } return messageEmote.ReplacementString; } } public class OutboundChatMessage { public string Channel { get; set; } public string Message { get; set; } public string Username { get; set; } public string ReplyToId { get; set; } public override string ToString() { string text = Username.ToLower(); string text2 = Channel.ToLower(); if (ReplyToId == null) { return ":" + text + "!" + text + "@" + text + ".tmi.twitch.tv PRIVMSG #" + text2 + " :" + Message; } return "@reply-parent-msg-id=" + ReplyToId + " PRIVMSG #" + text2 + " :" + Message; } } public class OutboundWhisperMessage { public string Username { get; set; } public string Receiver { get; set; } public string Message { get; set; } public override string ToString() { return ":" + Username + "~" + Username + "@" + Username + ".tmi.twitch.tv PRIVMSG #jtv :/w " + Receiver + " " + Message; } } public class OutgoingMessage { public string Channel { get; set; } public string Message { get; set; } public int Nonce { get; set; } public string Sender { get; set; } public MessageState State { get; set; } } public enum MessageState : byte { Normal, Queued, Failed } public class PrimePaidSubscriber : SubscriberBase { public PrimePaidSubscriber(IrcMessage ircMessage) : base(ircMessage) { } public PrimePaidSubscriber(List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string colorHex, Color color, string displayName, string emoteSet, string id, string login, string systemMessage, string msgId, string msgParamCumulativeMonths, string msgParamStreakMonths, bool msgParamShouldShareStreak, string systemMessageParsed, string resubMessage, SubscriptionPlan subscriptionPlan, string subscriptionPlanName, string roomId, string userId, bool isModerator, bool isTurbo, bool isSubscriber, bool isPartner, string tmiSentTs, UserType userType, string rawIrc, string channel, int months = 0) : base(badges, badgeInfo, colorHex, color, displayName, emoteSet, id, login, systemMessage, msgId, msgParamCumulativeMonths, msgParamStreakMonths, msgParamShouldShareStreak, systemMessageParsed, resubMessage, subscriptionPlan, subscriptionPlanName, roomId, userId, isModerator, isTurbo, isSubscriber, isPartner, tmiSentTs, userType, rawIrc, channel, months) { }//IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) } public class RaidNotification { public List<KeyValuePair<string, string>> Badges { get; } public List<KeyValuePair<string, string>> BadgeInfo { get; } public string Color { get; } public string DisplayName { get; } public string Emotes { get; } public string Id { get; } public string Login { get; } public bool Moderator { get; } public string MsgId { get; } public string MsgParamDisplayName { get; } public string MsgParamLogin { get; } public string MsgParamViewerCount { get; } public string RoomId { get; } public bool Subscriber { get; } public string SystemMsg { get; } public string SystemMsgParsed { get; } public string TmiSentTs { get; } public bool Turbo { get; } public string UserId { get; } public UserType UserType { get; } public RaidNotification(IrcMessage ircMessage) { //IL_0411: Unknown result type (might be due to invalid IL or missing references) //IL_041a: Unknown result type (might be due to invalid IL or missing references) //IL_0423: Unknown result type (might be due to invalid IL or missing references) //IL_042c: Unknown result type (might be due to invalid IL or missing references) //IL_0435: Unknown result type (might be due to invalid IL or missing references) foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "badges": Badges = Helpers.ParseBadges(text); break; case "badge-info": BadgeInfo = Helpers.ParseBadges(text); break; case "color": Color = text; break; case "display-name": DisplayName = text; break; case "emotes": Emotes = text; break; case "login": Login = text; break; case "mod": Moderator = Helpers.ConvertToBool(text); break; case "msg-id": MsgId = text; break; case "msg-param-displayName": MsgParamDisplayName = text; break; case "msg-param-login": MsgParamLogin = text; break; case "msg-param-viewerCount": MsgParamViewerCount = text; break; case "room-id": RoomId = text; break; case "subscriber": Subscriber = Helpers.ConvertToBool(text); break; case "system-msg": SystemMsg = text; SystemMsgParsed = text.Replace("\\s", " ").Replace("\\n", ""); break; case "tmi-sent-ts": TmiSentTs = text; break; case "turbo": Turbo = Helpers.ConvertToBool(text); break; case "user-id": UserId = text; break; case "user-type": switch (text) { case "mod": UserType = (UserType)1; break; case "global_mod": UserType = (UserType)2; break; case "admin": UserType = (UserType)4; break; case "staff": UserType = (UserType)5; break; default: UserType = (UserType)0; break; } break; } } } public RaidNotification(List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string color, string displayName, string emotes, string id, string login, bool moderator, string msgId, string msgParamDisplayName, string msgParamLogin, string msgParamViewerCount, string roomId, bool subscriber, string systemMsg, string systemMsgParsed, string tmiSentTs, bool turbo, UserType userType, string userId) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) Badges = badges; BadgeInfo = badgeInfo; Color = color; DisplayName = displayName; Emotes = emotes; Id = id; Login = login; Moderator = moderator; MsgId = msgId; MsgParamDisplayName = msgParamDisplayName; MsgParamLogin = msgParamLogin; MsgParamViewerCount = msgParamViewerCount; RoomId = roomId; Subscriber = subscriber; SystemMsg = systemMsg; SystemMsgParsed = systemMsgParsed; TmiSentTs = tmiSentTs; Turbo = turbo; UserType = userType; UserId = userId; } } public class ReSubscriber : SubscriberBase { public int Months => monthsInternal; public ReSubscriber(IrcMessage ircMessage) : base(ircMessage) { } public ReSubscriber(List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string colorHex, Color color, string displayName, string emoteSet, string id, string login, string systemMessage, string msgId, string msgParamCumulativeMonths, string msgParamStreakMonths, bool msgParamShouldShareStreak, string systemMessageParsed, string resubMessage, SubscriptionPlan subscriptionPlan, string subscriptionPlanName, string roomId, string userId, bool isModerator, bool isTurbo, bool isSubscriber, bool isPartner, string tmiSentTs, UserType userType, string rawIrc, string channel, int months = 0) : base(badges, badgeInfo, colorHex, color, displayName, emoteSet, id, login, systemMessage, msgId, msgParamCumulativeMonths, msgParamStreakMonths, msgParamShouldShareStreak, systemMessageParsed, resubMessage, subscriptionPlan, subscriptionPlanName, roomId, userId, isModerator, isTurbo, isSubscriber, isPartner, tmiSentTs, userType, rawIrc, channel, months) { }//IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) } public class RitualNewChatter { public List<KeyValuePair<string, string>> Badges { get; } public List<KeyValuePair<string, string>> BadgeInfo { get; } public string Color { get; } public string DisplayName { get; } public string Emotes { get; } public string Id { get; } public bool IsModerator { get; } public bool IsSubscriber { get; } public bool IsTurbo { get; } public string Login { get; } public string Message { get; } public string MsgId { get; } public string MsgParamRitualName { get; } public string RoomId { get; } public string SystemMsgParsed { get; } public string SystemMsg { get; } public string TmiSentTs { get; } public string UserId { get; } public UserType UserType { get; } public RitualNewChatter(IrcMessage ircMessage) { //IL_03f1: Unknown result type (might be due to invalid IL or missing references) //IL_03fa: Unknown result type (might be due to invalid IL or missing references) //IL_0403: Unknown result type (might be due to invalid IL or missing references) //IL_040c: Unknown result type (might be due to invalid IL or missing references) //IL_0415: Unknown result type (might be due to invalid IL or missing references) Message = ircMessage.Message; foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "badges": Badges = Helpers.ParseBadges(text); break; case "badge-info": BadgeInfo = Helpers.ParseBadges(text); break; case "color": Color = text; break; case "display-name": DisplayName = text; break; case "emotes": Emotes = text; break; case "id": Id = text; break; case "login": Login = text; break; case "mod": IsModerator = Helpers.ConvertToBool(text); break; case "msg-id": MsgId = text; break; case "msg-param-ritual-name": MsgParamRitualName = text; break; case "room-id": RoomId = text; break; case "subscriber": IsSubscriber = Helpers.ConvertToBool(text); break; case "system-msg": SystemMsg = text; SystemMsgParsed = text.Replace("\\s", " ").Replace("\\n", ""); break; case "tmi-sent-ts": TmiSentTs = text; break; case "turbo": IsTurbo = Helpers.ConvertToBool(text); break; case "user-id": UserId = text; break; case "user-type": switch (text) { case "mod": UserType = (UserType)1; break; case "global_mod": UserType = (UserType)2; break; case "admin": UserType = (UserType)4; break; case "staff": UserType = (UserType)5; break; default: UserType = (UserType)0; break; } break; } } } } public class SentMessage { public List<KeyValuePair<string, string>> Badges { get; } public string Channel { get; } public string ColorHex { get; } public string DisplayName { get; } public string EmoteSet { get; } public bool IsModerator { get; } public bool IsSubscriber { get; } public string Message { get; } public UserType UserType { get; } public SentMessage(UserState state, string message) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) Badges = state.Badges; Channel = state.Channel; ColorHex = state.ColorHex; DisplayName = state.DisplayName; EmoteSet = state.EmoteSet; IsModerator = state.IsModerator; IsSubscriber = state.IsSubscriber; UserType = state.UserType; Message = message; } public SentMessage(List<KeyValuePair<string, string>> badges, string channel, string colorHex, string displayName, string emoteSet, bool isModerator, bool isSubscriber, UserType userType, string message) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) Badges = badges; Channel = channel; ColorHex = colorHex; DisplayName = displayName; EmoteSet = emoteSet; IsModerator = isModerator; IsSubscriber = isSubscriber; UserType = userType; Message = message; } } public class Subscriber : SubscriberBase { public Subscriber(IrcMessage ircMessage) : base(ircMessage) { } public Subscriber(List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string colorHex, Color color, string displayName, string emoteSet, string id, string login, string systemMessage, string msgId, string msgParamCumulativeMonths, string msgParamStreakMonths, bool msgParamShouldShareStreak, string systemMessageParsed, string resubMessage, SubscriptionPlan subscriptionPlan, string subscriptionPlanName, string roomId, string userId, bool isModerator, bool isTurbo, bool isSubscriber, bool isPartner, string tmiSentTs, UserType userType, string rawIrc, string channel) : base(badges, badgeInfo, colorHex, color, displayName, emoteSet, id, login, systemMessage, msgId, msgParamCumulativeMonths, msgParamStreakMonths, msgParamShouldShareStreak, systemMessageParsed, resubMessage, subscriptionPlan, subscriptionPlanName, roomId, userId, isModerator, isTurbo, isSubscriber, isPartner, tmiSentTs, userType, rawIrc, channel, 0) { }//IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) } public class SubscriberBase { protected readonly int monthsInternal; public List<KeyValuePair<string, string>> Badges { get; } public List<KeyValuePair<string, string>> BadgeInfo { get; } public string ColorHex { get; } public Color Color { get; } public string DisplayName { get; } public string EmoteSet { get; } public string Id { get; } public bool IsModerator { get; } public bool IsPartner { get; } public bool IsSubscriber { get; } public bool IsTurbo { get; } public string Login { get; } public string MsgId { get; } public string MsgParamCumulativeMonths { get; } public bool MsgParamShouldShareStreak { get; } public string MsgParamStreakMonths { get; } public string RawIrc { get; } public string ResubMessage { get; } public string RoomId { get; } public SubscriptionPlan SubscriptionPlan { get; } public string SubscriptionPlanName { get; } public string SystemMessage { get; } public string SystemMessageParsed { get; } public string TmiSentTs { get; } public string UserId { get; } public UserType UserType { get; } public string Channel { get; } protected SubscriberBase(IrcMessage ircMessage) { //IL_04a2: Unknown result type (might be due to invalid IL or missing references) //IL_04ae: Unknown result type (might be due to invalid IL or missing references) //IL_058d: Unknown result type (might be due to invalid IL or missing references) //IL_04ba: Unknown result type (might be due to invalid IL or missing references) //IL_0596: Unknown result type (might be due to invalid IL or missing references) //IL_04c6: Unknown result type (might be due to invalid IL or missing references) //IL_059f: Unknown result type (might be due to invalid IL or missing references) //IL_05a8: Unknown result type (might be due to invalid IL or missing references) //IL_05b1: Unknown result type (might be due to invalid IL or missing references) RawIrc = ircMessage.ToString(); ResubMessage = ircMessage.Message; foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "badges": Badges = Helpers.ParseBadges(text); foreach (KeyValuePair<string, string> badge in Badges) { if (badge.Key == "partner") { IsPartner = true; } } break; case "badge-info": BadgeInfo = Helpers.ParseBadges(text); break; case "color": ColorHex = text; if (!string.IsNullOrEmpty(ColorHex)) { Color = TwitchLib.Client.Models.Extensions.NetCore.ColorTranslator.FromHtml(ColorHex); } break; case "display-name": DisplayName = text; break; case "emotes": EmoteSet = text; break; case "id": Id = text; break; case "login": Login = text; break; case "mod": IsModerator = ConvertToBool(text); break; case "msg-id": MsgId = text; break; case "msg-param-cumulative-months": MsgParamCumulativeMonths = text; break; case "msg-param-streak-months": MsgParamStreakMonths = text; break; case "msg-param-should-share-streak": MsgParamShouldShareStreak = Helpers.ConvertToBool(text); break; case "msg-param-sub-plan": switch (text.ToLower()) { case "prime": SubscriptionPlan = (SubscriptionPlan)1; break; case "1000": SubscriptionPlan = (SubscriptionPlan)2; break; case "2000": SubscriptionPlan = (SubscriptionPlan)3; break; case "3000": SubscriptionPlan = (SubscriptionPlan)4; break; default: throw new ArgumentOutOfRangeException("ToLower"); } break; case "msg-param-sub-plan-name": SubscriptionPlanName = text.Replace("\\s", " "); break; case "room-id": RoomId = text; break; case "subscriber": IsSubscriber = ConvertToBool(text); break; case "system-msg": SystemMessage = text; SystemMessageParsed = text.Replace("\\s", " "); break; case "tmi-sent-ts": TmiSentTs = text; break; case "turbo": IsTurbo = ConvertToBool(text); break; case "user-id": UserId = text; break; case "user-type": switch (text) { case "mod": UserType = (UserType)1; break; case "global_mod": UserType = (UserType)2; break; case "admin": UserType = (UserType)4; break; case "staff": UserType = (UserType)5; break; default: UserType = (UserType)0; break; } break; } } } internal SubscriberBase(List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string colorHex, Color color, string displayName, string emoteSet, string id, string login, string systemMessage, string msgId, string msgParamCumulativeMonths, string msgParamStreakMonths, bool msgParamShouldShareStreak, string systemMessageParsed, string resubMessage, SubscriptionPlan subscriptionPlan, string subscriptionPlanName, string roomId, string userId, bool isModerator, bool isTurbo, bool isSubscriber, bool isPartner, string tmiSentTs, UserType userType, string rawIrc, string channel, int months) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) Badges = badges; BadgeInfo = badgeInfo; ColorHex = colorHex; Color = color; DisplayName = displayName; EmoteSet = emoteSet; Id = id; Login = login; MsgId = msgId; MsgParamCumulativeMonths = msgParamCumulativeMonths; MsgParamStreakMonths = msgParamStreakMonths; MsgParamShouldShareStreak = msgParamShouldShareStreak; SystemMessage = systemMessage; SystemMessageParsed = systemMessageParsed; ResubMessage = resubMessage; SubscriptionPlan = subscriptionPlan; SubscriptionPlanName = subscriptionPlanName; RoomId = roomId; UserId = UserId; IsModerator = isModerator; IsTurbo = isTurbo; IsSubscriber = isSubscriber; IsPartner = isPartner; TmiSentTs = tmiSentTs; UserType = userType; RawIrc = rawIrc; monthsInternal = months; UserId = userId; Channel = channel; } private static bool ConvertToBool(string data) { return data == "1"; } public override string ToString() { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) return $"Badges: {Badges.Count}, color hex: {ColorHex}, display name: {DisplayName}, emote set: {EmoteSet}, login: {Login}, system message: {SystemMessage}, msgId: {MsgId}, msgParamCumulativeMonths: {MsgParamCumulativeMonths}" + $"msgParamStreakMonths: {MsgParamStreakMonths}, msgParamShouldShareStreak: {MsgParamShouldShareStreak}, resub message: {ResubMessage}, months: {monthsInternal}, room id: {RoomId}, user id: {UserId}, mod: {IsModerator}, turbo: {IsTurbo}, sub: {IsSubscriber}, user type: {UserType}, raw irc: {RawIrc}"; } } public abstract class TwitchLibMessage { public List<KeyValuePair<string, string>> Badges { get; protected set; } public string BotUsername { get; protected set; } public Color Color { get; protected set; } public string ColorHex { get; protected set; } public string DisplayName { get; protected set; } public EmoteSet EmoteSet { get; protected set; } public bool IsTurbo { get; protected set; } public string UserId { get; protected set; } public string Username { get; protected set; } public UserType UserType { get; protected set; } public string RawIrcMessage { get; protected set; } } public class UserBan { public string BanReason; public string Channel; public string Username; public string RoomId; public string TargetUserId; public UserBan(IrcMessage ircMessage) { Channel = ircMessage.Channel; Username = ircMessage.Message; if (ircMessage.Tags.TryGetValue("ban-reason", out var value)) { BanReason = value; } if (ircMessage.Tags.TryGetValue("room-id", out var value2)) { RoomId = value2; } if (ircMessage.Tags.TryGetValue("target-user-id", out var value3)) { TargetUserId = value3; } } public UserBan(string channel, string username, string banReason, string roomId, string targetUserId) { Channel = channel; Username = username; BanReason = banReason; RoomId = roomId; TargetUserId = targetUserId; } } public class UserState { public List<KeyValuePair<string, string>> Badges { get; } = new List<KeyValuePair<string, string>>(); public List<KeyValuePair<string, string>> BadgeInfo { get; } = new List<KeyValuePair<string, string>>(); public string Channel { get; } public string ColorHex { get; } public string DisplayName { get; } public string EmoteSet { get; } public string Id { get; } public bool IsModerator { get; } public bool IsSubscriber { get; } public UserType UserType { get; } public UserState(IrcMessage ircMessage) { //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) Channel = ircMessage.Channel; foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "badges": Badges = Helpers.ParseBadges(text); break; case "badge-info": BadgeInfo = Helpers.ParseBadges(text); break; case "color": ColorHex = text; break; case "display-name": DisplayName = text; break; case "emote-sets": EmoteSet = text; break; case "id": Id = text; break; case "mod": IsModerator = Helpers.ConvertToBool(text); break; case "subscriber": IsSubscriber = Helpers.ConvertToBool(text); break; case "user-type": switch (text) { case "mod": UserType = (UserType)1; break; case "global_mod": UserType = (UserType)2; break; case "admin": UserType = (UserType)4; break; case "staff": UserType = (UserType)5; break; default: UserType = (UserType)0; break; } break; default: Console.WriteLine("Unaccounted for [UserState]: " + key); break; } } if (string.Equals(ircMessage.User, Channel, StringComparison.InvariantCultureIgnoreCase)) { UserType = (UserType)3; } } public UserState(List<KeyValuePair<string, string>> badges, List<KeyValuePair<string, string>> badgeInfo, string colorHex, string displayName, string emoteSet, string channel, string id, bool isSubscriber, bool isModerator, UserType userType) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) Badges = badges; BadgeInfo = badgeInfo; ColorHex = colorHex; DisplayName = displayName; EmoteSet = emoteSet; Channel = channel; Id = id; IsSubscriber = isSubscriber; IsModerator = isModerator; UserType = userType; } } public class UserTimeout { public string Channel; public int TimeoutDuration; public string TimeoutReason; public string Username; public string TargetUserId; public UserTimeout(IrcMessage ircMessage) { Channel = ircMessage.Channel; Username = ircMessage.Message; foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "ban-duration": TimeoutDuration = int.Parse(text); break; case "ban-reason": TimeoutReason = text; break; case "target-user-id": TargetUserId = text; break; } } } public UserTimeout(string channel, string username, string targetuserId, int timeoutDuration, string timeoutReason) { Channel = channel; Username = username; TargetUserId = targetuserId; TimeoutDuration = timeoutDuration; TimeoutReason = timeoutReason; } } public class WhisperCommand { public List<string> ArgumentsAsList { get; } public string ArgumentsAsString { get; } public char CommandIdentifier { get; } public string CommandText { get; } public WhisperMessage WhisperMessage { get; } public WhisperCommand(WhisperMessage whisperMessage) { WhisperCommand whisperCommand = this; WhisperMessage = whisperMessage; string[] array = whisperMessage.Message.Split(new char[1] { ' ' }); CommandText = ((array != null) ? array[0].Substring(1, whisperMessage.Message.Split(new char[1] { ' ' })[0].Length - 1) : null) ?? whisperMessage.Message.Substring(1, whisperMessage.Message.Length - 1); string message = whisperMessage.Message; string[] array2 = whisperMessage.Message.Split(new char[1] { ' ' }); ArgumentsAsString = message.Replace(((array2 != null) ? array2[0] : null) + " ", ""); ArgumentsAsList = whisperMessage.Message.Split(new char[1] { ' ' })?.Where((string arg) => arg != whisperMessage.Message[0] + whisperCommand.CommandText).ToList() ?? new List<string>(); CommandIdentifier = whisperMessage.Message[0]; } public WhisperCommand(WhisperMessage whisperMessage, string commandText, string argumentsAsString, List<string> argumentsAsList, char commandIdentifier) { WhisperMessage = whisperMessage; CommandText = commandText; ArgumentsAsString = argumentsAsString; ArgumentsAsList = argumentsAsList; CommandIdentifier = commandIdentifier; } } public class WhisperMessage : TwitchLibMessage { public string MessageId { get; } public string ThreadId { get; } public string Message { get; } public WhisperMessage(List<KeyValuePair<string, string>> badges, string colorHex, Color color, string username, string displayName, EmoteSet emoteSet, string threadId, string messageId, string userId, bool isTurbo, string botUsername, string message, UserType userType) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) base.Badges = badges; base.ColorHex = colorHex; base.Color = color; base.Username = username; base.DisplayName = displayName; base.EmoteSet = emoteSet; ThreadId = threadId; MessageId = messageId; base.UserId = userId; base.IsTurbo = isTurbo; base.BotUsername = botUsername; Message = message; base.UserType = userType; } public WhisperMessage(IrcMessage ircMessage, string botUsername) { base.Username = ircMessage.User; base.BotUsername = botUsername; base.RawIrcMessage = ircMessage.ToString(); Message = ircMessage.Message; foreach (string key in ircMessage.Tags.Keys) { string text = ircMessage.Tags[key]; switch (key) { case "badges": { base.Badges = new List<KeyValuePair<string, string>>(); if (!Enumerable.Contains(text, '/')) { break; } if (!text.Contains(",")) { base.Badges.Add(new KeyValuePair<string, string>(text.Split(new char[1] { '/' })[0], text.Split(new char[1] { '/' })[1])); break; } string[] array = text.Split(new char[1] { ',' }); foreach (string text2 in array) { base.Badges.Add(new KeyValuePair<string, string>(text2.Split(new char[1] { '/' })[0], text2.Split(new char[1] { '/' })[1])); } break; } case "color": base.ColorHex = text; if (!string.IsNullOrEmpty(base.ColorHex)) { base.Color = TwitchLib.Client.Models.Extensions.NetCore.ColorTranslator.FromHtml(base.ColorHex); } break; case "display-name": base.DisplayName = text; break; case "emotes": base.EmoteSet = new EmoteSet(text, Message); break; case "message-id": MessageId = text; break; case "thread-id": ThreadId = text; break; case "turbo": base.IsTurbo = Helpers.ConvertToBool(text); break; case "user-id": base.UserId = text; break; case "user-type": switch (text) { case "global_mod": base.UserType = (UserType)2; break; case "admin": base.UserType = (UserType)4; break; case "staff": base.UserType = (UserType)5; break; default: base.UserType = (UserType)0; break; } break; } } if (base.EmoteSet == null) { base.EmoteSet = new EmoteSet((string)null, Message); } } } } namespace TwitchLib.Client.Models.Internal { public class IrcMessage { private readonly string[] _parameters; public readonly string User; public readonly string Hostmask; public readonly IrcCommand Command; public readonly Dictionary<string, string> Tags; public string Channel { get { if (!Params.StartsWith("#")) { return Params; } return Params.Remove(0, 1); } } public string Params { get { if (_parameters == null || _parameters.Length == 0) { return ""; } return _parameters[0]; } } public string Message => Trailing; public string Trailing { get { if (_parameters == null || _parameters.Length <= 1) { return ""; } return _parameters[_parameters.Length - 1]; } } public IrcMessage(string user) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) _parameters = null; User = user; Hostmask = null; Command = (IrcCommand)0; Tags = null; } public IrcMessage(IrcCommand command, string[] parameters, string hostmask, Dictionary<string, string> tags = null) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Invalid comparison between Unknown and I4 int num = hostmask.IndexOf('!'); User = ((num != -1) ? hostmask.Substring(0, num) : hostmask); Hostmask = hostmask; _parameters = parameters; Command = command; Tags = tags; if ((int)command == 18 && Params.Length > 0 && Params.Contains("#")) { _parameters[0] = "#" + _parameters[0].Split(new char[1] { '#' })[1]; } } public new string ToString() { StringBuilder stringBuilder = new StringBuilder(32); if (Tags != null) { string[] array = new string[Tags.Count]; int num = 0; foreach (KeyValuePair<string, string> tag in Tags) { array[num] = tag.Key + "=" + tag.Value; num++; } if (array.Length != 0) { stringBuilder.Append("@").Append(string.Join(";", array)).Append(" "); } } if (!string.IsNullOrEmpty(Hostmask)) { stringBuilder.Append(":").Append(Hostmask).Append(" "); } stringBuilder.Append(((object)(IrcCommand)(ref Command)).ToString().ToUpper().Replace("RPL_", "")); if (_parameters.Length == 0) { return stringBuilder.ToString(); } if (_parameters[0] != null && _parameters[0].Length > 0) { stringBuilder.Append(" ").Append(_parameters[0]); } if (_parameters.Length > 1 && _parameters[1] != null && _parameters[1].Length > 0) { stringBuilder.Append(" :").Append(_parameters[1]); } return stringBuilder.ToString(); } } public static class MsgIds { public const string AlreadyBanned = "already_banned"; public const string AlreadyEmotesOff = "already_emotes_off"; public const string AlreadyEmotesOn = "already_emotes_on"; public const string AlreadyR9KOff = "already_r9k_off"; public const string AlreadyR9KOn = "already_r9k_on"; public const string AlreadySubsOff = "already_subs_off"; public const string AlreadySubsOn = "already_subs_on"; public const string Announcement = "announcement"; public const string BadUnbanNoBan = "bad_unban_no_ban"; public const string BanSuccess = "ban_success"; public const string ColorChanged = "color_changed"; public const string EmoteOnlyOff = "emote_only_off"; public const string EmoteOnlyOn = "emote_only_on"; public const string HighlightedMessage = "highlighted-message"; public const string ModeratorsReceived = "room_mods"; public const string NoMods = "no_mods"; public const string NoVIPs = "no_vips"; public const string MsgBannedEmailAlias = "msg_banned_email_alias"; public const string MsgChannelSuspended = "msg_channel_suspended"; public const string MsgRequiresVerifiedPhoneNumber = "msg_requires_verified_phone_number"; public const string MsgVerifiedEmail = "msg_verified_email"; public const string MsgRateLimit = "msg_ratelimit"; public const string MsgDuplicate = "msg_duplicate"; public const string MsgR9k = "msg_r9k"; public const string MsgFollowersOnly = "msg_followersonly"; public const string MsgSubsOnly = "msg_subsonly"; public const string MsgEmoteOnly = "msg_emoteonly"; public const string MsgSuspended = "msg_suspended"; public const string MsgBanned = "msg_banned"; public const string MsgSlowMode = "msg_slowmode"; public const string NoPermission = "no_permission"; public const string PrimePaidUprade = "primepaidupgrade"; public const string Raid = "raid"; public const string RaidErrorSelf = "raid_error_self"; public const string RaidNoticeMature = "raid_notice_mature"; public const string ReSubscription = "resub"; public const string R9KOff = "r9k_off"; public const string R9KOn = "r9k_on"; public const string SubGift = "subgift"; public const string CommunitySubscription = "submysterygift"; public const string ContinuedGiftedSubscription = "giftpaidupgrade"; public const string Subscription = "sub"; public const string SubsOff = "subs_off"; public const string SubsOn = "subs_on"; public const string TimeoutSuccess = "timeout_success"; public const string UnbanSuccess = "unban_success"; public const string UnrecognizedCmd = "unrecognized_cmd"; public const string UserIntro = "user-intro"; public const string VIPsSuccess = "vips_success"; public const string SkipSubsModeMessage = "skip-subs-mode-message"; } public static class Tags { public const string Badges = "badges"; public const string BadgeInfo = "badge-info"; public const string BanDuration = "ban-duration"; public const string BanReason = "ban-reason"; public const string BroadcasterLang = "broadcaster-lang"; public const string Bits = "bits"; public const string Color = "color"; public const string CustomRewardId = "custom-reward-id"; public const string DisplayName = "display-name"; public const string Emotes = "emotes"; public const string EmoteOnly = "emote-only"; public const string EmotesSets = "emote-sets"; public const string FirstMessage = "first-msg"; public const string Flags = "flags"; public const string FollowersOnly = "followers-only"; public const string Id = "id"; public const string Login = "login"; public const string Mercury = "mercury"; public const string MessageId = "message-id"; public const string Mod = "mod"; public const string MsgId = "msg-id"; public const string MsgParamColor = "msg-param-color"; public const string MsgParamDisplayname = "msg-param-displayName"; public const string MsgParamLogin = "msg-param-login"; public const string MsgParamCumulativeMonths = "msg-param-cumulative-months"; public const string MsgParamMonths = "msg-param-months"; public const string MsgParamPromoGiftTotal = "msg-param-promo-gift-total"; public const string MsgParamPromoName = "msg-param-promo-name"; public const string MsgParamShouldShareStreak = "msg-param-should-share-streak"; public const string MsgParamStreakMonths = "msg-param-streak-months"; public const string MsgParamSubPlan = "msg-param-sub-plan"; public const string MsgParamSubPlanName = "msg-param-sub-plan-name"; public const string MsgParamViewerCount = "msg-param-viewerCount"; public const string MsgParamRecipientDisplayname = "msg-param-recipient-display-name"; public const string MsgParamRecipientId = "msg-param-recipient-id"; public const string MsgParamRecipientUsername = "msg-param-recipient-user-name"; public const string MsgParamRitualName = "msg-param-ritual-name"; public const string MsgParamMassGiftCount = "msg-param-mass-gift-count"; public const string MsgParamSenderCount = "msg-param-sender-count"; public const string MsgParamSenderLogin = "msg-param-sender-login"; public const string MsgParamSenderName = "msg-param-sender-name"; public const string MsgParamThreshold = "msg-param-threshold"; public const string Noisy = "noisy"; public const string ReplyParentDisplayName = "reply-parent-display-name"; public const string ReplyParentMsgBody = "reply-parent-msg-body"; public const string ReplyParentMsgId = "reply-parent-msg-id"; public const string ReplyParentUserId = "reply-parent-user-id"; public const string ReplyParentUserLogin = "reply-parent-user-login"; public const string Rituals = "rituals"; public const string RoomId = "room-id"; public const string R9K = "r9k"; public const string Slow = "slow"; public const string Subscriber = "subscriber"; public const string SubsOnly = "subs-only"; public const string SystemMsg = "system-msg"; public const string ThreadId = "thread-id"; public const string TmiSentTs = "tmi-sent-ts"; public const string Turbo = "turbo"; public const string UserId = "user-id"; public const string UserType = "user-type"; public const string MsgParamMultiMonthGiftDuration = "msg-param-gift-months"; public const string TargetUserId = "target-user-id"; } } namespace TwitchLib.Client.Models.Extractors { public class EmoteExtractor { public IEnumerable<Emote> Extract(string rawEmoteSetString, string message) { if (string.IsNullOrEmpty(rawEmoteSetString) || string.IsNullOrEmpty(message)) { yield break; } string emoteId2; if (rawEmoteSetString.Contains("/")) { string[] array = rawEmoteSetString.Split(new char[1] { '/' }); foreach (string text in array) { emoteId2 = text.Split(new char[1] { ':' })[0]; if (text.Contains(",")) { string[] array2 = text.Replace(emoteId2 + ":", "").Split(new char[1] { ',' }); foreach (string emoteData in array2) { yield return GetEmote(emoteData, emoteId2, message); } } else { yield return GetEmote(text, emoteId2, message, single: true); } } yield break; } emoteId2 = rawEmoteSetString.Split(new char[1] { ':' })[0]; if (rawEmoteSetString.Contains(",")) { string[] array = rawEmoteSetString.Replace(emoteId2 + ":", "").Split(new char[1] { ',' }); foreach (string emoteData2 in array) { yield return GetEmote(emoteData2, emoteId2, message); } } else { yield return GetEmote(rawEmoteSetString, emoteId2, message, single: true); } } private Emote GetEmote(string emoteData, string emoteId, string message, bool single = false) { int num = -1; int num2 = -1; if (single) { num = int.Parse(emoteData.Split(new char[1] { ':' })[1].Split(new char[1] { '-' })[0]); num2 = int.Parse(emoteData.Split(new char[1] { ':' })[1].Split(new char[1] { '-' })[1]); } else { num = int.Parse(emoteData.Split(new char[1] { '-' })[0]); num2 = int.Parse(emoteData.Split(new char[1] { '-' })[1]); } string name = message.Substring(num, num2 - num + 1); return EmoteBuilder.Create().WithId(emoteId).WithName(name) .WithStartIndex(num) .WithEndIndex(num2) .Build(); } } public interface IExtractor<TResult> { TResult Extract(IrcMessage ircMessage); } } namespace TwitchLib.Client.Models.Extensions.NetCore { public static class ColorTranslator { public static Color FromHtml(string hexColor) { hexColor += 0; return Color.FromArgb(int.Parse(hexColor.Replace("#", ""), NumberStyles.HexNumber)); } } } namespace TwitchLib.Client.Models.Common { public static class Helpers { public static List<string> ParseQuotesAndNonQuotes(string message) { List<string> list = new List<string>(); if (message == "") { return new List<string>(); } bool flag = message[0] != '"'; string[] array = message.Split(new char[1] { '"' }); foreach (string text in array) { if (string.IsNullOrEmpty(text)) { continue; } if (!flag) { list.Add(text); flag = true; } else { if (!text.Contains(" ")) { continue; } string[] array2 = text.Split(new char[1] { ' ' }); foreach (string text2 in array2) { if (!string.IsNullOrWhiteSpace(text2)) { list.Add(text2); flag = false; } } } } return list; } public static List<KeyValuePair<string, string>> ParseBadges(string badgesStr) { List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(); if (Enumerable.Contains(badgesStr, '/')) { if (!badgesStr.Contains(",")) { list.Add(new KeyValuePair<string, string>(badgesStr.Split(new char[1] { '/' })[0], badgesStr.Split(new char[1] { '/' })[1])); } else { string[] array = badgesStr.Split(new char[1] { ',' }); foreach (string text in array) { list.Add(new KeyValuePair<string, string>(text.Split(new char[1] { '/' })[0], text.Split(new char[1] { '/' })[1])); } } } return list; } public static string ParseToken(string token, string message) { string result = string.Empty; for (int num = message.IndexOf(token, StringComparison.InvariantCultureIgnoreCase); num > -1; num = message.IndexOf(token, num + token.Length, StringComparison.InvariantCultureIgnoreCase)) { result = new string(message.Substring(num).TakeWhile((char x) => x != ';' && x != ' ').ToArray()).Split(new char[1] { '=' }).LastOrDefault(); } return result; } public static bool ConvertToBool(string data) { return data == "1"; } } } namespace TwitchLib.Client.Models.Builders { public sealed class ChannelStateBuilder : IBuilder<ChannelState>, IFromIrcMessageBuilder<ChannelState> { private string _broadcasterLanguage; private string _channel; private bool _emoteOnly; private TimeSpan _followersOnly; private bool _mercury; private bool _r9K; private bool _rituals; private string _roomId; private int _slowMode; private bool _subOnly; private ChannelStateBuilder() { } public ChannelStateBuilder WithBroadcasterLanguage(string broadcasterLanguage) { _broadcasterLanguage = broadcasterLanguage; return this; } public ChannelStateBuilder WithChannel(string channel) { _channel = channel; return this; } public ChannelStateBuilder WithEmoteOnly(bool emoteOnly) { _emoteOnly = emoteOnly; return this; } public ChannelStateBuilder WIthFollowersOnly(TimeSpan followersOnly) { _followersOnly = followersOnly; return this; } public ChannelStateBuilder WithMercury(bool mercury) { _mercury = mercury; return this; } public ChannelStateBuilder WithR9K(bool r9k) { _r9K = r9k; return this; } public ChannelStateBuilder WithRituals(bool rituals) { _rituals = rituals; return this; } public ChannelStateBuilder WithRoomId(string roomId) { _roomId = roomId; return this; } public ChannelStateBuilder WithSlowMode(int slowMode) { _slowMode = slowMode; return this; } public ChannelStateBuilder WithSubOnly(bool subOnly) { _subOnly = subOnly; return this; } public static ChannelStateBuilder Create() { return new ChannelStateBuilder(); } public ChannelState Build() { return new ChannelState(_r9K, _rituals, _subOnly, _slowMode, _emoteOnly, _broadcasterLanguage, _channel, _followersOnly, _mercury, _roomId); } public ChannelState BuildFromIrcMessage(FromIrcMessageBuilderDataObject fromIrcMessageBuilderDataObject) { return new ChannelState(fromIrcMessageBuilderDataObject.Message); } } public sealed class ChatCommandBuilder : IBuilder<ChatCommand> { private readonly List<string> _argumentsAsList = new List<string>(); private string _argumentsAsString; private ChatMessage _chatMessage; private char _commandIdentifier; private string _commandText; private ChatCommandBuilder() { } public ChatCommandBuilder WithArgumentsAsList(params string[] argumentsList) { _argumentsAsList.AddRange(argumentsList); return this; } public ChatCommandBuilder WithArgumentsAsString(string argumentsAsString) { _argumentsAsString = argumentsAsString; return this; } public ChatCommandBuilder WithChatMessage(ChatMessage chatMessage) { _chatMessage = chatMessage; return this; } public ChatCommandBuilder WithCommandIdentifier(char commandIdentifier) { _commandIdentifier = commandIdentifier; return this; } public ChatCommandBuilder WithCommandText(string commandText) { _commandText = commandText; return this; } public static ChatCommandBuilder Create() { return new ChatCommandBuilder(); } public ChatCommand Build() { return new ChatCommand(_chatMessage, _commandText, _argumentsAsString, _argumentsAsList, _commandIdentifier); } public ChatCommand BuildFromChatMessage(ChatMessage chatMessage) { return new ChatCommand(chatMessage); } } public sealed class ChatMessageBuilder : IBuilder<ChatMessage> { private TwitchLibMessage _twitchLibMessage; private readonly List<KeyValuePair<string, string>> BadgeInfo = new List<KeyValuePair<string, string>>(); private int _bits; private double _bitsInDollars; private string _channel; private CheerBadge _cheerBadge; private string _emoteReplacedMessage; private string _id; private bool _isBroadcaster; private bool _isMe; private bool _isModerator; private bool _isSubscriber; private bool _isVip; private bool _isStaff; private bool _isPartner; private string _message; private Noisy _noisy; private string _rawIrcMessage; private string _roomId; private int _subscribedMonthCount; private ChatMessageBuilder() { _twitchLibMessage = TwitchLibMessageBuilder.Create().Build(); } public ChatMessageBuilder WithTwitchLibMessage(TwitchLibMessage twitchLibMessage) { _twitchLibMessage = twitchLibMessage; return this; } public ChatMessageBuilder WithBadgeInfos(params KeyValuePair<string, string>[] badgeInfos) { BadgeInfo.AddRange(badgeInfos); return this; } public ChatMessageBuilder WithBits(int bits) { _bits = bits; return this; } public ChatMessageBuilder WithBitsInDollars(double bitsInDollars) { _bitsInDollars = bitsInDollars; return this; } public ChatMessageBuilder WithChannel(string channel) { _channel = channel; return this; } public ChatMessageBuilder WithCheerBadge(CheerBadge cheerBadge) { _cheerBadge = cheerBadge; return this; } public ChatMessageBuilder WithEmoteReplaceMessage(string emoteReplaceMessage) { _emoteReplacedMessage = emoteReplaceMessage; return this; } public ChatMessageBuilder WithId(string id) { _id = id; return this; } public ChatMessageBuilder WithIsBroadcaster(bool isBroadcaster) { _isBroadcaster = isBroadcaster; return this; } public ChatMessageBuilder WithIsMe(bool isMe) { _isMe = isMe; return this; } public ChatMessageBuilder WithIsModerator(bool isModerator) { _isModerator = isModerator; return this; } public ChatMessageBuilder WithIsSubscriber(bool isSubscriber) { _isSubscriber = isSubscriber; return this; } public ChatMessageBuilder WithIsVip(bool isVip) { _isVip = isVip; return this; } public ChatMessageBuilder WithIsStaff(bool isStaff) { _isStaff = isStaff; return this; } public ChatMessageBuilder WithIsPartner(bool isPartner) { _isPartner = isPartner; return this; } public ChatMessageBuilder WithMessage(string message) { _message = message; return this; } public ChatMessageBuilder WithNoisy(Noisy noisy) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) _noisy = noisy; return this; } public ChatMessageBuilder WithRawIrcMessage(string rawIrcMessage) { _rawIrcMessage = rawIrcMessage; return this; } public ChatMessageBuilder WithRoomId(string roomId) { _roomId = roomId; return this; } public ChatMessageBuilder WithSubscribedMonthCount(int subscribedMonthCount) { _subscribedMonthCount = subscribedMonthCount; return this; } public static ChatMessageBuilder Create() { return new ChatMessageBuilder(); } public ChatMessage Build() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) return new ChatMessage(_twitchLibMessage.BotUsername, _twitchLibMessage.UserId, _twitchLibMessage.Username, _twitchLibMessage.DisplayName, _twitchLibMessage.ColorHex, _twitchLibMessage.Color, _twitchLibMessage.EmoteSet, _message, _twitchLibMessage.UserType, _channel, _id, _isSubscriber, _subscribedMonthCount, _roomId, _twitchLibMessage.IsTurbo, _isModerator, _isMe, _isBroadcaster, _isVip, _isPartner, _isStaff, _noisy, _rawIrcMessage, _emoteReplacedMessage, _twitchLibMessage.Badges, _cheerBadge, _bits, _bitsInDollars); } } public sealed class CheerBadgeBuilder : IBuilder<CheerBadge> { private int _cheerAmount; public CheerBadgeBuilder WithCheerAmount(int cheerAmount) { _cheerAmount = cheerAmount; return this; } public CheerBadge Build() { return new CheerBadge(_cheerAmount); } } public sealed class CommunitySubscriptionBuilder : IFromIrcMessageBuilder<CommunitySubscription> { private CommunitySubscriptionBuilder() { } public static CommunitySubscriptionBuilder Create() { return new CommunitySubscriptionBuilder(); } public CommunitySubscription BuildFromIrcMessage(FromIrcMessageBuilderDataObject fromIrcMessageBuilderDataObject) { return new CommunitySubscription(fromIrcMessageBuilderDataObject.Message); } } public sealed class ConnectionCredentialsBuilder : IBuilder<ConnectionCredentials> { private string _twitchUsername; private string _twitchOAuth; private string _twitchWebsocketURI = "wss://irc-ws.chat.twitch.tv:443"; private bool _disableUsernameCheck; private ConnectionCredentialsBuilder() { } public ConnectionCredentialsBuilder WithTwitchUsername(string twitchUsername) { _twitchUsername = twitchUsername; return this; } public ConnectionCredentialsBuilder WithTwitchOAuth(string twitchOAuth) { _twitchOAuth = twitchOAuth; return this; } public ConnectionCredentialsBuilder WithTwitchWebSocketUri(string twitchWebSocketUri) { _twitchWebsocketURI = twitchWebSocketUri; return this; } public ConnectionCredentialsBuilder WithDisableUsernameCheck(bool disableUsernameCheck) { _disableUsernameCheck = disableUsernameCheck; return this; } public static ConnectionCredentialsBuilder Create() { return new ConnectionCredentialsBuilder(); } public ConnectionCredentials Build() { return new ConnectionCredentials(_twitchUsername, _twitchOAuth, _twitchWebsocketURI, _disableUsernameCheck); } } public sealed class EmoteBuilder : IBuilder<Emote> { private string _id; private string _name; private int _startIndex; private int _endIndex; private EmoteBuilder() { } public static EmoteBuilder Create() { return new EmoteBuilder(); } public EmoteBuilder WithId(string id) { _id = id; return this; } public EmoteBuilder WithName(string name) { _name = name; return this; } public EmoteBuilder WithStartIndex(int startIndex) { _startIndex = startIndex; return this; } public EmoteBuilder WithEndIndex(int endIndex) { _endIndex = endIndex; return this; } public Emote Build() { return new Emote(_id, _name, _startIndex, _endIndex); } } public sealed class ErrorEventBuilder : IBuilder<ErrorEvent> { private string _message; private ErrorEventBuilder() { } public ErrorEventBuilder WithMessage(string message) { _message = message; return this; } public static ErrorEventBuilder Create() { return new ErrorEventBuilder(); } public ErrorEvent Build() { return new ErrorEvent { Message = _message }; } } public class FromIrcMessageBuilderDataObject { public IrcMessage Message { get; set; } public object AditionalData { get; set; } } public sealed class GiftedSubscriptionBuilder : IBuilder<GiftedSubscription>, IFromIrcMessageBuilder<GiftedSubscription> { private readonly List<KeyValuePair<string, string>> _badges = new List<KeyValuePair<string, string>>(); private readonly List<KeyValuePair<string, string>> _badgeInfo = new List<KeyValuePair<string, string>>(); private string _color; private string _displayName; private string _emotes; private string _id; private bool _isModerator; private bool _isSubscriber; private bool _isTurbo; private string _login; private string _msgId; private string _msgParamMonths; private string _msgParamRecipientDisplayName; private string _msgParamRecipientId; private string _msgParamRecipientUserName; private string _msgParamSubPlanName; private string _msgParamMultiMonthGiftDuration; private SubscriptionPlan _msgParamSubPlan; private string _roomId; private string _systemMsg; private string _systemMsgParsed; private string _tmiSentTs; private string _userId; private UserType _userType; private GiftedSubscriptionBuilder() { } public GiftedSubscriptionBuilder WithBadges(params KeyValuePair<string, string>[] badges) { _badges.AddRange(badges); return this; } public GiftedSubscriptionBuilder WithBadgeInfos(params KeyValuePair<string, string>[] badgeInfos) { _badgeInfo.AddRange(badgeInfos); return this; } public GiftedSubscriptionBuilder WithColor(string color) { _color = color; return this; } public GiftedSubscriptionBuilder WithDisplayName(string displayName) { _displayName = displayName; return this; } public GiftedSubscriptionBuilder WithEmotes(string emotes) { _emotes = emotes; return this; } public GiftedSubscriptionBuilder WithId(string id) { _id = id; return this; } public GiftedSubscriptionBuilder WithIsModerator(bool isModerator) { _isModerator = isModerator; return this; } public GiftedSubscriptionBuilder WithIsSubscriber(bool isSubscriber) { _isSubscriber = isSubscriber; return this; } public GiftedSubscriptionBuilder WithIsTurbo(bool isTurbo) { _isTurbo = isTurbo; return this; } public GiftedSubscriptionBuilder WithLogin(string login) { _login = login; return this; } public GiftedSubscriptionBuilder WithMessageId(string msgId) { _msgId = msgId; return this; } public GiftedSubscriptionBuilder WithMsgParamCumulativeMonths(string msgParamMonths) { _msgParamMonths = msgParamMonths; return this; } public GiftedSubscriptionBuilder WithMsgParamRecipientDisplayName(string msgParamRecipientDisplayName) { _msgParamRecipientDisplayName = msgParamRecipientDisplayName; return this; } public GiftedSubscriptionBuilder WithMsgParamRecipientId(string msgParamRecipientId) { _msgParamRecipientId = msgParamRecipientId; return this; } public GiftedSubscriptionBuilder WithMsgParamRecipientUserName(string msgParamRecipientUserName) { _msgParamRecipientUserName = msgParamRecipientUserName; return this; } public GiftedSubscriptionBuilder WithMsgParamSubPlanName(string msgParamSubPlanName) { _msgParamSubPlanName = msgParamSubPlanName; return this; } public GiftedSubscriptionBuilder WithMsgParamMultiMonthGiftDuration(string msgParamMultiMonthGiftDuration) { _msgParamMultiMonthGiftDuration = msgParamMultiMonthGiftDuration; return this; } public GiftedSubscriptionBuilder WithMsgParamSubPlan(SubscriptionPlan msgParamSubPlan) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) _msgParamSubPlan = msgParamSubPlan; return this; } public GiftedSubscriptionBuilder WithRoomId(string roomId) { _roomId = roomId; return this; } public GiftedSubscriptionBuilder WithSystemMsg(string systemMsg) { _systemMsg = systemMsg; return this; } public GiftedSubscriptionBuilder WithSystemMsgParsed(string systemMsgParsed) { _systemMsgParsed = systemMsgParsed; return this; } public GiftedSubscriptionBuilder WithTmiSentTs(string tmiSentTs) { _tmiSentTs = tmiSentTs; return this; } public GiftedSubscriptionBuilder WithUserId(string userId) { _userId = userId; return this; } public GiftedSubscriptionBuilder WithUserType(UserType userType) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) _userType = userType; return this; } public static GiftedSubscriptionBuilder Create() { return new GiftedSubscriptionBuilder(); } public GiftedSubscription Build() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) return new GiftedSubscription(_badges, _badgeInfo, _color, _displayName, _emotes, _id, _login, _isModerator, _msgId, _msgParamMonths, _msgParamRecipientDisplayName, _msgParamRecipientId, _msgParamRecipientUserName, _msgParamSubPlanName, _msgParamMultiMonthGiftDuration, _msgParamSubPlan, _roomId, _isSubscriber, _systemMsg, _systemMsgParsed, _tmiSentTs, _isTurbo, _userType, _userId); } public GiftedSubscription BuildFromIrcMessage(FromIrcMessageBuilderDataObject fromIrcMessageBuilderDataObject) { return new GiftedSubscription(fromIrcMessageBuilderDataObject.Message); } } public interface IBuilder<T> { T Build(); } public interface IFromIrcMessageBuilder<T> { T BuildFromIrcMessage(FromIrcMessageBuilderDataObject fromIrcMessageBuilderDataObject); } public sealed class IrcMessageBuilder : IBuilder<IrcMessage> { private IrcCommand _ircCommand; private readonly List<string> _parameters = new List<string>(); private string _hostmask; private Dictionary<string, string> _tags; public static IrcMessageBuilder Create() { return new IrcMessageBuilder(); } private IrcMessageBuilder() { } public IrcMessageBuilder WithCommand(IrcCommand ircCommand) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) _ircCommand = ircCommand; return Builder(); } public IrcMessageBuilder WithParameter(params string[] parameters) { _parameters.AddRange(parameters); return Builder(); } private IrcMessageBuilder Builder() { return this; } public IrcMessage BuildWithUserOnly(string user) { return new IrcMessage(user); } public IrcMessageBuilder WithHostMask(string hostMask) { _hostmask = hostMask; return Builder(); } public IrcMessageBuilder WithTags(Dictionary<string, string> tags) { _tags = tags; return Builder(); } public IrcMessage Build() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return new IrcMessage(_ircCom
plugins/TwitchLib.Communication.dll
Decompiled 2 hours agousing System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Net.WebSockets; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; using TwitchLib.Communication.Clients; using TwitchLib.Communication.Enums; using TwitchLib.Communication.Events; using TwitchLib.Communication.Interfaces; using TwitchLib.Communication.Models; using TwitchLib.Communication.Services; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("swiftyspiffy, Prom3theu5, Syzuna, LuckyNoS7evin")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2022")] [assembly: AssemblyDescription("Connection library used throughout TwitchLib to replace third party depedencies.")] [assembly: AssemblyFileVersion("1.0.4")] [assembly: AssemblyInformationalVersion("1.0.4")] [assembly: AssemblyProduct("TwitchLib.Communication")] [assembly: AssemblyTitle("TwitchLib.Communication")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TwitchLib/TwitchLib.Communication")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("1.0.4.0")] namespace TwitchLib.Communication.Services { public class Throttlers { public readonly BlockingCollection<Tuple<DateTime, string>> SendQueue = new BlockingCollection<Tuple<DateTime, string>>(); public readonly BlockingCollection<Tuple<DateTime, string>> WhisperQueue = new BlockingCollection<Tuple<DateTime, string>>(); public bool ResetThrottlerRunning; public bool ResetWhisperThrottlerRunning; public int SentCount; public int WhispersSent; public Task ResetThrottler; public Task ResetWhisperThrottler; private readonly TimeSpan _throttlingPeriod; private readonly TimeSpan _whisperThrottlingPeriod; private readonly IClient _client; public bool Reconnecting { get; set; } public bool ShouldDispose { get; set; } public CancellationTokenSource TokenSource { get; set; } public Throttlers(IClient client, TimeSpan throttlingPeriod, TimeSpan whisperThrottlingPeriod) { _throttlingPeriod = throttlingPeriod; _whisperThrottlingPeriod = whisperThrottlingPeriod; _client = client; } public void StartThrottlingWindowReset() { ResetThrottler = Task.Run(async delegate { ResetThrottlerRunning = true; while (!ShouldDispose && !Reconnecting) { Interlocked.Exchange(ref SentCount, 0); await Task.Delay(_throttlingPeriod, TokenSource.Token); } ResetThrottlerRunning = false; return Task.CompletedTask; }); } public void StartWhisperThrottlingWindowReset() { ResetWhisperThrottler = Task.Run(async delegate { ResetWhisperThrottlerRunning = true; while (!ShouldDispose && !Reconnecting) { Interlocked.Exchange(ref WhispersSent, 0); await Task.Delay(_whisperThrottlingPeriod, TokenSource.Token); } ResetWhisperThrottlerRunning = false; return Task.CompletedTask; }); } public void IncrementSentCount() { Interlocked.Increment(ref SentCount); } public void IncrementWhisperCount() { Interlocked.Increment(ref WhispersSent); } public Task StartSenderTask() { StartThrottlingWindowReset(); return Task.Run(async delegate { _ = 2; try { while (!ShouldDispose) { await Task.Delay(_client.Options.SendDelay); if (SentCount == _client.Options.MessagesAllowedInPeriod) { _client.MessageThrottled(new OnMessageThrottledEventArgs { Message = "Message Throttle Occured. Too Many Messages within the period specified in WebsocketClientOptions.", AllowedInPeriod = _client.Options.MessagesAllowedInPeriod, Period = _client.Options.ThrottlingPeriod, SentMessageCount = Interlocked.CompareExchange(ref SentCount, 0, 0) }); } else if (_client.IsConnected && !ShouldDispose) { Tuple<DateTime, string> msg = SendQueue.Take(TokenSource.Token); if (!(msg.Item1.Add(_client.Options.SendCacheItemTimeout) < DateTime.UtcNow)) { try { IClient client = _client; if (client is WebSocketClient webSocketClient) { await webSocketClient.SendAsync(Encoding.UTF8.GetBytes(msg.Item2)); } else if (client is TwitchLib.Communication.Clients.TcpClient tcpClient) { await tcpClient.SendAsync(msg.Item2); } IncrementSentCount(); } catch (Exception exception) { _client.SendFailed(new OnSendFailedEventArgs { Data = msg.Item2, Exception = exception }); break; } } } } } catch (Exception exception2) { _client.SendFailed(new OnSendFailedEventArgs { Data = "", Exception = exception2 }); _client.Error(new OnErrorEventArgs { Exception = exception2 }); } }); } public Task StartWhisperSenderTask() { StartWhisperThrottlingWindowReset(); return Task.Run(async delegate { _ = 2; try { while (!ShouldDispose) { await Task.Delay(_client.Options.SendDelay); if (WhispersSent == _client.Options.WhispersAllowedInPeriod) { _client.WhisperThrottled(new OnWhisperThrottledEventArgs { Message = "Whisper Throttle Occured. Too Many Whispers within the period specified in ClientOptions.", AllowedInPeriod = _client.Options.WhispersAllowedInPeriod, Period = _client.Options.WhisperThrottlingPeriod, SentWhisperCount = Interlocked.CompareExchange(ref WhispersSent, 0, 0) }); } else if (_client.IsConnected && !ShouldDispose) { Tuple<DateTime, string> msg = WhisperQueue.Take(TokenSource.Token); if (!(msg.Item1.Add(_client.Options.SendCacheItemTimeout) < DateTime.UtcNow)) { try { IClient client = _client; if (client is WebSocketClient webSocketClient) { await webSocketClient.SendAsync(Encoding.UTF8.GetBytes(msg.Item2)); } else if (client is TwitchLib.Communication.Clients.TcpClient tcpClient) { await tcpClient.SendAsync(msg.Item2); } IncrementWhisperCount(); } catch (Exception exception) { _client.SendFailed(new OnSendFailedEventArgs { Data = msg.Item2, Exception = exception }); break; } } } } } catch (Exception exception2) { _client.SendFailed(new OnSendFailedEventArgs { Data = "", Exception = exception2 }); _client.Error(new OnErrorEventArgs { Exception = exception2 }); } }); } } } namespace TwitchLib.Communication.Models { public class ClientOptions : IClientOptions { public int SendQueueCapacity { get; set; } = 10000; public TimeSpan SendCacheItemTimeout { get; set; } = TimeSpan.FromMinutes(30.0); public ushort SendDelay { get; set; } = 50; public ReconnectionPolicy ReconnectionPolicy { get; set; } = new ReconnectionPolicy(3000, (int?)10); public bool UseSsl { get; set; } = true; public int DisconnectWait { get; set; } = 20000; public ClientType ClientType { get; set; } public TimeSpan ThrottlingPeriod { get; set; } = TimeSpan.FromSeconds(30.0); public int MessagesAllowedInPeriod { get; set; } = 100; public TimeSpan WhisperThrottlingPeriod { get; set; } = TimeSpan.FromSeconds(60.0); public int WhispersAllowedInPeriod { get; set; } = 100; public int WhisperQueueCapacity { get; set; } = 10000; } public class ReconnectionPolicy { private readonly int _reconnectStepInterval; private readonly int? _initMaxAttempts; private int _minReconnectInterval; private readonly int _maxReconnectInterval; private int? _maxAttempts; private int _attemptsMade; public ReconnectionPolicy() { _reconnectStepInterval = 3000; _minReconnectInterval = 3000; _maxReconnectInterval = 30000; _maxAttempts = null; _initMaxAttempts = null; _attemptsMade = 0; } public void SetMaxAttempts(int attempts) { _maxAttempts = attempts; } public void Reset() { _attemptsMade = 0; _minReconnectInterval = _reconnectStepInterval; _maxAttempts = _initMaxAttempts; } public void SetAttemptsMade(int count) { _attemptsMade = count; } public ReconnectionPolicy(int minReconnectInterval, int maxReconnectInterval, int? maxAttempts) { _reconnectStepInterval = minReconnectInterval; _minReconnectInterval = ((minReconnectInterval > maxReconnectInterval) ? maxReconnectInterval : minReconnectInterval); _maxReconnectInterval = maxReconnectInterval; _maxAttempts = maxAttempts; _initMaxAttempts = maxAttempts; _attemptsMade = 0; } public ReconnectionPolicy(int minReconnectInterval, int maxReconnectInterval) { _reconnectStepInterval = minReconnectInterval; _minReconnectInterval = ((minReconnectInterval > maxReconnectInterval) ? maxReconnectInterval : minReconnectInterval); _maxReconnectInterval = maxReconnectInterval; _maxAttempts = null; _initMaxAttempts = null; _attemptsMade = 0; } public ReconnectionPolicy(int reconnectInterval) { _reconnectStepInterval = reconnectInterval; _minReconnectInterval = reconnectInterval; _maxReconnectInterval = reconnectInterval; _maxAttempts = null; _initMaxAttempts = null; _attemptsMade = 0; } public ReconnectionPolicy(int reconnectInterval, int? maxAttempts) { _reconnectStepInterval = reconnectInterval; _minReconnectInterval = reconnectInterval; _maxReconnectInterval = reconnectInterval; _maxAttempts = maxAttempts; _initMaxAttempts = maxAttempts; _attemptsMade = 0; } internal void ProcessValues() { _attemptsMade++; if (_minReconnectInterval < _maxReconnectInterval) { _minReconnectInterval += _reconnectStepInterval; } if (_minReconnectInterval > _maxReconnectInterval) { _minReconnectInterval = _maxReconnectInterval; } } public int GetReconnectInterval() { return _minReconnectInterval; } public bool AreAttemptsComplete() { return _attemptsMade == _maxAttempts; } } } namespace TwitchLib.Communication.Interfaces { public interface IClient { TimeSpan DefaultKeepAliveInterval { get; set; } int SendQueueLength { get; } int WhisperQueueLength { get; } bool IsConnected { get; } IClientOptions Options { get; } event EventHandler<OnConnectedEventArgs> OnConnected; event EventHandler<OnDataEventArgs> OnData; event EventHandler<OnDisconnectedEventArgs> OnDisconnected; event EventHandler<OnErrorEventArgs> OnError; event EventHandler<OnFatalErrorEventArgs> OnFatality; event EventHandler<OnMessageEventArgs> OnMessage; event EventHandler<OnMessageThrottledEventArgs> OnMessageThrottled; event EventHandler<OnWhisperThrottledEventArgs> OnWhisperThrottled; event EventHandler<OnSendFailedEventArgs> OnSendFailed; event EventHandler<OnStateChangedEventArgs> OnStateChanged; event EventHandler<OnReconnectedEventArgs> OnReconnected; void Close(bool callDisconnect = true); void Dispose(); bool Open(); bool Send(string message); bool SendWhisper(string message); void Reconnect(); void MessageThrottled(OnMessageThrottledEventArgs eventArgs); void SendFailed(OnSendFailedEventArgs eventArgs); void Error(OnErrorEventArgs eventArgs); void WhisperThrottled(OnWhisperThrottledEventArgs eventArgs); } public interface IClientOptions { ClientType ClientType { get; set; } int DisconnectWait { get; set; } int MessagesAllowedInPeriod { get; set; } ReconnectionPolicy ReconnectionPolicy { get; set; } TimeSpan SendCacheItemTimeout { get; set; } ushort SendDelay { get; set; } int SendQueueCapacity { get; set; } TimeSpan ThrottlingPeriod { get; set; } bool UseSsl { get; set; } TimeSpan WhisperThrottlingPeriod { get; set; } int WhispersAllowedInPeriod { get; set; } int WhisperQueueCapacity { get; set; } } } namespace TwitchLib.Communication.Events { public class OnConnectedEventArgs : EventArgs { } public class OnDataEventArgs : EventArgs { public byte[] Data; } public class OnDisconnectedEventArgs : EventArgs { } public class OnErrorEventArgs : EventArgs { public Exception Exception { get; set; } } public class OnFatalErrorEventArgs : EventArgs { public string Reason; } public class OnMessageEventArgs : EventArgs { public string Message; } public class OnMessageThrottledEventArgs : EventArgs { public string Message { get; set; } public int SentMessageCount { get; set; } public TimeSpan Period { get; set; } public int AllowedInPeriod { get; set; } } public class OnReconnectedEventArgs : EventArgs { } public class OnSendFailedEventArgs : EventArgs { public string Data; public Exception Exception; } public class OnStateChangedEventArgs : EventArgs { public bool IsConnected; public bool WasConnected; } public class OnWhisperThrottledEventArgs : EventArgs { public string Message { get; set; } public int SentWhisperCount { get; set; } public TimeSpan Period { get; set; } public int AllowedInPeriod { get; set; } } } namespace TwitchLib.Communication.Enums { public enum ClientType { Chat, PubSub } } namespace TwitchLib.Communication.Clients { public class TcpClient : IClient { private int NotConnectedCounter; private readonly string _server = "irc.chat.twitch.tv"; private StreamReader _reader; private StreamWriter _writer; private readonly Throttlers _throttlers; private CancellationTokenSource _tokenSource = new CancellationTokenSource(); private bool _stopServices; private bool _networkServicesRunning; private Task[] _networkTasks; private Task _monitorTask; public TimeSpan DefaultKeepAliveInterval { get; set; } public int SendQueueLength => _throttlers.SendQueue.Count; public int WhisperQueueLength => _throttlers.WhisperQueue.Count; public bool IsConnected => Client?.Connected ?? false; public IClientOptions Options { get; } private int Port { get { if (Options == null) { return 0; } if (!Options.UseSsl) { return 80; } return 443; } } public System.Net.Sockets.TcpClient Client { get; private set; } public event EventHandler<OnConnectedEventArgs> OnConnected; public event EventHandler<OnDataEventArgs> OnData; public event EventHandler<OnDisconnectedEventArgs> OnDisconnected; public event EventHandler<OnErrorEventArgs> OnError; public event EventHandler<OnFatalErrorEventArgs> OnFatality; public event EventHandler<OnMessageEventArgs> OnMessage; public event EventHandler<OnMessageThrottledEventArgs> OnMessageThrottled; public event EventHandler<OnWhisperThrottledEventArgs> OnWhisperThrottled; public event EventHandler<OnSendFailedEventArgs> OnSendFailed; public event EventHandler<OnStateChangedEventArgs> OnStateChanged; public event EventHandler<OnReconnectedEventArgs> OnReconnected; public TcpClient(IClientOptions options = null) { Options = options ?? new ClientOptions(); _throttlers = new Throttlers(this, Options.ThrottlingPeriod, Options.WhisperThrottlingPeriod) { TokenSource = _tokenSource }; InitializeClient(); } private void InitializeClient() { Client = new System.Net.Sockets.TcpClient(); if (_monitorTask == null) { _monitorTask = StartMonitorTask(); } else if (_monitorTask.IsCompleted) { _monitorTask = StartMonitorTask(); } } public bool Open() { try { if (IsConnected) { return true; } Task.Run(delegate { InitializeClient(); Client.Connect(_server, Port); if (Options.UseSsl) { SslStream sslStream = new SslStream(Client.GetStream(), leaveInnerStreamOpen: false); sslStream.AuthenticateAsClient(_server); _reader = new StreamReader(sslStream); _writer = new StreamWriter(sslStream); } else { _reader = new StreamReader(Client.GetStream()); _writer = new StreamWriter(Client.GetStream()); } }).Wait(10000); if (!IsConnected) { return Open(); } StartNetworkServices(); return true; } catch (Exception) { InitializeClient(); return false; } } public void Close(bool callDisconnect = true) { _reader?.Dispose(); _writer?.Dispose(); Client?.Close(); _stopServices = callDisconnect; CleanupServices(); InitializeClient(); this.OnDisconnected?.Invoke(this, new OnDisconnectedEventArgs()); } public void Reconnect() { Task.Run(delegate { Task.Delay(20).Wait(); Close(); if (Open()) { this.OnReconnected?.Invoke(this, new OnReconnectedEventArgs()); } }); } public bool Send(string message) { try { if (!IsConnected || SendQueueLength >= Options.SendQueueCapacity) { return false; } _throttlers.SendQueue.Add(new Tuple<DateTime, string>(DateTime.UtcNow, message)); return true; } catch (Exception exception) { this.OnError?.Invoke(this, new OnErrorEventArgs { Exception = exception }); throw; } } public bool SendWhisper(string message) { try { if (!IsConnected || WhisperQueueLength >= Options.WhisperQueueCapacity) { return false; } _throttlers.WhisperQueue.Add(new Tuple<DateTime, string>(DateTime.UtcNow, message)); return true; } catch (Exception exception) { this.OnError?.Invoke(this, new OnErrorEventArgs { Exception = exception }); throw; } } private void StartNetworkServices() { _networkServicesRunning = true; _networkTasks = new Task[3] { StartListenerTask(), _throttlers.StartSenderTask(), _throttlers.StartWhisperSenderTask() }.ToArray(); if (_networkTasks.Any((Task c) => c.IsFaulted)) { _networkServicesRunning = false; CleanupServices(); } } public Task SendAsync(string message) { return Task.Run(async delegate { await _writer.WriteLineAsync(message); await _writer.FlushAsync(); }); } private Task StartListenerTask() { return Task.Run(async delegate { while (IsConnected && _networkServicesRunning) { try { string text = await _reader.ReadLineAsync(); if (text == null && IsConnected) { Send("PING"); Task.Delay(500).Wait(); } this.OnMessage?.Invoke(this, new OnMessageEventArgs { Message = text }); } catch (Exception exception) { this.OnError?.Invoke(this, new OnErrorEventArgs { Exception = exception }); } } }); } private Task StartMonitorTask() { return Task.Run(delegate { bool flag = false; int num = 0; try { bool isConnected = IsConnected; while (!_tokenSource.IsCancellationRequested) { if (isConnected == IsConnected) { Thread.Sleep(200); if (!IsConnected) { NotConnectedCounter++; } else { num++; } if (num >= 300) { Send("PING"); num = 0; } switch (NotConnectedCounter) { case 25: case 75: case 150: case 300: case 600: Reconnect(); break; default: if (NotConnectedCounter >= 1200 && NotConnectedCounter % 600 == 0) { Reconnect(); } break; } if (NotConnectedCounter != 0 && IsConnected) { NotConnectedCounter = 0; } } else { this.OnStateChanged?.Invoke(this, new OnStateChangedEventArgs { IsConnected = IsConnected, WasConnected = isConnected }); if (IsConnected) { this.OnConnected?.Invoke(this, new OnConnectedEventArgs()); } if (!IsConnected && !_stopServices) { if (isConnected && Options.ReconnectionPolicy != null && !Options.ReconnectionPolicy.AreAttemptsComplete()) { flag = true; break; } this.OnDisconnected?.Invoke(this, new OnDisconnectedEventArgs()); } isConnected = IsConnected; } } } catch (Exception exception) { this.OnError?.Invoke(this, new OnErrorEventArgs { Exception = exception }); } if (flag && !_stopServices) { Reconnect(); } }, _tokenSource.Token); } private void CleanupServices() { _tokenSource.Cancel(); _tokenSource = new CancellationTokenSource(); _throttlers.TokenSource = _tokenSource; if (_stopServices) { Task[] networkTasks = _networkTasks; if (networkTasks != null && networkTasks.Length != 0 && !Task.WaitAll(_networkTasks, 15000)) { this.OnFatality?.Invoke(this, new OnFatalErrorEventArgs { Reason = "Fatal network error. Network services fail to shut down." }); _stopServices = false; _throttlers.Reconnecting = false; _networkServicesRunning = false; } } } public void WhisperThrottled(OnWhisperThrottledEventArgs eventArgs) { this.OnWhisperThrottled?.Invoke(this, eventArgs); } public void MessageThrottled(OnMessageThrottledEventArgs eventArgs) { this.OnMessageThrottled?.Invoke(this, eventArgs); } public void SendFailed(OnSendFailedEventArgs eventArgs) { this.OnSendFailed?.Invoke(this, eventArgs); } public void Error(OnErrorEventArgs eventArgs) { this.OnError?.Invoke(this, eventArgs); } public void Dispose() { Close(); _throttlers.ShouldDispose = true; _tokenSource.Cancel(); Thread.Sleep(500); _tokenSource.Dispose(); Client?.Dispose(); GC.Collect(); } } public class WebSocketClient : IClient { private int NotConnectedCounter; private readonly Throttlers _throttlers; private CancellationTokenSource _tokenSource = new CancellationTokenSource(); private bool _stopServices; private bool _networkServicesRunning; private Task[] _networkTasks; private Task _monitorTask; public TimeSpan DefaultKeepAliveInterval { get; set; } public int SendQueueLength => _throttlers.SendQueue.Count; public int WhisperQueueLength => _throttlers.WhisperQueue.Count; public bool IsConnected { get { ClientWebSocket client = Client; if (client == null) { return false; } return client.State == WebSocketState.Open; } } public IClientOptions Options { get; } public ClientWebSocket Client { get; private set; } private string Url { get; } public event EventHandler<OnConnectedEventArgs> OnConnected; public event EventHandler<OnDataEventArgs> OnData; public event EventHandler<OnDisconnectedEventArgs> OnDisconnected; public event EventHandler<OnErrorEventArgs> OnError; public event EventHandler<OnFatalErrorEventArgs> OnFatality; public event EventHandler<OnMessageEventArgs> OnMessage; public event EventHandler<OnMessageThrottledEventArgs> OnMessageThrottled; public event EventHandler<OnWhisperThrottledEventArgs> OnWhisperThrottled; public event EventHandler<OnSendFailedEventArgs> OnSendFailed; public event EventHandler<OnStateChangedEventArgs> OnStateChanged; public event EventHandler<OnReconnectedEventArgs> OnReconnected; public WebSocketClient(IClientOptions options = null) { Options = options ?? new ClientOptions(); switch (Options.ClientType) { case ClientType.Chat: Url = (Options.UseSsl ? "wss://irc-ws.chat.twitch.tv:443" : "ws://irc-ws.chat.twitch.tv:80"); break; case ClientType.PubSub: Url = (Options.UseSsl ? "wss://pubsub-edge.twitch.tv:443" : "ws://pubsub-edge.twitch.tv:80"); break; default: throw new ArgumentOutOfRangeException(); } _throttlers = new Throttlers(this, Options.ThrottlingPeriod, Options.WhisperThrottlingPeriod) { TokenSource = _tokenSource }; } private void InitializeClient() { Client?.Abort(); Client = new ClientWebSocket(); if (_monitorTask == null) { _monitorTask = StartMonitorTask(); } else if (_monitorTask.IsCompleted) { _monitorTask = StartMonitorTask(); } } public bool Open() { try { if (IsConnected) { return true; } InitializeClient(); Client.ConnectAsync(new Uri(Url), _tokenSource.Token).Wait(10000); if (!IsConnected) { return Open(); } StartNetworkServices(); return true; } catch (WebSocketException) { InitializeClient(); return false; } } public void Close(bool callDisconnect = true) { Client?.Abort(); _stopServices = callDisconnect; CleanupServices(); InitializeClient(); this.OnDisconnected?.Invoke(this, new OnDisconnectedEventArgs()); } public void Reconnect() { Task.Run(delegate { Task.Delay(20).Wait(); Close(); if (Open()) { this.OnReconnected?.Invoke(this, new OnReconnectedEventArgs()); } }); } public bool Send(string message) { try { if (!IsConnected || SendQueueLength >= Options.SendQueueCapacity) { return false; } _throttlers.SendQueue.Add(new Tuple<DateTime, string>(DateTime.UtcNow, message)); return true; } catch (Exception exception) { this.OnError?.Invoke(this, new OnErrorEventArgs { Exception = exception }); throw; } } public bool SendWhisper(string message) { try { if (!IsConnected || WhisperQueueLength >= Options.WhisperQueueCapacity) { return false; } _throttlers.WhisperQueue.Add(new Tuple<DateTime, string>(DateTime.UtcNow, message)); return true; } catch (Exception exception) { this.OnError?.Invoke(this, new OnErrorEventArgs { Exception = exception }); throw; } } private void StartNetworkServices() { _networkServicesRunning = true; _networkTasks = new Task[3] { StartListenerTask(), _throttlers.StartSenderTask(), _throttlers.StartWhisperSenderTask() }.ToArray(); if (_networkTasks.Any((Task c) => c.IsFaulted)) { _networkServicesRunning = false; CleanupServices(); } } public Task SendAsync(byte[] message) { return Client.SendAsync(new ArraySegment<byte>(message), WebSocketMessageType.Text, endOfMessage: true, _tokenSource.Token); } private Task StartListenerTask() { return Task.Run(async delegate { string message = ""; while (IsConnected && _networkServicesRunning) { byte[] buffer = new byte[1024]; WebSocketReceiveResult webSocketReceiveResult; try { webSocketReceiveResult = await Client.ReceiveAsync(new ArraySegment<byte>(buffer), _tokenSource.Token); } catch { InitializeClient(); break; } if (webSocketReceiveResult != null) { switch (webSocketReceiveResult.MessageType) { case WebSocketMessageType.Close: Close(); break; case WebSocketMessageType.Text: if (!webSocketReceiveResult.EndOfMessage) { message += Encoding.UTF8.GetString(buffer).TrimEnd(new char[1]); continue; } message += Encoding.UTF8.GetString(buffer).TrimEnd(new char[1]); this.OnMessage?.Invoke(this, new OnMessageEventArgs { Message = message }); break; default: throw new ArgumentOutOfRangeException(); case WebSocketMessageType.Binary: break; } message = ""; } } }); } private Task StartMonitorTask() { return Task.Run(delegate { bool flag = false; int num = 0; try { bool isConnected = IsConnected; while (!_tokenSource.IsCancellationRequested) { if (isConnected == IsConnected) { Thread.Sleep(200); if (!IsConnected) { NotConnectedCounter++; } else { num++; } if (num >= 300) { Send("PING"); num = 0; } switch (NotConnectedCounter) { case 25: case 75: case 150: case 300: case 600: Reconnect(); break; default: if (NotConnectedCounter >= 1200 && NotConnectedCounter % 600 == 0) { Reconnect(); } break; } if (NotConnectedCounter != 0 && IsConnected) { NotConnectedCounter = 0; } } else { this.OnStateChanged?.Invoke(this, new OnStateChangedEventArgs { IsConnected = (Client.State == WebSocketState.Open), WasConnected = isConnected }); if (IsConnected) { this.OnConnected?.Invoke(this, new OnConnectedEventArgs()); } if (!IsConnected && !_stopServices) { if (isConnected && Options.ReconnectionPolicy != null && !Options.ReconnectionPolicy.AreAttemptsComplete()) { flag = true; break; } this.OnDisconnected?.Invoke(this, new OnDisconnectedEventArgs()); if (Client.CloseStatus.HasValue && Client.CloseStatus != WebSocketCloseStatus.NormalClosure) { this.OnError?.Invoke(this, new OnErrorEventArgs { Exception = new Exception(Client.CloseStatus.ToString() + " " + Client.CloseStatusDescription) }); } } isConnected = IsConnected; } } } catch (Exception exception) { this.OnError?.Invoke(this, new OnErrorEventArgs { Exception = exception }); } if (flag && !_stopServices) { Reconnect(); } }, _tokenSource.Token); } private void CleanupServices() { _tokenSource.Cancel(); _tokenSource = new CancellationTokenSource(); _throttlers.TokenSource = _tokenSource; if (_stopServices) { Task[] networkTasks = _networkTasks; if (networkTasks != null && networkTasks.Length != 0 && !Task.WaitAll(_networkTasks, 15000)) { this.OnFatality?.Invoke(this, new OnFatalErrorEventArgs { Reason = "Fatal network error. Network services fail to shut down." }); _stopServices = false; _throttlers.Reconnecting = false; _networkServicesRunning = false; } } } public void WhisperThrottled(OnWhisperThrottledEventArgs eventArgs) { this.OnWhisperThrottled?.Invoke(this, eventArgs); } public void MessageThrottled(OnMessageThrottledEventArgs eventArgs) { this.OnMessageThrottled?.Invoke(this, eventArgs); } public void SendFailed(OnSendFailedEventArgs eventArgs) { this.OnSendFailed?.Invoke(this, eventArgs); } public void Error(OnErrorEventArgs eventArgs) { this.OnError?.Invoke(this, eventArgs); } public void Dispose() { Close(); _throttlers.ShouldDispose = true; _tokenSource.Cancel(); Thread.Sleep(500); _tokenSource.Dispose(); Client?.Dispose(); GC.Collect(); } } }
plugins/V8.TwitchChat.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using ExitGames.Client.Photon; using HarmonyLib; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Logging; using Photon.Pun; using Photon.Realtime; using TMPro; using TwitchLib.Client; using TwitchLib.Client.Enums; using TwitchLib.Client.Events; using TwitchLib.Client.Models; using TwitchLib.Communication.Clients; using TwitchLib.Communication.Interfaces; using TwitchLib.Communication.Models; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.UI; using UnityEngine.UI.ProceduralImage; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("V8.TwitchChat")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.1.1.0")] [assembly: AssemblyInformationalVersion("1.1.1")] [assembly: AssemblyProduct("V8.TwitchChat")] [assembly: AssemblyTitle("TwitchChat")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.1.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace System.Runtime.CompilerServices { [CompilerGenerated] [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] [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] [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 BepInEx { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] [Conditional("CodeGeneration")] [Embedded] internal sealed class BepInAutoPluginAttribute : Attribute { public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null) { } } } namespace BepInEx.Preloader.Core.Patching { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] [Conditional("CodeGeneration")] [Embedded] internal sealed class PatcherAutoPluginAttribute : Attribute { public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null) { } } } namespace Microsoft.CodeAnalysis { [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace PeakTextChat { public class BarGroupChildWatcher : MonoBehaviour { public Transform textChatDummyTransform; private void OnTransformChildrenChanged() { if ((Object)(object)textChatDummyTransform != (Object)null && textChatDummyTransform.GetSiblingIndex() > 0) { textChatDummyTransform.SetAsFirstSibling(); } } } public class TextChatDisplay : MonoBehaviour { public class ChatMessage { public string message; public GameObject textObj; public TMP_Text text; private Color textColor; private float hideDelay = 40f; private float hideTime = 10f; private float hideTimer = -1f; private float hide; public void Update() { //IL_0078: Unknown result type (might be due to invalid IL or missing references) hideTimer -= Time.deltaTime; if (hideTimer <= 0f && hide < 1f) { hide += Time.deltaTime / hideTime; ((Graphic)text).color = new Color(textColor.r, textColor.g, textColor.b, 1f - hide); } } public ChatMessage(string message, GameObject textObject, float hideDelay) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) this.message = message; textObj = textObject; text = textObject.GetComponent<TMP_Text>(); textColor = ((Graphic)text).color; this.hideDelay = hideDelay; hideTimer = hideDelay; } } private int maxMessages = 30; private Vector2 boxSize = new Vector2(500f, 300f); private float fadeInTime = 0.03f; private float fadeOutTime = 5f; private float hideTime = 5f; private float fadeOutDelay = 15f; private float hideDelay = 40f; private float messageHideDelay = 40f; private float fontSize = 25f; private bool usingIMGUI; private TMP_InputField inputField; private RectTransform chatLogViewportTransform; private RectTransform baseTransform; private CanvasGroup canvasGroup; private float fade = 1f; private float fadeTimer = -1f; private float hide; private float hideTimer = -1f; private KeysHelper.KeyCodeInfo keyInfo; private Color offWhite = new Color(0.87f, 0.85f, 0.76f); private Color red = new Color(0.99f, 0.33f, 0f); private List<ChatMessage> messages = new List<ChatMessage>(); public bool isBlockingInput; public int framesSinceInputBlocked; public static TextChatDisplay instance; private string imguiFieldString = ""; private bool imguiTyping; private GameObject currentSelection; private void Awake() { instance = this; } private void Start() { //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) keyInfo = KeysHelper.GetKeyCodeShortInfo(PeakTextChatPlugin.configKey.Value); fontSize = ((PeakTextChatPlugin.configFontSize.Value < 0f) ? 1E+09f : PeakTextChatPlugin.configFontSize.Value); hideDelay = ((PeakTextChatPlugin.configHideDelay.Value < 0f) ? float.PositiveInfinity : PeakTextChatPlugin.configHideDelay.Value); fadeOutDelay = Mathf.Min((PeakTextChatPlugin.configFadeDelay.Value < 0f) ? float.PositiveInfinity : PeakTextChatPlugin.configFadeDelay.Value, hideDelay); messageHideDelay = ((PeakTextChatPlugin.configMessageFadeDelay.Value < 0f) ? float.PositiveInfinity : PeakTextChatPlugin.configMessageFadeDelay.Value); usingIMGUI = PeakTextChatPlugin.configIMGUI.Value; string[] array = PeakTextChatPlugin.configChatSize.Value.Split(':'); if (array.Length >= 2) { string s = array[0].Replace(" ", ""); string s2 = array[1].Replace(" ", ""); if (float.TryParse(s, out var result) && float.TryParse(s2, out var result2)) { boxSize = new Vector2(Mathf.Max(result, 10f), Mathf.Max(result2, 10f)); } else { boxSize = new Vector2(500f, 300f); } } ResetTimers(); SetupChatGUI(); } private void Update() { //IL_008e: Unknown result type (might be due to invalid IL or missing references) if (isBlockingInput) { framesSinceInputBlocked = -1; } else { framesSinceInputBlocked = Mathf.Min(framesSinceInputBlocked + 1, 50); } if (!((Component)this).gameObject.activeInHierarchy) { isBlockingInput = false; return; } if ((Object)(object)currentSelection != (Object)(object)EventSystem.current.currentSelectedGameObject) { currentSelection = EventSystem.current.currentSelectedGameObject; if ((Object)(object)currentSelection != (Object)(object)((Component)inputField).gameObject) { isBlockingInput = false; } } if (!InputBlockingPatches.IsInputBlocked() && Input.GetKeyDown(keyInfo.key) && (Object)(object)inputField != (Object)null && (Object)(object)EventSystem.current != (Object)null) { if (usingIMGUI) { imguiTyping = true; GUI.FocusControl("ptctf"); } else { EventSystem.current.SetSelectedGameObject(((Component)inputField).gameObject, (BaseEventData)null); inputField.ActivateInputField(); } isBlockingInput = true; } if (isBlockingInput) { ResetTimers(); } if (PeakTextChatPlugin.configPos.Value == PeakTextChatPlugin.TextChatPosition.BottomLeft) { UpdatePosition(isBottomLeft: true); } fade = Mathf.Clamp((fadeTimer <= 0f) ? (fade - Time.deltaTime / fadeOutTime) : (fade + Time.deltaTime / fadeInTime), 0f, 1f); hide = Mathf.Clamp((hideTimer <= 0f) ? (hide + Time.deltaTime / hideTime) : (hide - Time.deltaTime / fadeInTime), 0f, 1f); fadeTimer -= Time.deltaTime; hideTimer -= Time.deltaTime; if ((Object)(object)canvasGroup != (Object)null) { canvasGroup.alpha = fade * 0.5f + (1f - hide) * 0.5f; } foreach (ChatMessage message in messages) { message.Update(); } } private void SetupChatGUI() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Expected O, but got Unknown //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02c2: Unknown result type (might be due to invalid IL or missing references) //IL_0351: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Expected O, but got Unknown //IL_03bb: Unknown result type (might be due to invalid IL or missing references) //IL_03c2: Expected O, but got Unknown //IL_03e0: Unknown result type (might be due to invalid IL or missing references) //IL_03ec: Unknown result type (might be due to invalid IL or missing references) //IL_03f8: Unknown result type (might be due to invalid IL or missing references) //IL_0404: Unknown result type (might be due to invalid IL or missing references) //IL_041a: Unknown result type (might be due to invalid IL or missing references) GUIManager val = GUIManager.instance; baseTransform = ((Component)this).gameObject.GetComponent<RectTransform>() ?? ((Component)this).gameObject.AddComponent<RectTransform>(); ((Transform)baseTransform).SetParent(((Component)this).transform, false); UpdatePosition(); baseTransform.sizeDelta = boxSize; canvasGroup = ((Component)this).gameObject.AddComponent<CanvasGroup>(); canvasGroup.alpha = 1f; canvasGroup.blocksRaycasts = true; canvasGroup.interactable = true; canvasGroup.ignoreParentGroups = false; GameObject val2 = new GameObject("Shadow"); val2.transform.SetParent((Transform)(object)baseTransform, false); RectTransform val3 = val2.AddComponent<RectTransform>(); val3.anchorMin = Vector2.zero; val3.anchorMax = Vector2.one; val3.offsetMin = Vector2.zero; val3.offsetMax = Vector2.zero; ProceduralImage val4 = val2.AddComponent<ProceduralImage>(); ((Graphic)val4).color = new Color(0f, 0f, 0f, PeakTextChatPlugin.configBgOpacity.Value); val4.FalloffDistance = 10f; val4.SetModifierType<UniformModifier>().Radius = fontSize / 4f + 10f; GameObject val5 = new GameObject("ChatLog"); RectTransform val6 = val5.AddComponent<RectTransform>(); ((Transform)val6).SetParent((Transform)(object)baseTransform, false); val6.anchorMin = Vector2.zero; val6.anchorMax = Vector2.one; val6.offsetMin = new Vector2(0f, fontSize * 2f); val6.offsetMax = Vector2.zero; val5.AddComponent<RectMask2D>(); GameObject val7 = new GameObject("Viewport"); chatLogViewportTransform = val7.AddComponent<RectTransform>(); ((Transform)chatLogViewportTransform).SetParent((Transform)(object)val6, false); chatLogViewportTransform.pivot = new Vector2(0.5f, 0f); chatLogViewportTransform.anchorMin = Vector2.zero; chatLogViewportTransform.anchorMax = new Vector2(1f, 0f); chatLogViewportTransform.offsetMin = Vector2.zero; chatLogViewportTransform.offsetMax = new Vector2(0f, 5000f); inputField = CreateInputField(); RectTransform val8 = (RectTransform)((Component)inputField).transform; val8.pivot = new Vector2(0.5f, 0f); val8.anchorMin = new Vector2(0f, 0f); val8.anchorMax = new Vector2(1f, 0f); val8.offsetMin = new Vector2(5f, 5f); val8.offsetMax = new Vector2(-5f, fontSize * 1.75f); ((Transform)val8).SetParent((Transform)(object)baseTransform, false); VerticalLayoutGroup val9 = val7.AddComponent<VerticalLayoutGroup>(); ((HorizontalOrVerticalLayoutGroup)val9).childControlWidth = true; ((HorizontalOrVerticalLayoutGroup)val9).childControlHeight = false; ((HorizontalOrVerticalLayoutGroup)val9).childForceExpandWidth = true; ((HorizontalOrVerticalLayoutGroup)val9).childForceExpandHeight = false; ((HorizontalOrVerticalLayoutGroup)val9).childScaleWidth = false; ((HorizontalOrVerticalLayoutGroup)val9).childScaleHeight = false; ((LayoutGroup)val9).childAlignment = (TextAnchor)7; ((LayoutGroup)val9).padding = new RectOffset((int)(fontSize * 0.6f), (int)(fontSize * 0.6f), (int)(fontSize / 20f), (int)(fontSize / 20f)); ((HorizontalOrVerticalLayoutGroup)val9).spacing = (0f - fontSize) / 8f; ((UnityEvent<string>)(object)inputField.onSubmit).AddListener((UnityAction<string>)delegate(string e) { inputField.text = ""; inputField.textComponent.text = ""; TextChatManager.instance?.SendChatMessage(e); }); ((UnityEvent<string>)(object)inputField.onEndEdit).AddListener((UnityAction<string>)delegate { EventSystem.current.SetSelectedGameObject((GameObject)null); isBlockingInput = false; }); if (PeakTextChatPlugin.configFrameVisible.Value) { GameObject val10 = new GameObject("Border"); val10.transform.SetParent((Transform)(object)baseTransform, false); RectTransform val11 = val10.AddComponent<RectTransform>(); val11.anchorMin = Vector2.zero; val11.anchorMax = Vector2.one; val11.offsetMin = Vector2.zero; val11.offsetMax = Vector2.zero; ProceduralImage val12 = val10.AddComponent<ProceduralImage>(); ((Graphic)val12).color = offWhite; val12.BorderWidth = 2f; val12.SetModifierType<UniformModifier>().Radius = fontSize / 4f + 5f; } } private TMP_InputField CreateInputField() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown //IL_0064: 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_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("InputField"); TMP_InputField val2 = val.AddComponent<TMP_InputField>(); ((Behaviour)val2).enabled = false; ProceduralImage val3 = (ProceduralImage)(object)(((Selectable)val2).targetGraphic = (Graphic)(object)((Component)val2).gameObject.AddComponent<ProceduralImage>()); ((Graphic)val3).color = offWhite; val3.SetModifierType<UniformModifier>().Radius = fontSize / 4f; GameObject val5 = new GameObject("Text Area"); RectTransform val6 = val5.AddComponent<RectTransform>(); val6.anchorMax = Vector2.one; val6.anchorMin = Vector2.zero; val6.offsetMax = new Vector2((0f - fontSize) / 2f, (0f - fontSize) * 0.3f); val6.offsetMin = new Vector2(fontSize / 2f, fontSize * 0.3f); ((Transform)val6).SetParent(((Component)val2).transform, false); RectMask2D val7 = val5.AddComponent<RectMask2D>(); val7.padding = new Vector4((0f - fontSize) * 0.4f, (0f - fontSize) / 4f, (0f - fontSize) * 0.4f, (0f - fontSize) / 4f); TMP_Text val8 = CreateText((Transform)(object)val6); ((Graphic)val8).color = new Color(0f, 0f, 0f, 0.6f); val8.text = "Press " + keyInfo.keyText + " to chat"; TMP_Text val9 = CreateText((Transform)(object)val6); ((Graphic)val9).color = new Color(0f, 0f, 0f, 1f); val2.textViewport = val6; val2.textComponent = val9; val2.placeholder = (Graphic)(object)val8; val2.richText = false; val2.restoreOriginalTextOnEscape = false; ((Behaviour)val2).enabled = true; return val2; } private TMP_Text CreateText(Transform parent) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("Text"); RectTransform val2 = val.AddComponent<RectTransform>(); val2.anchorMax = Vector2.one; val2.anchorMin = Vector2.zero; val2.offsetMax = new Vector2(-2f, 0f); val2.offsetMin = new Vector2(2f, 4f); ((Transform)val2).SetParent(parent, false); TextMeshProUGUI val3 = val.AddComponent<TextMeshProUGUI>(); ((TMP_Text)val3).text = "New Text"; if ((Object)(object)GUIManagerPatch.darumaDropOneFont != (Object)null) { ((TMP_Text)val3).font = GUIManagerPatch.darumaDropOneFont; } ((TMP_Text)val3).fontSize = fontSize; ((TMP_Text)val3).horizontalAlignment = (HorizontalAlignmentOptions)1; ((TMP_Text)val3).verticalAlignment = (VerticalAlignmentOptions)512; return (TMP_Text)(object)val3; } public void AddMessage(string message) { //IL_0027: 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_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)chatLogViewportTransform != (Object)null)) { return; } TMP_Text val = CreateText((Transform)(object)chatLogViewportTransform); val.text = message; ((Graphic)val).color = offWhite; val.lineSpacing = (0f - fontSize) * 0.75f; Vector2 preferredValues = val.GetPreferredValues(message, boxSize.x - 24f, 1000f); ((RectTransform)val.transform).sizeDelta = new Vector2(0f, preferredValues.y); ChatMessage item = new ChatMessage(message, ((Component)val).gameObject, messageHideDelay); messages.Add(item); if (messages.Count > maxMessages) { ChatMessage chatMessage = messages[0]; if (chatMessage != null && (Object)(object)chatMessage.textObj != (Object)null) { Object.Destroy((Object)(object)chatMessage.textObj); } messages.RemoveAt(0); } ResetTimers(); } public void AddMessage(TextChatManager.Message messageData) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)chatLogViewportTransform != (Object)null) { Color val = (Color)(((Object)(object)messageData.character != (Object)null) ? messageData.character.refs.customization.PlayerColor : new Color(0.64f, 0.69f, 0.83f)); string[] obj = new string[5] { "<color=#", ColorUtility.ToHtmlStringRGB(val), ">[", null, null }; Character character = messageData.character; obj[3] = ((character != null) ? character.characterName : null) ?? "Unknown"; obj[4] = "]</color>"; string text = string.Concat(obj); string text2 = messageData.message; if (!PeakTextChatPlugin.configRichTextEnabled.Value) { text2 = Regex.Replace(text2, "<.*?>", string.Empty); } AddMessage(text + ": " + text2); } } private void ResetTimers() { fadeTimer = fadeOutDelay; hideTimer = hideDelay; } private void UpdatePosition(bool isBottomLeft = false) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0089: 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_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) if (isBottomLeft || PeakTextChatPlugin.configPos.Value == PeakTextChatPlugin.TextChatPosition.BottomLeft) { if ((Object)(object)baseTransform != (Object)null && (Object)(object)StaminaBarPatch.barGroupChildWatcher.textChatDummyTransform != (Object)null) { baseTransform.pivot = Vector2.zero; baseTransform.anchorMax = Vector2.zero; baseTransform.anchorMin = Vector2.zero; ((Transform)baseTransform).position = StaminaBarPatch.barGroupChildWatcher.textChatDummyTransform.position; RectTransform obj = baseTransform; obj.anchoredPosition += new Vector2(0f, 40f); } } else if (PeakTextChatPlugin.configPos.Value == PeakTextChatPlugin.TextChatPosition.TopLeft) { baseTransform.pivot = new Vector2(0f, 1f); baseTransform.anchorMax = new Vector2(0f, 1f); baseTransform.anchorMin = new Vector2(0f, 1f); baseTransform.anchoredPosition = new Vector2(64f, -62f); } else if (PeakTextChatPlugin.configPos.Value == PeakTextChatPlugin.TextChatPosition.TopRight) { baseTransform.pivot = Vector2.one; baseTransform.anchorMax = Vector2.one; baseTransform.anchorMin = Vector2.one; baseTransform.anchoredPosition = new Vector2(-64f, -62f); } } private void OnGUI() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Invalid comparison between Unknown and I4 if (imguiTyping) { GUI.SetNextControlName("ptctf"); GUIStyle val = new GUIStyle(); val.fontSize = (int)(fontSize * 0.8f); val.clipping = (TextClipping)1; val.padding = new RectOffset((int)(fontSize * 0.7f), (int)(fontSize * 0.7f), (int)(fontSize * 0.24f), 0); Rect val2 = RectTransformToScreenSpace((RectTransform)((Component)inputField).transform); PeakTextChatPlugin.Logger.LogInfo((object)(((Rect)(ref val2)).xMin + " " + ((Rect)(ref val2)).yMin)); imguiFieldString = GUI.TextArea(val2, imguiFieldString, val); inputField.text = " "; if (GUI.GetNameOfFocusedControl() != "ptctf") { GUI.FocusControl("ptctf"); } if (imguiFieldString.Contains("\n")) { TextChatManager.instance?.SendChatMessage(imguiFieldString.Replace("\n", "")); imguiFieldString = ""; GUI.FocusControl(""); Event.current.Use(); imguiTyping = false; isBlockingInput = false; inputField.text = ""; } else if (Event.current.isKey && (int)Event.current.keyCode == 27) { GUI.FocusControl(""); imguiTyping = false; inputField.text = imguiFieldString; isBlockingInput = false; Event.current.Use(); } } } public static Rect RectTransformToScreenSpace(RectTransform transform) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //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_001e: 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_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: 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) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) Rect rect = transform.rect; Vector2 val = Vector2.Scale(((Rect)(ref rect)).size, Vector2.op_Implicit(((Transform)transform).lossyScale)); Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(((Transform)transform).position.x, (float)Screen.height - ((Transform)transform).position.y); return new Rect(val2 - val * new Vector2(0.5f, 1f), val); } } public class TextChatManager : MonoBehaviour { public class Message { public Character character; public string message; public bool isDead; public Message(string userId, string message, bool isDead) { character = Character.AllCharacters.Find(delegate(Character c) { PhotonView photonView = ((MonoBehaviourPun)c).photonView; object obj; if (photonView == null) { obj = null; } else { Player owner = photonView.Owner; obj = ((owner != null) ? owner.UserId : null); } return (string?)obj == userId; }); this.message = message; this.isDead = isDead; } } public static TextChatManager instance; private Character character; private byte chatEventCode = 81; private void Start() { instance = this; character = ((Component)this).GetComponent<Character>(); PeakTextChatPlugin.Logger.LogInfo((object)"[TextChatManager] Start()"); } private void OnEnable() { PhotonNetwork.NetworkingClient.EventReceived += OnEventReceived; } private void OnDisable() { PhotonNetwork.NetworkingClient.EventReceived -= OnEventReceived; } private void OnEventReceived(EventData eventData) { if (eventData.Code == chatEventCode) { object[] array = (object[])eventData.CustomData; if (array.Length >= 4) { string text = array[2]?.ToString() ?? ""; string text2 = array[1]?.ToString() ?? ""; bool result; bool isDead = bool.TryParse(array[3]?.ToString(), out result) && result; ReceiveChatMessage(text, text2, isDead); PeakTextChatPlugin.Logger.LogInfo((object)("[TextChatManager] Event received: userId=" + text + ", message='" + text2 + "'")); } } } public void ReceiveChatMessage(string userId, string message, bool isDead) { if ((Object)(object)TextChatDisplay.instance != (Object)null) { TextChatDisplay.instance.AddMessage(new Message(userId, message, isDead)); } } public void SendChatMessage(string message) { //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Expected O, but got Unknown //IL_0359: Unknown result type (might be due to invalid IL or missing references) //IL_035e: Unknown result type (might be due to invalid IL or missing references) //IL_0360: Unknown result type (might be due to invalid IL or missing references) //IL_0365: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Expected O, but got Unknown PeakTextChatPlugin.Logger.LogInfo((object)("[TextChatManager] SendChatMessage called: '" + message + "'")); if (string.IsNullOrWhiteSpace(message)) { return; } if (message.StartsWith("!")) { string text = message.Substring(1).Trim(); PeakTextChatPlugin.Logger.LogInfo((object)("[TextChatManager] Command detected: '" + text + "'")); if (string.IsNullOrEmpty(text)) { return; } bool flag = false; if (PhotonNetwork.IsMasterClient) { flag = true; PeakTextChatPlugin.Logger.LogInfo((object)"[TextChatManager] Player is master client."); } else { string value = PeakTextChatPlugin.AllowedSenders.Value; string userId = PhotonNetwork.LocalPlayer.UserId; PeakTextChatPlugin.Logger.LogInfo((object)("[TextChatManager] Non-host. AllowedSenders='" + value + "', UserId='" + userId + "'")); if (!string.IsNullOrEmpty(value)) { List<string> list = (from id in value.Split(',', StringSplitOptions.RemoveEmptyEntries) select id.Trim()).ToList(); if (list.Contains(userId)) { flag = true; PeakTextChatPlugin.Logger.LogInfo((object)"[TextChatManager] User found in allowed list."); } else { PeakTextChatPlugin.Logger.LogInfo((object)"[TextChatManager] User NOT in allowed list."); } } } if (flag) { string value2 = PeakTextChatPlugin.TwitchOAuth.Value; if (string.IsNullOrEmpty(value2) || !(value2 != "oauth:s1o2m3e4t5o6k7e8n9") || value2.Length < 5) { string message2 = "<color=#FF4444>[System]</color> <color=#FF8888>Invalid or missing token. Please set a valid token in the config. You cannot send messages to Twitch chat.</color>"; if ((Object)(object)TextChatDisplay.instance != (Object)null) { TextChatDisplay.instance.AddMessage(message2); } PeakTextChatPlugin.Logger.LogInfo((object)"[TextChatManager] Token invalid, message shown."); return; } TwitchIntegration.SendToTwitch(PhotonNetwork.LocalPlayer.NickName, text); string text2 = "[Twitch] " + PhotonNetwork.LocalPlayer.NickName + ": " + text; bool flag2 = false; try { Character localCharacter = Character.localCharacter; bool? obj; if (localCharacter == null) { obj = null; } else { CharacterData data = localCharacter.data; obj = ((data != null) ? new bool?(data.dead) : ((bool?)null)); } bool? flag3 = obj; flag2 = flag3 == true; } catch { } object[] array = new object[4] { PhotonNetwork.LocalPlayer.NickName, text2, PhotonNetwork.LocalPlayer.UserId, flag2 }; PhotonNetwork.RaiseEvent(chatEventCode, (object)array, new RaiseEventOptions { Receivers = (ReceiverGroup)1 }, SendOptions.SendReliable); PeakTextChatPlugin.Logger.LogInfo((object)("[TextChatManager] Duplicate message sent to game chat: '" + text2 + "'")); } else { string message3 = "<color=#FF4444>[System]</color> <color=#FF8888>You don't have permission to send to Twitch.</color>"; if ((Object)(object)TextChatDisplay.instance != (Object)null) { TextChatDisplay.instance.AddMessage(message3); } PeakTextChatPlugin.Logger.LogInfo((object)("[TextChatManager] Player " + PhotonNetwork.LocalPlayer.NickName + " has no permission to send.")); } return; } PeakTextChatPlugin.Logger.LogInfo((object)"[TextChatManager] Sending normal game chat message."); bool flag4 = false; try { Character localCharacter2 = Character.localCharacter; bool? obj3; if (localCharacter2 == null) { obj3 = null; } else { CharacterData data2 = localCharacter2.data; obj3 = ((data2 != null) ? new bool?(data2.dead) : ((bool?)null)); } bool? flag3 = obj3; flag4 = flag3 == true; } catch { } object[] array2 = new object[4] { PhotonNetwork.LocalPlayer.NickName, message, PhotonNetwork.LocalPlayer.UserId, flag4 }; PhotonNetwork.RaiseEvent(chatEventCode, (object)array2, new RaiseEventOptions { Receivers = (ReceiverGroup)1 }, SendOptions.SendReliable); } public static void CleanupObjects() { if ((Object)(object)instance != (Object)null) { Object.Destroy((Object)(object)((Component)instance).gameObject); } } } public class TwitchIntegration : MonoBehaviour { private static TwitchIntegration instance = null; private TwitchClient client; private string channelName; private bool isConnected; private static readonly Queue<Action> mainThreadActions = new Queue<Action>(); private readonly object queueLock = new object(); private void Awake() { instance = this; PeakTextChatPlugin.Logger.LogInfo((object)"[TwitchIntegration] Awake()"); } private void OnEnable() { PeakTextChatPlugin.Logger.LogInfo((object)"[TwitchIntegration] OnEnable()"); } private void Update() { lock (queueLock) { while (mainThreadActions.Count > 0) { Action action = mainThreadActions.Dequeue(); try { action?.Invoke(); } catch (Exception ex) { PeakTextChatPlugin.Logger.LogError((object)("[TwitchIntegration] UI thread error: " + ex.Message)); } } } } private void Start() { PeakTextChatPlugin.Logger.LogInfo((object)"[TwitchIntegration] Start()"); string value = PeakTextChatPlugin.TwitchUsername.Value; string value2 = PeakTextChatPlugin.TwitchOAuth.Value; channelName = value; if (string.IsNullOrEmpty(value) || value == "your_username") { ShowMessageInChat("<color=#FF4444>[System]</color> <color=#FF8888>Please set your Twitch username in the config!</color>"); PeakTextChatPlugin.Logger.LogError((object)"[TwitchIntegration] Username not set."); } else if (string.IsNullOrEmpty(channelName)) { ShowMessageInChat("<color=#FF4444>[System]</color> <color=#FF8888>Channel name is empty. Please set Username in config.</color>"); PeakTextChatPlugin.Logger.LogError((object)"[TwitchIntegration] Channel name is empty."); } else if (string.IsNullOrEmpty(value2) || !(value2 != "oauth:s1o2m3e4t5o6k7e8n9") || value2.Length < 5) { ShowMessageInChat("<color=#FF4444>[System]</color> <color=#FF8888>No valid OAuth token. Read-only mode (anonymous). To send messages, set a token in the config.</color>"); PeakTextChatPlugin.Logger.LogInfo((object)"[TwitchIntegration] No valid token, falling back to anonymous."); ((MonoBehaviour)this).StartCoroutine(ConnectAnonymous(value, channelName)); } else { PeakTextChatPlugin.Logger.LogInfo((object)"[TwitchIntegration] Token is valid, attempting connection..."); ((MonoBehaviour)this).StartCoroutine(ConnectAndWait(value, value2, channelName, 10f)); } } private void ShowMessageInChat(string message) { if ((Object)(object)TextChatDisplay.instance != (Object)null) { TextChatDisplay.instance.AddMessage(message); } else { ((MonoBehaviour)this).StartCoroutine(WaitForChatAndShow(message)); } } private IEnumerator WaitForChatAndShow(string message) { float timeout = 5f; float elapsed = 0f; while ((Object)(object)TextChatDisplay.instance == (Object)null && elapsed < timeout) { yield return (object)new WaitForSeconds(0.1f); elapsed += 0.1f; } if ((Object)(object)TextChatDisplay.instance != (Object)null) { TextChatDisplay.instance.AddMessage(message); } else { PeakTextChatPlugin.Logger.LogWarning((object)("[TwitchIntegration] Chat not available, message not shown: " + message)); } } private IEnumerator ConnectAnonymous(string username, string channel) { string text = "justinfan12345"; string oauth = ""; PeakTextChatPlugin.Logger.LogInfo((object)("[TwitchIntegration] Trying anonymous connection with nick " + text)); yield return ((MonoBehaviour)this).StartCoroutine(ConnectAndWait(text, oauth, channel, 10f)); if (isConnected) { PeakTextChatPlugin.Logger.LogInfo((object)"[TwitchIntegration] Anonymous connection successful! Chat reading."); ShowMessageInChat("<color=#00FF00>[Twitch] Anonymous mode (read-only)</color>"); } else { PeakTextChatPlugin.Logger.LogError((object)"[TwitchIntegration] Anonymous connection failed. Please provide OAuth token."); ShowMessageInChat("<color=#FF4444>[System]</color> <color=#FF8888>Anonymous connection failed. Please provide OAuth token.</color>"); } } private IEnumerator ConnectAndWait(string username, string oauth, string channel, float timeout) { PeakTextChatPlugin.Logger.LogInfo((object)$"[TwitchIntegration] ConnectAndWait started. username={username}, channel={channel}, timeout={timeout}"); isConnected = false; TwitchClient tempClient = null; try { ConnectionCredentials val = new ConnectionCredentials(username, oauth, "wss://irc-ws.chat.twitch.tv:443", false, (Capabilities)null); ClientOptions val2 = new ClientOptions { MessagesAllowedInPeriod = 20, ThrottlingPeriod = TimeSpan.FromSeconds(30.0) }; WebSocketClient val3 = new WebSocketClient((IClientOptions)(object)val2); tempClient = new TwitchClient((IClient)(object)val3, (ClientProtocol)1, (ILogger<TwitchClient>)null); tempClient.OnConnected += delegate(object s, OnConnectedArgs e) { PeakTextChatPlugin.Logger.LogInfo((object)("[TwitchIntegration] OnConnected: Connected to Twitch! Channel: " + e.AutoJoinChannel)); isConnected = true; }; tempClient.OnJoinedChannel += delegate(object s, OnJoinedChannelArgs e) { PeakTextChatPlugin.Logger.LogInfo((object)("[TwitchIntegration] OnJoinedChannel: Joined channel " + e.Channel)); }; tempClient.OnMessageReceived += OnMessageReceived; tempClient.OnError += OnError; tempClient.Initialize(val, channel, '!', '!', true); tempClient.Connect(); } catch (Exception ex) { PeakTextChatPlugin.Logger.LogError((object)("[TwitchIntegration] Initialization error: " + ex.Message)); TwitchClient obj = tempClient; if (obj != null) { obj.Disconnect(); } yield break; } float elapsed = 0f; while (!isConnected && elapsed < timeout) { yield return (object)new WaitForSeconds(0.1f); elapsed += 0.1f; } if (isConnected) { client = tempClient; PeakTextChatPlugin.Logger.LogInfo((object)$"[TwitchIntegration] Connection established in {elapsed:F1} sec."); ShowMessageInChat("<color=#00FF00>[Twitch] Connected to Twitch!</color>"); yield break; } PeakTextChatPlugin.Logger.LogWarning((object)$"[TwitchIntegration] Timeout {timeout} sec. Failed to connect."); TwitchClient obj2 = tempClient; if (obj2 != null) { obj2.Disconnect(); } ShowMessageInChat("<color=#FF4444>[System]</color> <color=#FF8888>Failed to connect to Twitch. Check your token and internet.</color>"); } private void OnMessageReceived(object sender, OnMessageReceivedArgs e) { string displayName = ((TwitchLibMessage)e.ChatMessage).DisplayName; string message = e.ChatMessage.Message; string colorHex = ((TwitchLibMessage)e.ChatMessage).ColorHex ?? "#FFFFFF"; PeakTextChatPlugin.Logger.LogInfo((object)("[TwitchIntegration] " + displayName + ": " + message)); lock (queueLock) { mainThreadActions.Enqueue(delegate { try { string message2 = "<color=#9147FF>[Twitch]</color> <color=" + colorHex + ">" + displayName + "</color>: " + message; if ((Object)(object)TextChatDisplay.instance != (Object)null) { TextChatDisplay.instance.AddMessage(message2); } else { PeakTextChatPlugin.Logger.LogWarning((object)"[TwitchIntegration] TextChatDisplay missing"); } } catch (Exception ex) { PeakTextChatPlugin.Logger.LogError((object)("[TwitchIntegration] Error adding message: " + ex.Message)); } }); } } private void OnError(object sender, EventArgs e) { try { PropertyInfo property = e.GetType().GetProperty("Exception"); if (property != null) { if (property.GetValue(e) is Exception ex) { PeakTextChatPlugin.Logger.LogError((object)("[TwitchIntegration] TwitchLib error: " + ex.Message)); } else { PeakTextChatPlugin.Logger.LogError((object)"[TwitchIntegration] Error, but Exception is null."); } } else { PeakTextChatPlugin.Logger.LogError((object)("[TwitchIntegration] Unknown error. Type: " + e.GetType().Name)); } } catch (Exception ex2) { PeakTextChatPlugin.Logger.LogError((object)("[TwitchIntegration] Error in OnError handler: " + ex2.Message)); } } public static void SendToTwitch(string playerName, string message) { if ((Object)(object)instance == (Object)null) { PeakTextChatPlugin.Logger.LogWarning((object)"[TwitchIntegration] Instance not created!"); } else { instance.SendMessageToTwitch("[" + playerName + "]: " + message); } } public void SendMessageToTwitch(string message) { ManualLogSource logger = PeakTextChatPlugin.Logger; object arg = client != null; TwitchClient obj = client; logger.LogInfo((object)$"[TwitchIntegration] SendMessageToTwitch called. client={arg}, IsConnected={obj != null && obj.IsConnected}, channelName={channelName}"); if (client != null && client.IsConnected && !string.IsNullOrEmpty(channelName)) { if (PeakTextChatPlugin.TwitchOAuth.Value == "oauth:s1o2m3e4t5o6k7e8n9" || string.IsNullOrEmpty(PeakTextChatPlugin.TwitchOAuth.Value)) { PeakTextChatPlugin.Logger.LogWarning((object)"[TwitchIntegration] No rights to send (anonymous mode)"); return; } client.SendMessage(channelName, message, false); PeakTextChatPlugin.Logger.LogInfo((object)("[TwitchIntegration] Sent to Twitch: " + message)); } else { PeakTextChatPlugin.Logger.LogWarning((object)"[TwitchIntegration] Client not ready to send"); } } private void OnDestroy() { PeakTextChatPlugin.Logger.LogInfo((object)"[TwitchIntegration] OnDestroy()"); try { TwitchClient obj = client; if (obj != null) { obj.Disconnect(); } } catch (Exception ex) { PeakTextChatPlugin.Logger.LogError((object)("[TwitchIntegration] Disconnect error: " + ex.Message)); } } } public static class KeysHelper { public class KeyCodeInfo { public KeyCodeShort shortKey; public KeyCode key; public string keyText; public KeyCodeInfo(KeyCodeShort shortKey, KeyCode key, string keyText) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) this.shortKey = shortKey; this.key = key; this.keyText = keyText; } } public static List<KeyCodeInfo> infos = new List<KeyCodeInfo> { new KeyCodeInfo(KeyCodeShort.A, (KeyCode)97, "A"), new KeyCodeInfo(KeyCodeShort.B, (KeyCode)98, "B"), new KeyCodeInfo(KeyCodeShort.C, (KeyCode)99, "C"), new KeyCodeInfo(KeyCodeShort.D, (KeyCode)100, "D"), new KeyCodeInfo(KeyCodeShort.E, (KeyCode)101, "E"), new KeyCodeInfo(KeyCodeShort.F, (KeyCode)102, "F"), new KeyCodeInfo(KeyCodeShort.G, (KeyCode)103, "G"), new KeyCodeInfo(KeyCodeShort.H, (KeyCode)104, "H"), new KeyCodeInfo(KeyCodeShort.I, (KeyCode)105, "I"), new KeyCodeInfo(KeyCodeShort.J, (KeyCode)106, "J"), new KeyCodeInfo(KeyCodeShort.K, (KeyCode)107, "K"), new KeyCodeInfo(KeyCodeShort.L, (KeyCode)108, "L"), new KeyCodeInfo(KeyCodeShort.M, (KeyCode)109, "M"), new KeyCodeInfo(KeyCodeShort.N, (KeyCode)110, "N"), new KeyCodeInfo(KeyCodeShort.O, (KeyCode)111, "O"), new KeyCodeInfo(KeyCodeShort.P, (KeyCode)112, "P"), new KeyCodeInfo(KeyCodeShort.Q, (KeyCode)113, "Q"), new KeyCodeInfo(KeyCodeShort.R, (KeyCode)114, "R"), new KeyCodeInfo(KeyCodeShort.S, (KeyCode)115, "S"), new KeyCodeInfo(KeyCodeShort.T, (KeyCode)116, "T"), new KeyCodeInfo(KeyCodeShort.U, (KeyCode)117, "U"), new KeyCodeInfo(KeyCodeShort.V, (KeyCode)118, "V"), new KeyCodeInfo(KeyCodeShort.W, (KeyCode)119, "W"), new KeyCodeInfo(KeyCodeShort.X, (KeyCode)120, "X"), new KeyCodeInfo(KeyCodeShort.Y, (KeyCode)121, "Y"), new KeyCodeInfo(KeyCodeShort.Z, (KeyCode)122, "Z"), new KeyCodeInfo(KeyCodeShort.One, (KeyCode)49, "1"), new KeyCodeInfo(KeyCodeShort.Two, (KeyCode)50, "2"), new KeyCodeInfo(KeyCodeShort.Three, (KeyCode)51, "3"), new KeyCodeInfo(KeyCodeShort.Four, (KeyCode)52, "4"), new KeyCodeInfo(KeyCodeShort.Five, (KeyCode)53, "5"), new KeyCodeInfo(KeyCodeShort.Six, (KeyCode)54, "6"), new KeyCodeInfo(KeyCodeShort.Seven, (KeyCode)55, "7"), new KeyCodeInfo(KeyCodeShort.Eight, (KeyCode)56, "8"), new KeyCodeInfo(KeyCodeShort.Nine, (KeyCode)57, "9"), new KeyCodeInfo(KeyCodeShort.Zero, (KeyCode)48, "0"), new KeyCodeInfo(KeyCodeShort.Minus, (KeyCode)45, "-"), new KeyCodeInfo(KeyCodeShort.Equals, (KeyCode)61, "="), new KeyCodeInfo(KeyCodeShort.Tab, (KeyCode)9, "Tab"), new KeyCodeInfo(KeyCodeShort.LeftBracket, (KeyCode)91, "["), new KeyCodeInfo(KeyCodeShort.RightBracket, (KeyCode)93, "]"), new KeyCodeInfo(KeyCodeShort.Semicolon, (KeyCode)59, ";"), new KeyCodeInfo(KeyCodeShort.Quote, (KeyCode)39, "'"), new KeyCodeInfo(KeyCodeShort.Backslash, (KeyCode)92, "\\"), new KeyCodeInfo(KeyCodeShort.Comma, (KeyCode)44, ","), new KeyCodeInfo(KeyCodeShort.Period, (KeyCode)46, "."), new KeyCodeInfo(KeyCodeShort.Slash, (KeyCode)47, "/"), new KeyCodeInfo(KeyCodeShort.Enter, (KeyCode)13, "Enter"), new KeyCodeInfo(KeyCodeShort.Numpad0, (KeyCode)256, "Num0"), new KeyCodeInfo(KeyCodeShort.Numpad1, (KeyCode)257, "Num1"), new KeyCodeInfo(KeyCodeShort.Numpad2, (KeyCode)258, "Num2"), new KeyCodeInfo(KeyCodeShort.Numpad3, (KeyCode)259, "Num3"), new KeyCodeInfo(KeyCodeShort.Numpad4, (KeyCode)260, "Num4"), new KeyCodeInfo(KeyCodeShort.Numpad5, (KeyCode)261, "Num5"), new KeyCodeInfo(KeyCodeShort.Numpad6, (KeyCode)262, "Num6"), new KeyCodeInfo(KeyCodeShort.Numpad7, (KeyCode)263, "Num7"), new KeyCodeInfo(KeyCodeShort.Numpad8, (KeyCode)264, "Num8"), new KeyCodeInfo(KeyCodeShort.Numpad9, (KeyCode)265, "Num9"), new KeyCodeInfo(KeyCodeShort.NumpadDivide, (KeyCode)267, "Num /"), new KeyCodeInfo(KeyCodeShort.NumpadMultiply, (KeyCode)268, "Num *"), new KeyCodeInfo(KeyCodeShort.NumpadMinus, (KeyCode)269, "Num -"), new KeyCodeInfo(KeyCodeShort.NumpadPlus, (KeyCode)270, "Num +"), new KeyCodeInfo(KeyCodeShort.NumpadEnter, (KeyCode)271, "Num Enter"), new KeyCodeInfo(KeyCodeShort.NumpadPeriod, (KeyCode)266, "Num .") }; public static KeyCodeInfo GetKeyCodeShortInfo(KeyCodeShort key) { return infos.Find((KeyCodeInfo i) => i.shortKey == key); } } public enum KeyCodeShort { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero, Tab, Minus, Equals, LeftBracket, RightBracket, Semicolon, Quote, Backslash, Comma, Period, Slash, Enter, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, NumpadDivide, NumpadMultiply, NumpadMinus, NumpadPlus, NumpadEnter, NumpadPeriod } public static class ProceduralImageExtensions { public static T SetModifierType<T>(this ProceduralImage image) where T : ProceduralImageModifier { image.ModifierType = typeof(T); return ((Component)image).gameObject.GetComponent<T>() ?? ((Component)image).gameObject.AddComponent<T>(); } } public static class GameUtilsPatch { [HarmonyPatch(typeof(GameUtils), "Awake")] [HarmonyPostfix] public static void AwakePatch(GameUtils __instance) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown GameObject val = new GameObject("TextChatManager"); val.transform.SetParent(((Component)__instance).transform, false); val.AddComponent<TextChatManager>(); } } [HarmonyPatch(typeof(StaminaBar), "Start")] public static class StaminaBarPatch { public static BarGroupChildWatcher barGroupChildWatcher; [HarmonyPostfix] public static void Postfix(StaminaBar __instance) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_002b: 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_005e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)GUIManager.instance != (Object)null) { GameObject val = new GameObject("TextChatPos"); RectTransform val2 = (RectTransform)((Component)__instance).transform.parent; val2.offsetMax = new Vector2(val2.offsetMax.x, 1000f); val.transform.SetParent((Transform)(object)val2); RectTransform val3 = val.AddComponent<RectTransform>(); ((Transform)val3).SetAsFirstSibling(); val3.sizeDelta = Vector2.zero; barGroupChildWatcher = ((Component)val2).gameObject.AddComponent<BarGroupChildWatcher>(); barGroupChildWatcher.textChatDummyTransform = val.transform; } } public static void CleanupObjects() { Object.Destroy((Object)(object)barGroupChildWatcher.textChatDummyTransform); Object.Destroy((Object)(object)barGroupChildWatcher); } } public static class GUIManagerPatch { public static Canvas textChatCanvas = null; public static TMP_FontAsset darumaDropOneFont = null; private static bool isHUDActive = true; [HarmonyPatch(typeof(GUIManager), "Start")] [HarmonyPostfix] public static void StartPostfix(GUIManager __instance) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown Transform transform = ((Component)__instance).transform; GameObject val = new GameObject("TextChatCanvas"); val.transform.SetParent(transform, false); textChatCanvas = val.AddComponent<Canvas>(); textChatCanvas.renderMode = (RenderMode)1; CanvasScaler val2 = ((Component)textChatCanvas).gameObject.GetComponent<CanvasScaler>() ?? ((Component)textChatCanvas).gameObject.AddComponent<CanvasScaler>(); val2.referencePixelsPerUnit = 100f; val2.matchWidthOrHeight = 1f; val2.referenceResolution = new Vector2(1920f, 1080f); val2.scaleFactor = 1f; val2.screenMatchMode = (ScreenMatchMode)0; val2.uiScaleMode = (ScaleMode)1; GameObject val3 = new GameObject("TextChat"); val3.transform.SetParent(((Component)textChatCanvas).transform, false); val3.AddComponent<TextChatDisplay>(); try { GUIManager instance = GUIManager.instance; object obj; if (instance == null) { obj = null; } else { TextMeshProUGUI itemPromptDrop = instance.itemPromptDrop; obj = ((itemPromptDrop != null) ? ((TMP_Text)itemPromptDrop).font : null); } darumaDropOneFont = (TMP_FontAsset)obj; } catch { } } [HarmonyPatch(typeof(GUIManager), "LateUpdate")] [HarmonyPostfix] public static void LateUpdatePostfix(GUIManager __instance) { try { if (isHUDActive != ((Component)__instance.hudCanvas).gameObject.activeInHierarchy) { isHUDActive = ((Component)__instance.hudCanvas).gameObject.activeInHierarchy; ((Component)textChatCanvas).gameObject.SetActive(isHUDActive); } } catch { PeakTextChatPlugin.Logger.LogError((object)"guimanager late update patch failed!! rhwrhrhwhrhwrhwhrawhhrhwhrwhrhrwrh"); } } } public static class InputBlockingPatches { private static MethodInfo windowBlockingInput; [HarmonyPatch(typeof(GUIManager), "UpdateWindowStatus")] [HarmonyPostfix] public static void UpdateWindowStatusPatch() { try { if (windowBlockingInput == null) { windowBlockingInput = AccessTools.PropertySetter(typeof(GUIManager), "windowBlockingInput"); } TextChatDisplay instance = TextChatDisplay.instance; if (instance != null && instance.isBlockingInput) { windowBlockingInput?.Invoke(GUIManager.instance, new object[1] { true }); } } catch { } } [HarmonyPatch(typeof(CinemaCamera), "Update")] [HarmonyPrefix] public static bool UpdateCinemaCamPatch(CinemaCamera __instance) { if (IsInputBlocked() && !__instance.on) { return false; } return true; } [HarmonyPatch(typeof(Character), "UpdateVariablesFixed")] [HarmonyPrefix] public static bool UpdateCharacterVariablesPatch(Character __instance) { try { if (IsInputBlocked()) { __instance.input.interactIsPressed = false; } } catch { PeakTextChatPlugin.Logger.LogError((object)"update character variables patch failed!! YIPPEEEE"); } return true; } public static bool IsInputBlocked() { try { GUIManager instance = GUIManager.instance; return instance != null && instance.windowBlockingInput; } catch { PeakTextChatPlugin.Logger.LogError((object)"window blocking input check failed!! YAY"); } return false; } } [BepInPlugin("V8.TwitchChat", "TwitchChat", "1.1.1")] public class PeakTextChatPlugin : BaseUnityPlugin { public enum TextChatPosition { BottomLeft, TopLeft, TopRight } internal static ManualLogSource Logger; private Harmony harmony; public static ConfigEntry<float> configFontSize; public static ConfigEntry<string> configChatSize; public static ConfigEntry<float> configMessageFadeDelay; public static ConfigEntry<float> configFadeDelay; public static ConfigEntry<float> configHideDelay; public static ConfigEntry<KeyCodeShort> configKey; public static ConfigEntry<TextChatPosition> configPos; public static ConfigEntry<bool> configRichTextEnabled; public static ConfigEntry<bool> configIMGUI; public static ConfigEntry<float> configBgOpacity; public static ConfigEntry<bool> configFrameVisible; public static ConfigEntry<string> TwitchUsername; public static ConfigEntry<string> TwitchOAuth; public static ConfigEntry<string> AllowedSenders; private void Awake() { //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Expected O, but got Unknown Logger = ((BaseUnityPlugin)this).Logger; Logger.LogInfo((object)"PeakTextChat is loaded!"); configKey = ((BaseUnityPlugin)this).Config.Bind<KeyCodeShort>("Display", "ChatKey", KeyCodeShort.Slash, "The key that activates typing in chat"); configIMGUI = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "UseIMGUI", false, "Use IMGUI for the text field"); configPos = ((BaseUnityPlugin)this).Config.Bind<TextChatPosition>("Display", "ChatPosition", TextChatPosition.BottomLeft, "The position of the text chat"); configChatSize = ((BaseUnityPlugin)this).Config.Bind<string>("Display", "ChatSize", "500:300", "The size of the text chat (formatted X:Y)"); configFontSize = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "ChatFontSize", 20f, "Size of the chat's text"); configBgOpacity = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "ChatBackgroundOpacity", 0.3f, "Opacity of the chat's background/shadow"); configFrameVisible = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ChatFrameVisible", true, "Whether the frame of the chat box is visible"); configRichTextEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ChatRichText", true, "Whether rich text tags get parsed in messages"); configFadeDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "ChatFadeDelay", 15f, "How long before the chat fades out"); configHideDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "ChatHideDelay", 40f, "How long before the chat hides completely"); configMessageFadeDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "ChatMessageHideDelay", 40f, "How long before a chat message disappears"); TwitchUsername = ((BaseUnityPlugin)this).Config.Bind<string>("Twitch", "Username", "your_username", "Twitch username (without #)"); TwitchOAuth = ((BaseUnityPlugin)this).Config.Bind<string>("Twitch", "OAuthToken", "oauth:s1o2m3e4t5o6k7e8n9", "OAuth token (get it at twitchtokengenerator.com)"); AllowedSenders = ((BaseUnityPlugin)this).Config.Bind<string>("Twitch", "AllowedSenders", "", "List of Steam IDs (comma separated) allowed to send to Twitch. If empty, only host can send."); TwitchIntegration twitchIntegration = ((Component)this).gameObject.AddComponent<TwitchIntegration>(); if ((Object)(object)twitchIntegration != (Object)null) { Logger.LogInfo((object)"[PeakTextChatPlugin] TwitchIntegration component successfully added!"); } else { Logger.LogError((object)"[PeakTextChatPlugin] Failed to add TwitchIntegration!"); } harmony = new Harmony("com.borealityy.peaktextchat"); harmony.PatchAll(typeof(GameUtilsPatch)); harmony.PatchAll(typeof(StaminaBarPatch)); harmony.PatchAll(typeof(GUIManagerPatch)); harmony.PatchAll(typeof(InputBlockingPatches)); } private void OnDestroy() { if ((Object)(object)TextChatDisplay.instance != (Object)null) { Object.Destroy((Object)(object)((Component)TextChatDisplay.instance).gameObject); } if ((Object)(object)GUIManagerPatch.textChatCanvas != (Object)null) { Object.Destroy((Object)(object)GUIManagerPatch.textChatCanvas); } TextChatManager.CleanupObjects(); StaminaBarPatch.CleanupObjects(); harmony.UnpatchSelf(); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "V8.TwitchChat"; public const string PLUGIN_NAME = "TwitchChat"; public const string PLUGIN_VERSION = "1.1.1"; } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ConstantExpectedAttribute : Attribute { public object? Min { get; set; } public object? Max { get; set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ExperimentalAttribute : Attribute { public string DiagnosticId { get; } public string? UrlFormat { get; set; } public ExperimentalAttribute(string diagnosticId) { DiagnosticId = diagnosticId; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] 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)] [ExcludeFromCodeCoverage] 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; } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class SetsRequiredMembersAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object?[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = new object[0]; } public StringSyntaxAttribute(string syntax, params object?[] arguments) { Syntax = syntax; Arguments = arguments; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class UnscopedRefAttribute : Attribute { } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class RequiresPreviewFeaturesAttribute : Attribute { public string? Message { get; } public string? Url { get; set; } public RequiresPreviewFeaturesAttribute() { } public RequiresPreviewFeaturesAttribute(string? message) { Message = message; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CollectionBuilderAttribute : Attribute { public Type BuilderType { get; } public string MethodName { get; } public CollectionBuilderAttribute(Type builderType, string methodName) { BuilderType = builderType; MethodName = methodName; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CompilerFeatureRequiredAttribute : Attribute { public const string RefStructs = "RefStructs"; public const string RequiredMembers = "RequiredMembers"; public string FeatureName { get; } public bool IsOptional { get; set; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute { public string[] Arguments { get; } public InterpolatedStringHandlerArgumentAttribute(string argument) { Arguments = new string[1] { argument }; } public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) { Arguments = arguments; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class InterpolatedStringHandlerAttribute : Attribute { } [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ModuleInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class OverloadResolutionPriorityAttribute : Attribute { public int Priority { get; } public OverloadResolutionPriorityAttribute(int priority) { Priority = priority; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] [ExcludeFromCodeCoverage] internal sealed class ParamCollectionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] internal sealed class RequiresLocationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class SkipLocalsInitAttribute : Attribute { } }