Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of RiskOfRumble v1.1.0
plugins/System.Numerics.Vectors.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Diagnostics; using System.Globalization; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using FxResources.System.Numerics.Vectors; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Numerics.Vectors")] [assembly: AssemblyDescription("System.Numerics.Vectors")] [assembly: AssemblyDefaultAlias("System.Numerics.Vectors")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.26515.06")] [assembly: AssemblyInformationalVersion("4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.1.4.0")] [module: UnverifiableCode] namespace FxResources.System.Numerics.Vectors { internal static class SR { } } namespace System { internal static class MathF { public const float PI = 3.1415927f; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(float x) { return Math.Abs(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Acos(float x) { return (float)Math.Acos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cos(float x) { return (float)Math.Cos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float IEEERemainder(float x, float y) { return (float)Math.IEEERemainder(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Pow(float x, float y) { return (float)Math.Pow(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sin(float x) { return (float)Math.Sin(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sqrt(float x) { return (float)Math.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Tan(float x) { return (float)Math.Tan(x); } } internal static class SR { private static ResourceManager s_resourceManager; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static Type ResourceType { get; } = typeof(SR); internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException", null); internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination", null); internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef", null); internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported", null); internal static string Arg_InsufficientNumberOfElements => GetResourceString("Arg_InsufficientNumberOfElements", null); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, Inherited = false)] internal sealed class IntrinsicAttribute : Attribute { } [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } namespace System.Numerics { internal class ConstantHelper { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte GetByteWithAllBitsSet() { byte result = 0; result = byte.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static sbyte GetSByteWithAllBitsSet() { sbyte result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort GetUInt16WithAllBitsSet() { ushort result = 0; result = ushort.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short GetInt16WithAllBitsSet() { short result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint GetUInt32WithAllBitsSet() { uint result = 0u; result = uint.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetInt32WithAllBitsSet() { int result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong GetUInt64WithAllBitsSet() { ulong result = 0uL; result = ulong.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long GetInt64WithAllBitsSet() { long result = 0L; result = -1L; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static float GetSingleWithAllBitsSet() { float result = 0f; *(int*)(&result) = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static double GetDoubleWithAllBitsSet() { double result = 0.0; *(long*)(&result) = -1L; return result; } } [StructLayout(LayoutKind.Explicit)] internal struct Register { [FieldOffset(0)] internal byte byte_0; [FieldOffset(1)] internal byte byte_1; [FieldOffset(2)] internal byte byte_2; [FieldOffset(3)] internal byte byte_3; [FieldOffset(4)] internal byte byte_4; [FieldOffset(5)] internal byte byte_5; [FieldOffset(6)] internal byte byte_6; [FieldOffset(7)] internal byte byte_7; [FieldOffset(8)] internal byte byte_8; [FieldOffset(9)] internal byte byte_9; [FieldOffset(10)] internal byte byte_10; [FieldOffset(11)] internal byte byte_11; [FieldOffset(12)] internal byte byte_12; [FieldOffset(13)] internal byte byte_13; [FieldOffset(14)] internal byte byte_14; [FieldOffset(15)] internal byte byte_15; [FieldOffset(0)] internal sbyte sbyte_0; [FieldOffset(1)] internal sbyte sbyte_1; [FieldOffset(2)] internal sbyte sbyte_2; [FieldOffset(3)] internal sbyte sbyte_3; [FieldOffset(4)] internal sbyte sbyte_4; [FieldOffset(5)] internal sbyte sbyte_5; [FieldOffset(6)] internal sbyte sbyte_6; [FieldOffset(7)] internal sbyte sbyte_7; [FieldOffset(8)] internal sbyte sbyte_8; [FieldOffset(9)] internal sbyte sbyte_9; [FieldOffset(10)] internal sbyte sbyte_10; [FieldOffset(11)] internal sbyte sbyte_11; [FieldOffset(12)] internal sbyte sbyte_12; [FieldOffset(13)] internal sbyte sbyte_13; [FieldOffset(14)] internal sbyte sbyte_14; [FieldOffset(15)] internal sbyte sbyte_15; [FieldOffset(0)] internal ushort uint16_0; [FieldOffset(2)] internal ushort uint16_1; [FieldOffset(4)] internal ushort uint16_2; [FieldOffset(6)] internal ushort uint16_3; [FieldOffset(8)] internal ushort uint16_4; [FieldOffset(10)] internal ushort uint16_5; [FieldOffset(12)] internal ushort uint16_6; [FieldOffset(14)] internal ushort uint16_7; [FieldOffset(0)] internal short int16_0; [FieldOffset(2)] internal short int16_1; [FieldOffset(4)] internal short int16_2; [FieldOffset(6)] internal short int16_3; [FieldOffset(8)] internal short int16_4; [FieldOffset(10)] internal short int16_5; [FieldOffset(12)] internal short int16_6; [FieldOffset(14)] internal short int16_7; [FieldOffset(0)] internal uint uint32_0; [FieldOffset(4)] internal uint uint32_1; [FieldOffset(8)] internal uint uint32_2; [FieldOffset(12)] internal uint uint32_3; [FieldOffset(0)] internal int int32_0; [FieldOffset(4)] internal int int32_1; [FieldOffset(8)] internal int int32_2; [FieldOffset(12)] internal int int32_3; [FieldOffset(0)] internal ulong uint64_0; [FieldOffset(8)] internal ulong uint64_1; [FieldOffset(0)] internal long int64_0; [FieldOffset(8)] internal long int64_1; [FieldOffset(0)] internal float single_0; [FieldOffset(4)] internal float single_1; [FieldOffset(8)] internal float single_2; [FieldOffset(12)] internal float single_3; [FieldOffset(0)] internal double double_0; [FieldOffset(8)] internal double double_1; } [System.Runtime.CompilerServices.Intrinsic] public struct Vector<T> : IEquatable<Vector<T>>, IFormattable where T : struct { private struct VectorSizeHelper { internal Vector<T> _placeholder; internal byte _byte; } private System.Numerics.Register register; private static readonly int s_count = InitializeCount(); private static readonly Vector<T> s_zero = default(Vector<T>); private static readonly Vector<T> s_one = new Vector<T>(GetOneValue()); private static readonly Vector<T> s_allOnes = new Vector<T>(GetAllBitsSetValue()); public static int Count { [System.Runtime.CompilerServices.Intrinsic] get { return s_count; } } public static Vector<T> Zero { [System.Runtime.CompilerServices.Intrinsic] get { return s_zero; } } public static Vector<T> One { [System.Runtime.CompilerServices.Intrinsic] get { return s_one; } } internal static Vector<T> AllOnes => s_allOnes; public unsafe T this[int index] { [System.Runtime.CompilerServices.Intrinsic] get { if (index >= Count || index < 0) { throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, index)); } if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { return (T)(object)ptr[index]; } } if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { return (T)(object)ptr2[index]; } } if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { return (T)(object)ptr3[index]; } } if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { return (T)(object)ptr4[index]; } } if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { return (T)(object)ptr5[index]; } } if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { return (T)(object)ptr6[index]; } } if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { return (T)(object)ptr7[index]; } } if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { return (T)(object)ptr8[index]; } } if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { return (T)(object)ptr9[index]; } } if (typeof(T) == typeof(double)) { fixed (double* ptr10 = ®ister.double_0) { return (T)(object)ptr10[index]; } } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } } private unsafe static int InitializeCount() { VectorSizeHelper vectorSizeHelper = default(VectorSizeHelper); byte* ptr = &vectorSizeHelper._placeholder.register.byte_0; byte* ptr2 = &vectorSizeHelper._byte; int num = (int)(ptr2 - ptr); int num2 = -1; if (typeof(T) == typeof(byte)) { num2 = 1; } else if (typeof(T) == typeof(sbyte)) { num2 = 1; } else if (typeof(T) == typeof(ushort)) { num2 = 2; } else if (typeof(T) == typeof(short)) { num2 = 2; } else if (typeof(T) == typeof(uint)) { num2 = 4; } else if (typeof(T) == typeof(int)) { num2 = 4; } else if (typeof(T) == typeof(ulong)) { num2 = 8; } else if (typeof(T) == typeof(long)) { num2 = 8; } else if (typeof(T) == typeof(float)) { num2 = 4; } else { if (!(typeof(T) == typeof(double))) { throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } num2 = 8; } return num / num2; } [System.Runtime.CompilerServices.Intrinsic] public unsafe Vector(T value) { this = default(Vector<T>); if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)value; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)value; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)value; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)value; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)value; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)value; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)value; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)value; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)value; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)value; } } } } else if (typeof(T) == typeof(byte)) { register.byte_0 = (byte)(object)value; register.byte_1 = (byte)(object)value; register.byte_2 = (byte)(object)value; register.byte_3 = (byte)(object)value; register.byte_4 = (byte)(object)value; register.byte_5 = (byte)(object)value; register.byte_6 = (byte)(object)value; register.byte_7 = (byte)(object)value; register.byte_8 = (byte)(object)value; register.byte_9 = (byte)(object)value; register.byte_10 = (byte)(object)value; register.byte_11 = (byte)(object)value; register.byte_12 = (byte)(object)value; register.byte_13 = (byte)(object)value; register.byte_14 = (byte)(object)value; register.byte_15 = (byte)(object)value; } else if (typeof(T) == typeof(sbyte)) { register.sbyte_0 = (sbyte)(object)value; register.sbyte_1 = (sbyte)(object)value; register.sbyte_2 = (sbyte)(object)value; register.sbyte_3 = (sbyte)(object)value; register.sbyte_4 = (sbyte)(object)value; register.sbyte_5 = (sbyte)(object)value; register.sbyte_6 = (sbyte)(object)value; register.sbyte_7 = (sbyte)(object)value; register.sbyte_8 = (sbyte)(object)value; register.sbyte_9 = (sbyte)(object)value; register.sbyte_10 = (sbyte)(object)value; register.sbyte_11 = (sbyte)(object)value; register.sbyte_12 = (sbyte)(object)value; register.sbyte_13 = (sbyte)(object)value; register.sbyte_14 = (sbyte)(object)value; register.sbyte_15 = (sbyte)(object)value; } else if (typeof(T) == typeof(ushort)) { register.uint16_0 = (ushort)(object)value; register.uint16_1 = (ushort)(object)value; register.uint16_2 = (ushort)(object)value; register.uint16_3 = (ushort)(object)value; register.uint16_4 = (ushort)(object)value; register.uint16_5 = (ushort)(object)value; register.uint16_6 = (ushort)(object)value; register.uint16_7 = (ushort)(object)value; } else if (typeof(T) == typeof(short)) { register.int16_0 = (short)(object)value; register.int16_1 = (short)(object)value; register.int16_2 = (short)(object)value; register.int16_3 = (short)(object)value; register.int16_4 = (short)(object)value; register.int16_5 = (short)(object)value; register.int16_6 = (short)(object)value; register.int16_7 = (short)(object)value; } else if (typeof(T) == typeof(uint)) { register.uint32_0 = (uint)(object)value; register.uint32_1 = (uint)(object)value; register.uint32_2 = (uint)(object)value; register.uint32_3 = (uint)(object)value; } else if (typeof(T) == typeof(int)) { register.int32_0 = (int)(object)value; register.int32_1 = (int)(object)value; register.int32_2 = (int)(object)value; register.int32_3 = (int)(object)value; } else if (typeof(T) == typeof(ulong)) { register.uint64_0 = (ulong)(object)value; register.uint64_1 = (ulong)(object)value; } else if (typeof(T) == typeof(long)) { register.int64_0 = (long)(object)value; register.int64_1 = (long)(object)value; } else if (typeof(T) == typeof(float)) { register.single_0 = (float)(object)value; register.single_1 = (float)(object)value; register.single_2 = (float)(object)value; register.single_3 = (float)(object)value; } else if (typeof(T) == typeof(double)) { register.double_0 = (double)(object)value; register.double_1 = (double)(object)value; } } [System.Runtime.CompilerServices.Intrinsic] public Vector(T[] values) : this(values, 0) { } public unsafe Vector(T[] values, int index) { this = default(Vector<T>); if (values == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (index < 0 || values.Length - index < Count) { throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_InsufficientNumberOfElements, Count, "values")); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)values[i + index]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)values[j + index]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)values[k + index]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)values[l + index]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)values[m + index]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)values[n + index]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)values[num + index]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)values[num2 + index]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)values[num3 + index]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)values[num4 + index]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = ®ister.byte_0) { *ptr11 = (byte)(object)values[index]; ptr11[1] = (byte)(object)values[1 + index]; ptr11[2] = (byte)(object)values[2 + index]; ptr11[3] = (byte)(object)values[3 + index]; ptr11[4] = (byte)(object)values[4 + index]; ptr11[5] = (byte)(object)values[5 + index]; ptr11[6] = (byte)(object)values[6 + index]; ptr11[7] = (byte)(object)values[7 + index]; ptr11[8] = (byte)(object)values[8 + index]; ptr11[9] = (byte)(object)values[9 + index]; ptr11[10] = (byte)(object)values[10 + index]; ptr11[11] = (byte)(object)values[11 + index]; ptr11[12] = (byte)(object)values[12 + index]; ptr11[13] = (byte)(object)values[13 + index]; ptr11[14] = (byte)(object)values[14 + index]; ptr11[15] = (byte)(object)values[15 + index]; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = ®ister.sbyte_0) { *ptr12 = (sbyte)(object)values[index]; ptr12[1] = (sbyte)(object)values[1 + index]; ptr12[2] = (sbyte)(object)values[2 + index]; ptr12[3] = (sbyte)(object)values[3 + index]; ptr12[4] = (sbyte)(object)values[4 + index]; ptr12[5] = (sbyte)(object)values[5 + index]; ptr12[6] = (sbyte)(object)values[6 + index]; ptr12[7] = (sbyte)(object)values[7 + index]; ptr12[8] = (sbyte)(object)values[8 + index]; ptr12[9] = (sbyte)(object)values[9 + index]; ptr12[10] = (sbyte)(object)values[10 + index]; ptr12[11] = (sbyte)(object)values[11 + index]; ptr12[12] = (sbyte)(object)values[12 + index]; ptr12[13] = (sbyte)(object)values[13 + index]; ptr12[14] = (sbyte)(object)values[14 + index]; ptr12[15] = (sbyte)(object)values[15 + index]; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = ®ister.uint16_0) { *ptr13 = (ushort)(object)values[index]; ptr13[1] = (ushort)(object)values[1 + index]; ptr13[2] = (ushort)(object)values[2 + index]; ptr13[3] = (ushort)(object)values[3 + index]; ptr13[4] = (ushort)(object)values[4 + index]; ptr13[5] = (ushort)(object)values[5 + index]; ptr13[6] = (ushort)(object)values[6 + index]; ptr13[7] = (ushort)(object)values[7 + index]; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = ®ister.int16_0) { *ptr14 = (short)(object)values[index]; ptr14[1] = (short)(object)values[1 + index]; ptr14[2] = (short)(object)values[2 + index]; ptr14[3] = (short)(object)values[3 + index]; ptr14[4] = (short)(object)values[4 + index]; ptr14[5] = (short)(object)values[5 + index]; ptr14[6] = (short)(object)values[6 + index]; ptr14[7] = (short)(object)values[7 + index]; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = ®ister.uint32_0) { *ptr15 = (uint)(object)values[index]; ptr15[1] = (uint)(object)values[1 + index]; ptr15[2] = (uint)(object)values[2 + index]; ptr15[3] = (uint)(object)values[3 + index]; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = ®ister.int32_0) { *ptr16 = (int)(object)values[index]; ptr16[1] = (int)(object)values[1 + index]; ptr16[2] = (int)(object)values[2 + index]; ptr16[3] = (int)(object)values[3 + index]; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = ®ister.uint64_0) { *ptr17 = (ulong)(object)values[index]; ptr17[1] = (ulong)(object)values[1 + index]; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = ®ister.int64_0) { *ptr18 = (long)(object)values[index]; ptr18[1] = (long)(object)values[1 + index]; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = ®ister.single_0) { *ptr19 = (float)(object)values[index]; ptr19[1] = (float)(object)values[1 + index]; ptr19[2] = (float)(object)values[2 + index]; ptr19[3] = (float)(object)values[3 + index]; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = ®ister.double_0) { *ptr20 = (double)(object)values[index]; ptr20[1] = (double)(object)values[1 + index]; } } } internal unsafe Vector(void* dataPointer) : this(dataPointer, 0) { } internal unsafe Vector(void* dataPointer, int offset) { this = default(Vector<T>); if (typeof(T) == typeof(byte)) { byte* ptr = (byte*)dataPointer; ptr += offset; fixed (byte* ptr2 = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr2[i] = ptr[i]; } } return; } if (typeof(T) == typeof(sbyte)) { sbyte* ptr3 = (sbyte*)dataPointer; ptr3 += offset; fixed (sbyte* ptr4 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr4[j] = ptr3[j]; } } return; } if (typeof(T) == typeof(ushort)) { ushort* ptr5 = (ushort*)dataPointer; ptr5 += offset; fixed (ushort* ptr6 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr6[k] = ptr5[k]; } } return; } if (typeof(T) == typeof(short)) { short* ptr7 = (short*)dataPointer; ptr7 += offset; fixed (short* ptr8 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr8[l] = ptr7[l]; } } return; } if (typeof(T) == typeof(uint)) { uint* ptr9 = (uint*)dataPointer; ptr9 += offset; fixed (uint* ptr10 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr10[m] = ptr9[m]; } } return; } if (typeof(T) == typeof(int)) { int* ptr11 = (int*)dataPointer; ptr11 += offset; fixed (int* ptr12 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr12[n] = ptr11[n]; } } return; } if (typeof(T) == typeof(ulong)) { ulong* ptr13 = (ulong*)dataPointer; ptr13 += offset; fixed (ulong* ptr14 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr14[num] = ptr13[num]; } } return; } if (typeof(T) == typeof(long)) { long* ptr15 = (long*)dataPointer; ptr15 += offset; fixed (long* ptr16 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr16[num2] = ptr15[num2]; } } return; } if (typeof(T) == typeof(float)) { float* ptr17 = (float*)dataPointer; ptr17 += offset; fixed (float* ptr18 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr18[num3] = ptr17[num3]; } } return; } if (typeof(T) == typeof(double)) { double* ptr19 = (double*)dataPointer; ptr19 += offset; fixed (double* ptr20 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr20[num4] = ptr19[num4]; } } return; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } private Vector(ref System.Numerics.Register existingRegister) { register = existingRegister; } [System.Runtime.CompilerServices.Intrinsic] public void CopyTo(T[] destination) { CopyTo(destination, 0); } [System.Runtime.CompilerServices.Intrinsic] public unsafe void CopyTo(T[] destination, int startIndex) { if (destination == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (startIndex < 0 || startIndex >= destination.Length) { throw new ArgumentOutOfRangeException("startIndex", System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, startIndex)); } if (destination.Length - startIndex < Count) { throw new ArgumentException(System.SR.Format(System.SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex)); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = (byte[])(object)destination) { for (int i = 0; i < Count; i++) { ptr[startIndex + i] = (byte)(object)this[i]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = (sbyte[])(object)destination) { for (int j = 0; j < Count; j++) { ptr2[startIndex + j] = (sbyte)(object)this[j]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = (ushort[])(object)destination) { for (int k = 0; k < Count; k++) { ptr3[startIndex + k] = (ushort)(object)this[k]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = (short[])(object)destination) { for (int l = 0; l < Count; l++) { ptr4[startIndex + l] = (short)(object)this[l]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = (uint[])(object)destination) { for (int m = 0; m < Count; m++) { ptr5[startIndex + m] = (uint)(object)this[m]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = (int[])(object)destination) { for (int n = 0; n < Count; n++) { ptr6[startIndex + n] = (int)(object)this[n]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = (ulong[])(object)destination) { for (int num = 0; num < Count; num++) { ptr7[startIndex + num] = (ulong)(object)this[num]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = (long[])(object)destination) { for (int num2 = 0; num2 < Count; num2++) { ptr8[startIndex + num2] = (long)(object)this[num2]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = (float[])(object)destination) { for (int num3 = 0; num3 < Count; num3++) { ptr9[startIndex + num3] = (float)(object)this[num3]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = (double[])(object)destination) { for (int num4 = 0; num4 < Count; num4++) { ptr10[startIndex + num4] = (double)(object)this[num4]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = (byte[])(object)destination) { ptr11[startIndex] = register.byte_0; ptr11[startIndex + 1] = register.byte_1; ptr11[startIndex + 2] = register.byte_2; ptr11[startIndex + 3] = register.byte_3; ptr11[startIndex + 4] = register.byte_4; ptr11[startIndex + 5] = register.byte_5; ptr11[startIndex + 6] = register.byte_6; ptr11[startIndex + 7] = register.byte_7; ptr11[startIndex + 8] = register.byte_8; ptr11[startIndex + 9] = register.byte_9; ptr11[startIndex + 10] = register.byte_10; ptr11[startIndex + 11] = register.byte_11; ptr11[startIndex + 12] = register.byte_12; ptr11[startIndex + 13] = register.byte_13; ptr11[startIndex + 14] = register.byte_14; ptr11[startIndex + 15] = register.byte_15; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = (sbyte[])(object)destination) { ptr12[startIndex] = register.sbyte_0; ptr12[startIndex + 1] = register.sbyte_1; ptr12[startIndex + 2] = register.sbyte_2; ptr12[startIndex + 3] = register.sbyte_3; ptr12[startIndex + 4] = register.sbyte_4; ptr12[startIndex + 5] = register.sbyte_5; ptr12[startIndex + 6] = register.sbyte_6; ptr12[startIndex + 7] = register.sbyte_7; ptr12[startIndex + 8] = register.sbyte_8; ptr12[startIndex + 9] = register.sbyte_9; ptr12[startIndex + 10] = register.sbyte_10; ptr12[startIndex + 11] = register.sbyte_11; ptr12[startIndex + 12] = register.sbyte_12; ptr12[startIndex + 13] = register.sbyte_13; ptr12[startIndex + 14] = register.sbyte_14; ptr12[startIndex + 15] = register.sbyte_15; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = (ushort[])(object)destination) { ptr13[startIndex] = register.uint16_0; ptr13[startIndex + 1] = register.uint16_1; ptr13[startIndex + 2] = register.uint16_2; ptr13[startIndex + 3] = register.uint16_3; ptr13[startIndex + 4] = register.uint16_4; ptr13[startIndex + 5] = register.uint16_5; ptr13[startIndex + 6] = register.uint16_6; ptr13[startIndex + 7] = register.uint16_7; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = (short[])(object)destination) { ptr14[startIndex] = register.int16_0; ptr14[startIndex + 1] = register.int16_1; ptr14[startIndex + 2] = register.int16_2; ptr14[startIndex + 3] = register.int16_3; ptr14[startIndex + 4] = register.int16_4; ptr14[startIndex + 5] = register.int16_5; ptr14[startIndex + 6] = register.int16_6; ptr14[startIndex + 7] = register.int16_7; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = (uint[])(object)destination) { ptr15[startIndex] = register.uint32_0; ptr15[startIndex + 1] = register.uint32_1; ptr15[startIndex + 2] = register.uint32_2; ptr15[startIndex + 3] = register.uint32_3; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = (int[])(object)destination) { ptr16[startIndex] = register.int32_0; ptr16[startIndex + 1] = register.int32_1; ptr16[startIndex + 2] = register.int32_2; ptr16[startIndex + 3] = register.int32_3; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = (ulong[])(object)destination) { ptr17[startIndex] = register.uint64_0; ptr17[startIndex + 1] = register.uint64_1; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = (long[])(object)destination) { ptr18[startIndex] = register.int64_0; ptr18[startIndex + 1] = register.int64_1; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = (float[])(object)destination) { ptr19[startIndex] = register.single_0; ptr19[startIndex + 1] = register.single_1; ptr19[startIndex + 2] = register.single_2; ptr19[startIndex + 3] = register.single_3; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = (double[])(object)destination) { ptr20[startIndex] = register.double_0; ptr20[startIndex + 1] = register.double_1; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector<T>)) { return false; } return Equals((Vector<T>)obj); } [System.Runtime.CompilerServices.Intrinsic] public bool Equals(Vector<T> other) { if (Vector.IsHardwareAccelerated) { for (int i = 0; i < Count; i++) { if (!ScalarEquals(this[i], other[i])) { return false; } } return true; } if (typeof(T) == typeof(byte)) { if (register.byte_0 == other.register.byte_0 && register.byte_1 == other.register.byte_1 && register.byte_2 == other.register.byte_2 && register.byte_3 == other.register.byte_3 && register.byte_4 == other.register.byte_4 && register.byte_5 == other.register.byte_5 && register.byte_6 == other.register.byte_6 && register.byte_7 == other.register.byte_7 && register.byte_8 == other.register.byte_8 && register.byte_9 == other.register.byte_9 && register.byte_10 == other.register.byte_10 && register.byte_11 == other.register.byte_11 && register.byte_12 == other.register.byte_12 && register.byte_13 == other.register.byte_13 && register.byte_14 == other.register.byte_14) { return register.byte_15 == other.register.byte_15; } return false; } if (typeof(T) == typeof(sbyte)) { if (register.sbyte_0 == other.register.sbyte_0 && register.sbyte_1 == other.register.sbyte_1 && register.sbyte_2 == other.register.sbyte_2 && register.sbyte_3 == other.register.sbyte_3 && register.sbyte_4 == other.register.sbyte_4 && register.sbyte_5 == other.register.sbyte_5 && register.sbyte_6 == other.register.sbyte_6 && register.sbyte_7 == other.register.sbyte_7 && register.sbyte_8 == other.register.sbyte_8 && register.sbyte_9 == other.register.sbyte_9 && register.sbyte_10 == other.register.sbyte_10 && register.sbyte_11 == other.register.sbyte_11 && register.sbyte_12 == other.register.sbyte_12 && register.sbyte_13 == other.register.sbyte_13 && register.sbyte_14 == other.register.sbyte_14) { return register.sbyte_15 == other.register.sbyte_15; } return false; } if (typeof(T) == typeof(ushort)) { if (register.uint16_0 == other.register.uint16_0 && register.uint16_1 == other.register.uint16_1 && register.uint16_2 == other.register.uint16_2 && register.uint16_3 == other.register.uint16_3 && register.uint16_4 == other.register.uint16_4 && register.uint16_5 == other.register.uint16_5 && register.uint16_6 == other.register.uint16_6) { return register.uint16_7 == other.register.uint16_7; } return false; } if (typeof(T) == typeof(short)) { if (register.int16_0 == other.register.int16_0 && register.int16_1 == other.register.int16_1 && register.int16_2 == other.register.int16_2 && register.int16_3 == other.register.int16_3 && register.int16_4 == other.register.int16_4 && register.int16_5 == other.register.int16_5 && register.int16_6 == other.register.int16_6) { return register.int16_7 == other.register.int16_7; } return false; } if (typeof(T) == typeof(uint)) { if (register.uint32_0 == other.register.uint32_0 && register.uint32_1 == other.register.uint32_1 && register.uint32_2 == other.register.uint32_2) { return register.uint32_3 == other.register.uint32_3; } return false; } if (typeof(T) == typeof(int)) { if (register.int32_0 == other.register.int32_0 && register.int32_1 == other.register.int32_1 && register.int32_2 == other.register.int32_2) { return register.int32_3 == other.register.int32_3; } return false; } if (typeof(T) == typeof(ulong)) { if (register.uint64_0 == other.register.uint64_0) { return register.uint64_1 == other.register.uint64_1; } return false; } if (typeof(T) == typeof(long)) { if (register.int64_0 == other.register.int64_0) { return register.int64_1 == other.register.int64_1; } return false; } if (typeof(T) == typeof(float)) { if (register.single_0 == other.register.single_0 && register.single_1 == other.register.single_1 && register.single_2 == other.register.single_2) { return register.single_3 == other.register.single_3; } return false; } if (typeof(T) == typeof(double)) { if (register.double_0 == other.register.double_0) { return register.double_1 == other.register.double_1; } return false; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override int GetHashCode() { int num = 0; if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { for (int i = 0; i < Count; i++) { num = HashHelpers.Combine(num, ((byte)(object)this[i]).GetHashCode()); } return num; } if (typeof(T) == typeof(sbyte)) { for (int j = 0; j < Count; j++) { num = HashHelpers.Combine(num, ((sbyte)(object)this[j]).GetHashCode()); } return num; } if (typeof(T) == typeof(ushort)) { for (int k = 0; k < Count; k++) { num = HashHelpers.Combine(num, ((ushort)(object)this[k]).GetHashCode()); } return num; } if (typeof(T) == typeof(short)) { for (int l = 0; l < Count; l++) { num = HashHelpers.Combine(num, ((short)(object)this[l]).GetHashCode()); } return num; } if (typeof(T) == typeof(uint)) { for (int m = 0; m < Count; m++) { num = HashHelpers.Combine(num, ((uint)(object)this[m]).GetHashCode()); } return num; } if (typeof(T) == typeof(int)) { for (int n = 0; n < Count; n++) { num = HashHelpers.Combine(num, ((int)(object)this[n]).GetHashCode()); } return num; } if (typeof(T) == typeof(ulong)) { for (int num2 = 0; num2 < Count; num2++) { num = HashHelpers.Combine(num, ((ulong)(object)this[num2]).GetHashCode()); } return num; } if (typeof(T) == typeof(long)) { for (int num3 = 0; num3 < Count; num3++) { num = HashHelpers.Combine(num, ((long)(object)this[num3]).GetHashCode()); } return num; } if (typeof(T) == typeof(float)) { for (int num4 = 0; num4 < Count; num4++) { num = HashHelpers.Combine(num, ((float)(object)this[num4]).GetHashCode()); } return num; } if (typeof(T) == typeof(double)) { for (int num5 = 0; num5 < Count; num5++) { num = HashHelpers.Combine(num, ((double)(object)this[num5]).GetHashCode()); } return num; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } if (typeof(T) == typeof(byte)) { num = HashHelpers.Combine(num, register.byte_0.GetHashCode()); num = HashHelpers.Combine(num, register.byte_1.GetHashCode()); num = HashHelpers.Combine(num, register.byte_2.GetHashCode()); num = HashHelpers.Combine(num, register.byte_3.GetHashCode()); num = HashHelpers.Combine(num, register.byte_4.GetHashCode()); num = HashHelpers.Combine(num, register.byte_5.GetHashCode()); num = HashHelpers.Combine(num, register.byte_6.GetHashCode()); num = HashHelpers.Combine(num, register.byte_7.GetHashCode()); num = HashHelpers.Combine(num, register.byte_8.GetHashCode()); num = HashHelpers.Combine(num, register.byte_9.GetHashCode()); num = HashHelpers.Combine(num, register.byte_10.GetHashCode()); num = HashHelpers.Combine(num, register.byte_11.GetHashCode()); num = HashHelpers.Combine(num, register.byte_12.GetHashCode()); num = HashHelpers.Combine(num, register.byte_13.GetHashCode()); num = HashHelpers.Combine(num, register.byte_14.GetHashCode()); return HashHelpers.Combine(num, register.byte_15.GetHashCode()); } if (typeof(T) == typeof(sbyte)) { num = HashHelpers.Combine(num, register.sbyte_0.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_1.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_2.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_3.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_4.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_5.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_6.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_7.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_8.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_9.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_10.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_11.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_12.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_13.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_14.GetHashCode()); return HashHelpers.Combine(num, register.sbyte_15.GetHashCode()); } if (typeof(T) == typeof(ushort)) { num = HashHelpers.Combine(num, register.uint16_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_2.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_3.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_4.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_5.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_6.GetHashCode()); return HashHelpers.Combine(num, register.uint16_7.GetHashCode()); } if (typeof(T) == typeof(short)) { num = HashHelpers.Combine(num, register.int16_0.GetHashCode()); num = HashHelpers.Combine(num, register.int16_1.GetHashCode()); num = HashHelpers.Combine(num, register.int16_2.GetHashCode()); num = HashHelpers.Combine(num, register.int16_3.GetHashCode()); num = HashHelpers.Combine(num, register.int16_4.GetHashCode()); num = HashHelpers.Combine(num, register.int16_5.GetHashCode()); num = HashHelpers.Combine(num, register.int16_6.GetHashCode()); return HashHelpers.Combine(num, register.int16_7.GetHashCode()); } if (typeof(T) == typeof(uint)) { num = HashHelpers.Combine(num, register.uint32_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_2.GetHashCode()); return HashHelpers.Combine(num, register.uint32_3.GetHashCode()); } if (typeof(T) == typeof(int)) { num = HashHelpers.Combine(num, register.int32_0.GetHashCode()); num = HashHelpers.Combine(num, register.int32_1.GetHashCode()); num = HashHelpers.Combine(num, register.int32_2.GetHashCode()); return HashHelpers.Combine(num, register.int32_3.GetHashCode()); } if (typeof(T) == typeof(ulong)) { num = HashHelpers.Combine(num, register.uint64_0.GetHashCode()); return HashHelpers.Combine(num, register.uint64_1.GetHashCode()); } if (typeof(T) == typeof(long)) { num = HashHelpers.Combine(num, register.int64_0.GetHashCode()); return HashHelpers.Combine(num, register.int64_1.GetHashCode()); } if (typeof(T) == typeof(float)) { num = HashHelpers.Combine(num, register.single_0.GetHashCode()); num = HashHelpers.Combine(num, register.single_1.GetHashCode()); num = HashHelpers.Combine(num, register.single_2.GetHashCode()); return HashHelpers.Combine(num, register.single_3.GetHashCode()); } if (typeof(T) == typeof(double)) { num = HashHelpers.Combine(num, register.double_0.GetHashCode()); return HashHelpers.Combine(num, register.double_1.GetHashCode()); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } public string ToString(string format, IFormatProvider formatProvider) { StringBuilder stringBuilder = new StringBuilder(); string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; stringBuilder.Append('<'); for (int i = 0; i < Count - 1; i++) { stringBuilder.Append(((IFormattable)(object)this[i]).ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); } stringBuilder.Append(((IFormattable)(object)this[Count - 1]).ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } public unsafe static Vector<T>operator +(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarAdd(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarAdd(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarAdd(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarAdd(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarAdd(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarAdd(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarAdd(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarAdd(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 + right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 + right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 + right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 + right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 + right.register.int32_0; result.register.int32_1 = left.register.int32_1 + right.register.int32_1; result.register.int32_2 = left.register.int32_2 + right.register.int32_2; result.register.int32_3 = left.register.int32_3 + right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 + right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 + right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 + right.register.int64_0; result.register.int64_1 = left.register.int64_1 + right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 + right.register.single_0; result.register.single_1 = left.register.single_1 + right.register.single_1; result.register.single_2 = left.register.single_2 + right.register.single_2; result.register.single_3 = left.register.single_3 + right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 + right.register.double_0; result.register.double_1 = left.register.double_1 + right.register.double_1; } return result; } public unsafe static Vector<T>operator -(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarSubtract(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarSubtract(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarSubtract(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarSubtract(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarSubtract(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarSubtract(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarSubtract(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarSubtract(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 - right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 - right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 - right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 - right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 - right.register.int32_0; result.register.int32_1 = left.register.int32_1 - right.register.int32_1; result.register.int32_2 = left.register.int32_2 - right.register.int32_2; result.register.int32_3 = left.register.int32_3 - right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 - right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 - right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 - right.register.int64_0; result.register.int64_1 = left.register.int64_1 - right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 - right.register.single_0; result.register.single_1 = left.register.single_1 - right.register.single_1; result.register.single_2 = left.register.single_2 - right.register.single_2; result.register.single_3 = left.register.single_3 - right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 - right.register.double_0; result.register.double_1 = left.register.double_1 - right.register.double_1; } return result; } public unsafe static Vector<T>operator *(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarMultiply(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarMultiply(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarMultiply(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarMultiply(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarMultiply(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarMultiply(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarMultiply(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarMultiply(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 * right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 * right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 * right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 * right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 * right.register.int32_0; result.register.int32_1 = left.register.int32_1 * right.register.int32_1; result.register.int32_2 = left.register.int32_2 * right.register.int32_2; result.register.int32_3 = left.register.int32_3 * right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 * right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 * right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 * right.register.int64_0; result.register.int64_1 = left.register.int64_1 * right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 * right.register.single_0; result.register.single_1 = left.register.single_1 * right.register.single_1; result.register.single_2 = left.register.single_2 * right.register.single_2; result.register.single_3 = left.register.single_3 * right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 * right.register.double_0; result.register.double_1 = left.register.double_1 * right.register.double_1; } return result; } public static Vector<T>operator *(Vector<T> value, T factor) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public static Vector<T>operator *(T factor, Vector<T> value) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public unsafe static Vector<T>operator /(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarDivide(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarDivide(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarDivide(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarDivide(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarDivide(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarDivide(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarDivide(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarDivide(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 / right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 / right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 / right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 / right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 / right.register.int32_0; result.register.int32_1 = left.register.int32_1 / right.register.int32_1; result.register.int32_2 = left.register.int32_2 / right.register.int32_2; result.register.int32_3 = left.register.int32_3 / right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 / right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 / right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 / right.register.int64_0; result.register.int64_1 = left.register.int64_1 / right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 / right.register.single_0; result.register.single_1 = left.register.single_1 / right.register.single_1; result.register.single_2 = left.register.single_2 / right.register.single_2; result.register.single_3 = left.register.single_3 / right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 / right.register.double_0; result.register.double_1 = left.register.double_1 / right.register.double_1; } return result; } public static Vector<T>operator -(Vector<T> value) { return Zero - value; } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector<T>operator &(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] & ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 & right.register.int64_0; result.register.int64_1 = left.register.int64_1 & right.register.int64_1; } return result; } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector<T>operator |(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] | ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 | right.register.int64_0; result.register.int64_1 = left.register.int64_1 | right.register.int64_1; } return result; } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector<T>operator ^(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] ^ ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 ^ right.register.int64_0; result.register.int64_1 = left.register.int64_1 ^ right.register.int64_1; } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T>operator ~(Vector<T> value) { return s_allOnes ^ value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector<T> left, Vector<T> right) { return left.Equals(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector<T> left, Vector<T> right) { return !(left == right); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<byte>(Vector<T> value) { return new Vector<byte>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<sbyte>(Vector<T> value) { return new Vector<sbyte>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<ushort>(Vector<T> value) { return new Vector<ushort>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<short>(Vector<T> value) { return new Vector<short>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<uint>(Vector<T> value) { return new Vector<uint>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<int>(Vector<T> value) { return new Vector<int>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<ulong>(Vector<T> value) { return new Vector<ulong>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<long>(Vector<T> value) { return new Vector<long>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<float>(Vector<T> value) { return new Vector<float>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<double>(Vector<T> value) { return new Vector<double>(ref value.register); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] internal unsafe static Vector<T> Equals(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; fo
plugins/System.Memory.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Numerics; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using FxResources.System.Memory; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Memory")] [assembly: AssemblyDescription("System.Memory")] [assembly: AssemblyDefaultAlias("System.Memory")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.31308.01")] [assembly: AssemblyInformationalVersion("4.6.31308.01 @BuiltBy: cloudtest-841353dfc000000 @Branch: release/2.1-MSRC @SrcCode: https://github.com/dotnet/corefx/tree/32b491939fbd125f304031c35038b1e14b4e3958")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.1.2")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } } namespace FxResources.System.Memory { internal static class SR { } } namespace System { public readonly struct SequencePosition : IEquatable<SequencePosition> { private readonly object _object; private readonly int _integer; public SequencePosition(object @object, int integer) { _object = @object; _integer = integer; } [EditorBrowsable(EditorBrowsableState.Never)] public object GetObject() { return _object; } [EditorBrowsable(EditorBrowsableState.Never)] public int GetInteger() { return _integer; } public bool Equals(SequencePosition other) { if (_integer == other._integer) { return object.Equals(_object, other._object); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is SequencePosition other) { return Equals(other); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return HashHelpers.Combine(_object?.GetHashCode() ?? 0, _integer); } } internal static class ThrowHelper { internal static void ThrowArgumentNullException(System.ExceptionArgument argument) { throw CreateArgumentNullException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentNullException(System.ExceptionArgument argument) { return new ArgumentNullException(argument.ToString()); } internal static void ThrowArrayTypeMismatchException() { throw CreateArrayTypeMismatchException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArrayTypeMismatchException() { return new ArrayTypeMismatchException(); } internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type) { throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type) { return new ArgumentException(System.SR.Format(System.SR.Argument_InvalidTypeWithPointersNotSupported, type)); } internal static void ThrowArgumentException_DestinationTooShort() { throw CreateArgumentException_DestinationTooShort(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_DestinationTooShort() { return new ArgumentException(System.SR.Argument_DestinationTooShort); } internal static void ThrowIndexOutOfRangeException() { throw CreateIndexOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateIndexOutOfRangeException() { return new IndexOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException() { throw CreateArgumentOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException() { return new ArgumentOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument) { throw CreateArgumentOutOfRangeException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException(System.ExceptionArgument argument) { return new ArgumentOutOfRangeException(argument.ToString()); } internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge() { throw CreateArgumentOutOfRangeException_PrecisionTooLarge(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge() { return new ArgumentOutOfRangeException("precision", System.SR.Format(System.SR.Argument_PrecisionTooLarge, (byte)99)); } internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit() { throw CreateArgumentOutOfRangeException_SymbolDoesNotFit(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit() { return new ArgumentOutOfRangeException("symbol", System.SR.Argument_BadFormatSpecifier); } internal static void ThrowInvalidOperationException() { throw CreateInvalidOperationException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException() { return new InvalidOperationException(); } internal static void ThrowInvalidOperationException_OutstandingReferences() { throw CreateInvalidOperationException_OutstandingReferences(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_OutstandingReferences() { return new InvalidOperationException(System.SR.OutstandingReferences); } internal static void ThrowInvalidOperationException_UnexpectedSegmentType() { throw CreateInvalidOperationException_UnexpectedSegmentType(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_UnexpectedSegmentType() { return new InvalidOperationException(System.SR.UnexpectedSegmentType); } internal static void ThrowInvalidOperationException_EndPositionNotReached() { throw CreateInvalidOperationException_EndPositionNotReached(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_EndPositionNotReached() { return new InvalidOperationException(System.SR.EndPositionNotReached); } internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange() { throw CreateArgumentOutOfRangeException_PositionOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange() { return new ArgumentOutOfRangeException("position"); } internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange() { throw CreateArgumentOutOfRangeException_OffsetOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange() { return new ArgumentOutOfRangeException("offset"); } internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer() { throw CreateObjectDisposedException_ArrayMemoryPoolBuffer(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer() { return new ObjectDisposedException("ArrayMemoryPoolBuffer"); } internal static void ThrowFormatException_BadFormatSpecifier() { throw CreateFormatException_BadFormatSpecifier(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateFormatException_BadFormatSpecifier() { return new FormatException(System.SR.Argument_BadFormatSpecifier); } internal static void ThrowArgumentException_OverlapAlignmentMismatch() { throw CreateArgumentException_OverlapAlignmentMismatch(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_OverlapAlignmentMismatch() { return new ArgumentException(System.SR.Argument_OverlapAlignmentMismatch); } internal static void ThrowNotSupportedException() { throw CreateThrowNotSupportedException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateThrowNotSupportedException() { return new NotSupportedException(); } public static bool TryFormatThrowFormatException(out int bytesWritten) { bytesWritten = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static bool TryParseThrowFormatException<T>(out T value, out int bytesConsumed) { value = default(T); bytesConsumed = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static void ThrowArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment) { throw CreateArgumentValidationException(startSegment, startIndex, endSegment); } private static Exception CreateArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment) { if (startSegment == null) { return CreateArgumentNullException(System.ExceptionArgument.startSegment); } if (endSegment == null) { return CreateArgumentNullException(System.ExceptionArgument.endSegment); } if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.endSegment); } if ((uint)startSegment.Memory.Length < (uint)startIndex) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.startIndex); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.endIndex); } public static void ThrowArgumentValidationException(Array array, int start) { throw CreateArgumentValidationException(array, start); } private static Exception CreateArgumentValidationException(Array array, int start) { if (array == null) { return CreateArgumentNullException(System.ExceptionArgument.array); } if ((uint)start > (uint)array.Length) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); } public static void ThrowStartOrEndArgumentValidationException(long start) { throw CreateStartOrEndArgumentValidationException(start); } private static Exception CreateStartOrEndArgumentValidationException(long start) { if (start < 0) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); } } internal enum ExceptionArgument { length, start, minimumBufferSize, elementIndex, comparable, comparer, destination, offset, startSegment, endSegment, startIndex, endIndex, array, culture, manager } internal static class DecimalDecCalc { private static uint D32DivMod1E9(uint hi32, ref uint lo32) { ulong num = ((ulong)hi32 << 32) | lo32; lo32 = (uint)(num / 1000000000); return (uint)(num % 1000000000); } internal static uint DecDivMod1E9(ref MutableDecimal value) { return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0u, ref value.High), ref value.Mid), ref value.Low); } internal static void DecAddInt32(ref MutableDecimal value, uint i) { if (D32AddCarry(ref value.Low, i) && D32AddCarry(ref value.Mid, 1u)) { D32AddCarry(ref value.High, 1u); } } private static bool D32AddCarry(ref uint value, uint i) { uint num = value; uint num2 = (value = num + i); if (num2 >= num) { return num2 < i; } return true; } internal static void DecMul10(ref MutableDecimal value) { MutableDecimal d = value; DecShiftLeft(ref value); DecShiftLeft(ref value); DecAdd(ref value, d); DecShiftLeft(ref value); } private static void DecShiftLeft(ref MutableDecimal value) { uint num = (((value.Low & 0x80000000u) != 0) ? 1u : 0u); uint num2 = (((value.Mid & 0x80000000u) != 0) ? 1u : 0u); value.Low <<= 1; value.Mid = (value.Mid << 1) | num; value.High = (value.High << 1) | num2; } private static void DecAdd(ref MutableDecimal value, MutableDecimal d) { if (D32AddCarry(ref value.Low, d.Low) && D32AddCarry(ref value.Mid, 1u)) { D32AddCarry(ref value.High, 1u); } if (D32AddCarry(ref value.Mid, d.Mid)) { D32AddCarry(ref value.High, 1u); } D32AddCarry(ref value.High, d.High); } } internal static class Number { private static class DoubleHelper { public unsafe static uint Exponent(double d) { return (*(uint*)((byte*)(&d) + 4) >> 20) & 0x7FFu; } public unsafe static ulong Mantissa(double d) { return *(uint*)(&d) | ((ulong)(uint)(*(int*)((byte*)(&d) + 4) & 0xFFFFF) << 32); } public unsafe static bool Sign(double d) { return *(uint*)((byte*)(&d) + 4) >> 31 != 0; } } internal const int DECIMAL_PRECISION = 29; private static readonly ulong[] s_rgval64Power10 = new ulong[30] { 11529215046068469760uL, 14411518807585587200uL, 18014398509481984000uL, 11258999068426240000uL, 14073748835532800000uL, 17592186044416000000uL, 10995116277760000000uL, 13743895347200000000uL, 17179869184000000000uL, 10737418240000000000uL, 13421772800000000000uL, 16777216000000000000uL, 10485760000000000000uL, 13107200000000000000uL, 16384000000000000000uL, 14757395258967641293uL, 11805916207174113035uL, 9444732965739290428uL, 15111572745182864686uL, 12089258196146291749uL, 9671406556917033399uL, 15474250491067253438uL, 12379400392853802751uL, 9903520314283042201uL, 15845632502852867522uL, 12676506002282294018uL, 10141204801825835215uL, 16225927682921336344uL, 12980742146337069075uL, 10384593717069655260uL }; private static readonly sbyte[] s_rgexp64Power10 = new sbyte[15] { 4, 7, 10, 14, 17, 20, 24, 27, 30, 34, 37, 40, 44, 47, 50 }; private static readonly ulong[] s_rgval64Power10By16 = new ulong[42] { 10240000000000000000uL, 11368683772161602974uL, 12621774483536188886uL, 14012984643248170708uL, 15557538194652854266uL, 17272337110188889248uL, 9588073174409622172uL, 10644899600020376798uL, 11818212630765741798uL, 13120851772591970216uL, 14567071740625403792uL, 16172698447808779622uL, 17955302187076837696uL, 9967194951097567532uL, 11065809325636130658uL, 12285516299433008778uL, 13639663065038175358uL, 15143067982934716296uL, 16812182738118149112uL, 9332636185032188787uL, 10361307573072618722uL, 16615349947311448416uL, 14965776766268445891uL, 13479973333575319909uL, 12141680576410806707uL, 10936253623915059637uL, 9850501549098619819uL, 17745086042373215136uL, 15983352577617880260uL, 14396524142538228461uL, 12967236152753103031uL, 11679847981112819795uL, 10520271803096747049uL, 9475818434452569218uL, 17070116948172427008uL, 15375394465392026135uL, 13848924157002783096uL, 12474001934591998882uL, 11235582092889474480uL, 10120112665365530972uL, 18230774251475056952uL, 16420821625123739930uL }; private static readonly short[] s_rgexp64Power10By16 = new short[21] { 54, 107, 160, 213, 266, 319, 373, 426, 479, 532, 585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064, 1117 }; public static void RoundNumber(ref NumberBuffer number, int pos) { Span<byte> digits = number.Digits; int i; for (i = 0; i < pos && digits[i] != 0; i++) { } if (i == pos && digits[i] >= 53) { while (i > 0 && digits[i - 1] == 57) { i--; } if (i > 0) { digits[i - 1]++; } else { number.Scale++; digits[0] = 49; i = 1; } } else { while (i > 0 && digits[i - 1] == 48) { i--; } } if (i == 0) { number.Scale = 0; number.IsNegative = false; } digits[i] = 0; } internal static bool NumberBufferToDouble(ref NumberBuffer number, out double value) { double num = NumberToDouble(ref number); uint num2 = DoubleHelper.Exponent(num); ulong num3 = DoubleHelper.Mantissa(num); switch (num2) { case 2047u: value = 0.0; return false; case 0u: if (num3 == 0L) { num = 0.0; } break; } value = num; return true; } public unsafe static bool NumberBufferToDecimal(ref NumberBuffer number, ref decimal value) { MutableDecimal source = default(MutableDecimal); byte* ptr = number.UnsafeDigits; int num = number.Scale; if (*ptr == 0) { if (num > 0) { num = 0; } } else { if (num > 29) { return false; } while ((num > 0 || (*ptr != 0 && num > -28)) && (source.High < 429496729 || (source.High == 429496729 && (source.Mid < 2576980377u || (source.Mid == 2576980377u && (source.Low < 2576980377u || (source.Low == 2576980377u && *ptr <= 53))))))) { DecimalDecCalc.DecMul10(ref source); if (*ptr != 0) { DecimalDecCalc.DecAddInt32(ref source, (uint)(*(ptr++) - 48)); } num--; } if (*(ptr++) >= 53) { bool flag = true; if (*(ptr - 1) == 53 && *(ptr - 2) % 2 == 0) { int num2 = 20; while (*ptr == 48 && num2 != 0) { ptr++; num2--; } if (*ptr == 0 || num2 == 0) { flag = false; } } if (flag) { DecimalDecCalc.DecAddInt32(ref source, 1u); if ((source.High | source.Mid | source.Low) == 0) { source.High = 429496729u; source.Mid = 2576980377u; source.Low = 2576980378u; num++; } } } } if (num > 0) { return false; } if (num <= -29) { source.High = 0u; source.Low = 0u; source.Mid = 0u; source.Scale = 28; } else { source.Scale = -num; } source.IsNegative = number.IsNegative; value = Unsafe.As<MutableDecimal, decimal>(ref source); return true; } public static void DecimalToNumber(decimal value, ref NumberBuffer number) { ref MutableDecimal reference = ref Unsafe.As<decimal, MutableDecimal>(ref value); Span<byte> digits = number.Digits; number.IsNegative = reference.IsNegative; int num = 29; while ((reference.Mid != 0) | (reference.High != 0)) { uint num2 = DecimalDecCalc.DecDivMod1E9(ref reference); for (int i = 0; i < 9; i++) { digits[--num] = (byte)(num2 % 10 + 48); num2 /= 10; } } for (uint num3 = reference.Low; num3 != 0; num3 /= 10) { digits[--num] = (byte)(num3 % 10 + 48); } int num4 = 29 - num; number.Scale = num4 - reference.Scale; Span<byte> digits2 = number.Digits; int index = 0; while (--num4 >= 0) { digits2[index++] = digits[num++]; } digits2[index] = 0; } private static uint DigitsToInt(ReadOnlySpan<byte> digits, int count) { uint value; int bytesConsumed; bool flag = Utf8Parser.TryParse(digits.Slice(0, count), out value, out bytesConsumed, 'D'); return value; } private static ulong Mul32x32To64(uint a, uint b) { return (ulong)a * (ulong)b; } private static ulong Mul64Lossy(ulong a, ulong b, ref int pexp) { ulong num = Mul32x32To64((uint)(a >> 32), (uint)(b >> 32)) + (Mul32x32To64((uint)(a >> 32), (uint)b) >> 32) + (Mul32x32To64((uint)a, (uint)(b >> 32)) >> 32); if ((num & 0x8000000000000000uL) == 0L) { num <<= 1; pexp--; } return num; } private static int abs(int value) { if (value < 0) { return -value; } return value; } private unsafe static double NumberToDouble(ref NumberBuffer number) { ReadOnlySpan<byte> digits = number.Digits; int i = 0; int numDigits = number.NumDigits; int num = numDigits; for (; digits[i] == 48; i++) { num--; } if (num == 0) { return 0.0; } int num2 = Math.Min(num, 9); num -= num2; ulong num3 = DigitsToInt(digits, num2); if (num > 0) { num2 = Math.Min(num, 9); num -= num2; uint b = (uint)(s_rgval64Power10[num2 - 1] >> 64 - s_rgexp64Power10[num2 - 1]); num3 = Mul32x32To64((uint)num3, b) + DigitsToInt(digits.Slice(9), num2); } int num4 = number.Scale - (numDigits - num); int num5 = abs(num4); if (num5 >= 352) { ulong num6 = ((num4 > 0) ? 9218868437227405312uL : 0); if (number.IsNegative) { num6 |= 0x8000000000000000uL; } return *(double*)(&num6); } int pexp = 64; if ((num3 & 0xFFFFFFFF00000000uL) == 0L) { num3 <<= 32; pexp -= 32; } if ((num3 & 0xFFFF000000000000uL) == 0L) { num3 <<= 16; pexp -= 16; } if ((num3 & 0xFF00000000000000uL) == 0L) { num3 <<= 8; pexp -= 8; } if ((num3 & 0xF000000000000000uL) == 0L) { num3 <<= 4; pexp -= 4; } if ((num3 & 0xC000000000000000uL) == 0L) { num3 <<= 2; pexp -= 2; } if ((num3 & 0x8000000000000000uL) == 0L) { num3 <<= 1; pexp--; } int num7 = num5 & 0xF; if (num7 != 0) { int num8 = s_rgexp64Power10[num7 - 1]; pexp += ((num4 < 0) ? (-num8 + 1) : num8); ulong b2 = s_rgval64Power10[num7 + ((num4 < 0) ? 15 : 0) - 1]; num3 = Mul64Lossy(num3, b2, ref pexp); } num7 = num5 >> 4; if (num7 != 0) { int num9 = s_rgexp64Power10By16[num7 - 1]; pexp += ((num4 < 0) ? (-num9 + 1) : num9); ulong b3 = s_rgval64Power10By16[num7 + ((num4 < 0) ? 21 : 0) - 1]; num3 = Mul64Lossy(num3, b3, ref pexp); } if (((uint)(int)num3 & 0x400u) != 0) { ulong num10 = num3 + 1023 + (ulong)(((int)num3 >> 11) & 1); if (num10 < num3) { num10 = (num10 >> 1) | 0x8000000000000000uL; pexp++; } num3 = num10; } pexp += 1022; num3 = ((pexp <= 0) ? ((pexp == -52 && num3 >= 9223372036854775896uL) ? 1 : ((pexp > -52) ? (num3 >> -pexp + 11 + 1) : 0)) : ((pexp < 2047) ? ((ulong)((long)pexp << 52) + ((num3 >> 11) & 0xFFFFFFFFFFFFFL)) : 9218868437227405312uL)); if (number.IsNegative) { num3 |= 0x8000000000000000uL; } return *(double*)(&num3); } } internal ref struct NumberBuffer { public int Scale; public bool IsNegative; public const int BufferSize = 51; private byte _b0; private byte _b1; private byte _b2; private byte _b3; private byte _b4; private byte _b5; private byte _b6; private byte _b7; private byte _b8; private byte _b9; private byte _b10; private byte _b11; private byte _b12; private byte _b13; private byte _b14; private byte _b15; private byte _b16; private byte _b17; private byte _b18; private byte _b19; private byte _b20; private byte _b21; private byte _b22; private byte _b23; private byte _b24; private byte _b25; private byte _b26; private byte _b27; private byte _b28; private byte _b29; private byte _b30; private byte _b31; private byte _b32; private byte _b33; private byte _b34; private byte _b35; private byte _b36; private byte _b37; private byte _b38; private byte _b39; private byte _b40; private byte _b41; private byte _b42; private byte _b43; private byte _b44; private byte _b45; private byte _b46; private byte _b47; private byte _b48; private byte _b49; private byte _b50; public unsafe Span<byte> Digits => new Span<byte>(Unsafe.AsPointer(ref _b0), 51); public unsafe byte* UnsafeDigits => (byte*)Unsafe.AsPointer(ref _b0); public int NumDigits => Digits.IndexOf<byte>(0); [Conditional("DEBUG")] public void CheckConsistency() { } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('['); stringBuilder.Append('"'); Span<byte> digits = Digits; for (int i = 0; i < 51; i++) { byte b = digits[i]; if (b == 0) { break; } stringBuilder.Append((char)b); } stringBuilder.Append('"'); stringBuilder.Append(", Scale = " + Scale); stringBuilder.Append(", IsNegative = " + IsNegative); stringBuilder.Append(']'); return stringBuilder.ToString(); } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct Memory<T> { private readonly object _object; private readonly int _index; private readonly int _length; private const int RemoveFlagsBitMask = int.MaxValue; public static Memory<T> Empty => default(Memory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Span<T> result; if (_index < 0) { result = ((MemoryManager<T>)_object).GetSpan(); return result.Slice(_index & 0x7FFFFFFF, _length); } if (typeof(T) == typeof(char) && _object is string text) { result = new Span<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new Span<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(Span<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) { this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[] array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = array.Length - start; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int length) { if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int start, int length) { if (length < 0 || start < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = start | int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(object obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator Memory<T>(T[] array) { return new Memory<T>(array); } public static implicit operator Memory<T>(ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { return Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.Memory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { int length2 = _length; int num = length2 & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer3, handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> readOnlyMemory) { return readOnlyMemory.Equals(this); } if (obj is Memory<T> other) { return Equals(other); } return false; } public bool Equals(Memory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } int hashCode = _object.GetHashCode(); int index = _index; int hashCode2 = index.GetHashCode(); index = _length; return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } } internal sealed class MemoryDebugView<T> { private readonly ReadOnlyMemory<T> _memory; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _memory.ToArray(); public MemoryDebugView(Memory<T> memory) { _memory = memory; } public MemoryDebugView(ReadOnlyMemory<T> memory) { _memory = memory; } } public static class MemoryExtensions { internal static readonly IntPtr StringAdjustment = MeasureStringAdjustment(); public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span) { return span.TrimStart().TrimEnd(); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span) { int i; for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span) { int num = span.Length - 1; while (num >= 0 && char.IsWhiteSpace(span[num])) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, char trimChar) { return span.TrimStart(trimChar).TrimEnd(trimChar); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, char trimChar) { int i; for (i = 0; i < span.Length && span[i] == trimChar; i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, char trimChar) { int num = span.Length - 1; while (num >= 0 && span[num] == trimChar) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { return span.TrimStart(trimChars).TrimEnd(trimChars); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimStart(); } int i; for (i = 0; i < span.Length; i++) { int num = 0; while (num < trimChars.Length) { if (span[i] != trimChars[num]) { num++; continue; } goto IL_003c; } break; IL_003c:; } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimEnd(); } int num; for (num = span.Length - 1; num >= 0; num--) { int num2 = 0; while (num2 < trimChars.Length) { if (span[num] != trimChars[num2]) { num2++; continue; } goto IL_0044; } break; IL_0044:; } return span.Slice(0, num + 1); } public static bool IsWhiteSpace(this ReadOnlySpan<char> span) { for (int i = 0; i < span.Length; i++) { if (!char.IsWhiteSpace(span[i])) { return false; } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } public static int SequenceCompareTo<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SequenceCompareTo<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } public static void Reverse<T>(this Span<T> span) { ref T reference = ref MemoryMarshal.GetReference(span); int num = 0; int num2 = span.Length - 1; while (num < num2) { T val = Unsafe.Add(ref reference, num); Unsafe.Add(ref reference, num) = Unsafe.Add(ref reference, num2); Unsafe.Add(ref reference, num2) = val; num++; num2--; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array) { return new Span<T>(array); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array, int start, int length) { return new Span<T>(array, start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Span<T>(segment.Array, segment.Offset + start, segment.Count - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Span<T>(segment.Array, segment.Offset + start, length); } public static Memory<T> AsMemory<T>(this T[] array) { return new Memory<T>(array); } public static Memory<T> AsMemory<T>(this T[] array, int start) { return new Memory<T>(array, start); } public static Memory<T> AsMemory<T>(this T[] array, int start, int length) { return new Memory<T>(array, start, length); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(segment.Array, segment.Offset + start, segment.Count - start); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Memory<T>(segment.Array, segment.Offset + start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[] source, Span<T> destination) { new ReadOnlySpan<T>(source).CopyTo(destination); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[] source, Memory<T> destination) { source.CopyTo(destination.Span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other) { return ((ReadOnlySpan<T>)span).Overlaps(other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other, out int elementOffset) { return ((ReadOnlySpan<T>)span).Overlaps(other, out elementOffset); } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) { if (span.IsEmpty || other.IsEmpty) { return false; } IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr >= (uint)(span.Length * Unsafe.SizeOf<T>())) { return (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>())); } return true; } if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>())) { return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>())); } return true; } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other, out int elementOffset) { if (span.IsEmpty || other.IsEmpty) { elementOffset = 0; return false; } IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr < (uint)(span.Length * Unsafe.SizeOf<T>()) || (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>()))) { if ((int)intPtr % Unsafe.SizeOf<T>() != 0) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)intPtr / Unsafe.SizeOf<T>(); return true; } elementOffset = 0; return false; } if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>()))) { if ((long)intPtr % Unsafe.SizeOf<T>() != 0L) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)((long)intPtr / Unsafe.SizeOf<T>()); return true; } elementOffset = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this Span<T> span, IComparable<T> comparable) { return span.BinarySearch<T, IComparable<T>>(comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this Span<T> span, TComparable comparable) where TComparable : IComparable<T> { return BinarySearch((ReadOnlySpan<T>)span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this Span<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { return ((ReadOnlySpan<T>)span).BinarySearch(value, comparer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this ReadOnlySpan<T> span, IComparable<T> comparable) { return MemoryExtensions.BinarySearch<T, IComparable<T>>(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { return System.SpanHelpers.BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this ReadOnlySpan<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { if (comparer == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparer); } System.SpanHelpers.ComparerComparable<T, TComparer> comparable = new System.SpanHelpers.ComparerComparable<T, TComparer>(value, comparer); return BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsTypeComparableAsBytes<T>(out NUInt size) { if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) { size = (NUInt)1; return true; } if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort)) { size = (NUInt)2; return true; } if (typeof(T) == typeof(int) || typeof(T) == typeof(uint)) { size = (NUInt)4; return true; } if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong)) { size = (NUInt)8; return true; } size = default(NUInt); return false; } public static Span<T> AsSpan<T>(this T[] array, int start) { return Span<T>.Create(array, start); } public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { return span.IndexOf(value, comparisonType) >= 0; } public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.SequenceEqual(other); case StringComparison.OrdinalIgnoreCase: if (span.Length != other.Length) { return false; } return EqualsOrdinalIgnoreCase(span, other); default: return span.ToString().Equals(other.ToString(), comparisonType); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool EqualsOrdinalIgnoreCase(ReadOnlySpan<char> span, ReadOnlySpan<char> other) { if (other.Length == 0) { return true; } return CompareToOrdinalIgnoreCase(span, other) == 0; } public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { return comparisonType switch { StringComparison.Ordinal => span.SequenceCompareTo(other), StringComparison.OrdinalIgnoreCase => CompareToOrdinalIgnoreCase(span, other), _ => string.Compare(span.ToString(), other.ToString(), comparisonType), }; } private unsafe static int CompareToOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB) { int num = Math.Min(strA.Length, strB.Length); int num2 = num; fixed (char* ptr = &MemoryMarshal.GetReference(strA)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(strB)) { char* ptr2 = ptr; char* ptr4 = ptr3; while (num != 0 && *ptr2 <= '\u007f' && *ptr4 <= '\u007f') { int num3 = *ptr2; int num4 = *ptr4; if (num3 == num4) { ptr2++; ptr4++; num--; continue; } if ((uint)(num3 - 97) <= 25u) { num3 -= 32; } if ((uint)(num4 - 97) <= 25u) { num4 -= 32; } if (num3 != num4) { return num3 - num4; } ptr2++; ptr4++; num--; } if (num == 0) { return strA.Length - strB.Length; } num2 -= num; return string.Compare(strA.Slice(num2).ToString(), strB.Slice(num2).ToString(), StringComparison.OrdinalIgnoreCase); } } } public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { if (comparisonType == StringComparison.Ordinal) { return span.IndexOf(value); } return span.ToString().IndexOf(value.ToString(), comparisonType); } public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); } if (destination.Length < source.Length) { return -1; } string text = source.ToString(); string text2 = text.ToLower(culture); AsSpan(text2).CopyTo(destination); return source.Length; } public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToLower(destination, CultureInfo.InvariantCulture); } public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); } if (destination.Length < source.Length) { return -1; } string text = source.ToString(); string text2 = text.ToUpper(culture); AsSpan(text2).CopyTo(destination); return source.Length; } public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToUpper(destination, CultureInfo.InvariantCulture); } public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.EndsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.EndsWith(value2, comparisonType); } } } public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.StartsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(0, value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.StartsWith(value2, comparisonType); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text) { if (text == null) { return default(ReadOnlySpan<char>); } return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment, text.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, text.Length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, length); } public static ReadOnlyMemory<char> AsMemory(this string text) { if (text == null) { return default(ReadOnlyMemory<char>); } return new ReadOnlyMemory<char>(text, 0, text.Length); } public static ReadOnlyMemory<char> AsMemory(this string text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, text.Length - start); } public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, length); } private unsafe static IntPtr MeasureStringAdjustment() { string text = "a"; fixed (char* source = text) { return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<char>>(text).Data, ref Unsafe.AsRef<char>(source)); } } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct ReadOnlyMemory<T> { private readonly object _object; private readonly int _index; private readonly int _length; internal const int RemoveFlagsBitMask = int.MaxValue; public static ReadOnlyMemory<T> Empty => default(ReadOnlyMemory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public ReadOnlySpan<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) { return ((MemoryManager<T>)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length); } ReadOnlySpan<T> result; if (typeof(T) == typeof(char) && _object is string text) { result = new ReadOnlySpan<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new ReadOnlySpan<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(ReadOnlySpan<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array) { if (array == null) { this = default(ReadOnlyMemory<T>); return; } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(ReadOnlyMemory<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlyMemory(object obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator ReadOnlyMemory<T>(T[] array) { return new ReadOnlyMemory<T>(array); } public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment) { return new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start, int length) { int length2 = _length; int num = _length & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer3, handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> other) { return Equals(other); } if (obj is Memory<T> memory) { return Equals(memory); } return false; } public bool Equals(ReadOnlyMemory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } int hashCode = _object.GetHashCode(); int index = _index; int hashCode2 = index.GetHashCode(); index = _length; return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal object GetObjectStartLength(out int start, out int length) { start = _index; length = _length; return _object; } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct ReadOnlySpan<T> { public ref struct Enumerator { private readonly ReadOnlySpan<T> _span; private int _index; public ref readonly T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly Pinnable<T> _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>); public unsafe ref readonly T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable<T> Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { return !(left == right); } [Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator ReadOnlySpan<T>(T[] array) { return new ReadOnlySpan<T>(array); } public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment) { return new ReadOnlySpan<T>(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array) { if (array == null) { this = default(ReadOnlySpan<T>); return; } _length = array.Length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(ReadOnlySpan<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe ReadOnlySpan(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(Pinnable<T> pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref readonly T GetPinnableReference() { if (_length != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } return ref Unsafe.AsRef<T>(null); } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination.Length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { if (left._length == right._length) { return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { if (_byteOffset == MemoryExtensions.StringAdjustment) { object obj = Unsafe.As<object>(_pinnable); if (obj is string text && _length == text.Length) { return text; } } fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal unsafe ref T DangerousGetPinnableReference() { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct Span<T> { public ref struct Enumerator { private readonly Span<T> _span; private int _index; public ref T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(Span<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly Pinnable<T> _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static Span<T> Empty => default(Span<T>); public unsafe ref T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable<T> Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(Span<T> left, Span<T> right) { return !(left == right); } [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator Span<T>(T[] array) { return new Span<T>(array); } public static implicit operator Span<T>(ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array) { if (array == null) { this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _length = array.Length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Span<T> Create(T[] array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(Span<T>); } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); int length = array.Length - start; return new Span<T>(Unsafe.As<Pinnable<T>>(array), byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe Span(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref T GetPinnableReference() { if (_length != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } return ref Unsafe.AsRef<T>(null); } public unsafe void Clear() { int length = _length; if (length == 0) { return; } UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * Unsafe.SizeOf<T>()); if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; byte* ptr = (byte*)byteOffset.ToPointer(); System.SpanHelpers.ClearLessThanPointerSized(ptr, byteLength); } else { System.SpanHelpers.ClearLessThanPointerSized(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), byteLength); } } else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * Unsafe.SizeOf<T>() / sizeof(IntPtr)); System.SpanHelpers.ClearPointerSizedWithReferences(ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength); } else { System.SpanHelpers.ClearPointerSizedWithoutReferences(ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength); } } public unsafe void Fill(T value) { int length = _length; if (length == 0) { return; } if (Unsafe.SizeOf<T>() == 1) { byte value2 = Unsafe.As<T, byte>(ref value); if (_pinnable == null) { IntPtr byteOffset = _byteOffset; Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), value2, (uint)length); } else { Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), value2, (uint)length); } return; } ref T source = ref DangerousGetPinnableReference(); int i; for (i = 0; i < (length & -8); i += 8) { Unsafe.Add(ref source, i) = value; Unsafe.Add(ref source, i + 1) = value; Unsafe.Add(ref source, i + 2) = value; Unsafe.Add(ref source, i + 3) = value; Unsafe.Add(ref source, i + 4) = value; Unsafe.Add(ref source, i + 5) = value; Unsafe.Add(ref source, i + 6) = value; Unsafe.Add(ref source, i + 7) = value; } if (i < (length & -4)) { Unsafe.Add(ref source, i) = value; Unsafe.Add(ref source, i + 1) = value; Unsafe.Add(ref source, i + 2) = value; Unsafe.Add(ref source, i + 3) = value; i += 4; } for (; i < length; i++) { Unsafe.Add(ref source, i) = value; } } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination._length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(Span<T> left, Span<T> right) { if (left._length == right._length) { return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public static implicit operator ReadOnlySpan<T>(Span<T> span) { return new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length); } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.Span<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new Span<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new Span<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal unsafe ref T DangerousGetPinnableReference() { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } } internal sealed class SpanDebugView<T> { private readonly T[] _array; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _array; public SpanDebugView(Span<T> span) { _array = span.ToArray(); } public SpanDebugView(ReadOnlySpan<T> span) { _array = span.ToArray(); } } internal static class SpanHelpers { internal struct ComparerComparable<T, TComparer> : IComparable<T> where TComparer : IComparer<T> { private readonly T _value; private readonly TComparer _comparer; public ComparerComparable(T value, TComparer comparer) { _value = value; _comparer = comparer; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(T other) { return _comparer.Compare(_value, other); } } [StructLayout(LayoutKind.Sequential, Size = 64)] private struct Reg64 { } [StructLayout(LayoutKind.Sequential, Size = 32)] private struct Reg32 { } [StructLayout(LayoutKind.Sequential, Size = 16)] private struct Reg16 { } public static class PerTypeValues<T> { public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferencesCore(typeof(T)); public static readonly T[] EmptyArray = new T[0]; public static readonly IntPtr ArrayAdjustment = MeasureArrayAdjustment(); private static IntPtr MeasureArrayAdjustment() { T[] array = new T[1]; return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<T>>(array).Data, ref array[0]); } } private const ulong XorPowerOfTwoToHighByte = 283686952306184uL; private const ulong XorPowerOfTwoToHighChar = 4295098372uL; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { if (comparable == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparable); } return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable); } public static int BinarySearch<T, TComparable>(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable<T> { int num = 0; int num2 = length - 1; while (num <= num2) { int num3 = num2 + num >>> 1; int num4 = comparable.CompareTo(Unsafe.Add(ref spanStart, num3)); if (num4 == 0) { return num3; } if (num4 > 0) { num = num3 + 1; } else { num2 = num3 - 1; } } return ~num; } public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num2), value2, num3); if (num4 == -1) { break; } num2 += num4; if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num2 + 1), ref second, num)) { return num2; } num2++; } return -1; } public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } int num = -1; for (int i = 0; i < valueLength; i++) { int num2 = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if ((uint)num2 < (uint)num) { num = num2; searchSpaceLength = num2; if (num == 0) { break; } } } return num; } public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } int num = -1; for (int i = 0; i < valueLength; i++) { int num2 = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if (num2 > num) { num = num2; } } return num; } public unsafe static int IndexOf(ref byte searchSpace, byte value, int length) { IntPtr intPtr = (IntPtr)0; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1); intPtr2 = (IntPtr)((Vector<byte>.Count - num) & (Vector<byte>.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) { goto IL_0242; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { goto IL_024a; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { goto IL_0258; } if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6)) { if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7)) { break; } intPtr += 8; continue; } return (int)(void*)(intPtr + 6); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 4); } goto IL_0266; } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) { goto IL_0242; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { goto IL_024a; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { goto IL_0258; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { goto IL_0266; } intPtr += 4; } while ((void*)intPtr2 != null) { intPtr2 -= 1; if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) { intPtr += 1; continue; } goto IL_0242; } if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) { intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector<byte>.Count - 1)); Vector<byte> vector = GetVector(value); for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector<byte>.Count) { Vector<byte> vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr))); if (!Vector<byte>.Zero.Equals(vector2)) { return (int)(void*)intPtr + LocateFirstFoundByte(vector2); } } if ((int)(void*)intPtr < length) { intPtr2 = (IntPtr)(length - (int)(void*)intPtr); continue; } } return -1; IL_0266: return (int)(void*)(intPtr + 3); IL_0242: return (int)(void*)intPtr; IL_0258: return (int)(void*)(intPtr + 2); IL_024a: return (int)(void*)(intPtr + 1); } return (int)(void*)(intPtr + 7); } public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = LastIndexOf(ref searchSpace, value2, num3); if (num4 == -1) { break; } if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num)) { return num4; } num2 += num3 - num4; } return -1; } public unsafe static int LastIndexOf(ref byte searchSpace, byte value, int length) { IntPtr intPtr = (IntPtr)length; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1); intPtr2 = (IntPtr)(((length & (Vector<byte>.Count - 1)) + num) & (Vector<byte>.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; intPtr -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7)) { break; } if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) { continue; } goto IL_0254; } goto IL_025c; } goto IL_026a; } goto IL_0278; } return (int)(void*)(intPtr + 4); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 6); } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; intPtr -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { goto IL_0278; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { goto IL_026a; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { goto IL_025c; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) { goto IL_0254; } } while ((void*)intPtr2 != null) { intPtr2 -= 1; intPtr -= 1; if (val
plugins/Buttplug.Client.Connectors.WebsocketConnector.dll
Decompiled 2 years agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Buttplug.Core; using Buttplug.Core.Messages; using vtortola.WebSockets; using vtortola.WebSockets.Rfc6455; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Nonpolynomial Labs, LLC")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright Nonpolynomial Labs, LLC")] [assembly: AssemblyDescription("Websocket Connection Capabilities for Buttplug Clients. (.Net Standard 2.0+)")] [assembly: AssemblyFileVersion("3.0.1.0")] [assembly: AssemblyInformationalVersion("3.0.1+4dbc02a18cc93accd82c59632d17bf779d09bf97")] [assembly: AssemblyProduct("Buttplug.Client.Connectors.WebsocketConnector")] [assembly: AssemblyTitle("Buttplug.Client.Connectors.WebsocketConnector")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/buttplugio/buttplug-csharp")] [assembly: AssemblyVersion("3.0.1.0")] namespace Buttplug.Client.Connectors.WebsocketConnector; public class ButtplugWebsocketConnector : ButtplugRemoteJSONConnector, IButtplugClientConnector { private WebSocketClient _wsClient; private WebSocket _ws; private readonly SynchronizationContext _owningDispatcher = SynchronizationContext.Current ?? new SynchronizationContext(); private readonly Uri _uri; private Channel<string> _channel = Channel.CreateBounded<string>(256); private Task _readTask; public bool Connected { get { WebSocket ws = _ws; if (ws == null) { return false; } return ws.IsConnected; } } public event EventHandler Disconnected; public ButtplugWebsocketConnector(Uri uri) { _uri = uri; } public async Task ConnectAsync(CancellationToken token = default(CancellationToken)) { if (_ws != null) { throw new ButtplugHandshakeException("Websocket connector is already connected.", 0u, (Exception)null); } WebSocketListenerOptions val = new WebSocketListenerOptions { SendBufferSize = 8192, BufferManager = BufferManager.CreateBufferManager(819200L, 8192), PingTimeout = Timeout.InfiniteTimeSpan, PingMode = (PingMode)0 }; WebSocketFactoryCollectionExtensions.RegisterRfc6455(val.Standards, (Action<WebSocketFactoryRfc6455>)null); _wsClient = new WebSocketClient(val); try { _ws = await _wsClient.ConnectAsync(_uri, token).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception ex) { throw new ButtplugClientConnectorException("Websocket Connection Exception! See Inner Exception", ex); } _readTask = Task.Run(async delegate { await RunClientLoop(token).ConfigureAwait(continueOnCapturedContext: false); }, token); } public async Task DisconnectAsync(CancellationToken token = default(CancellationToken)) { try { WebSocket ws = _ws; if (ws != null && ws.IsConnected) { await _ws.CloseAsync().ConfigureAwait(continueOnCapturedContext: false); } } catch { } await _readTask.ConfigureAwait(continueOnCapturedContext: false); } public async Task<ButtplugMessage> SendAsync(ButtplugMessage msg, CancellationToken token) { var (item, msgPromise) = ((ButtplugRemoteJSONConnector)this).PrepareMessage(msg); await _channel.Writer.WriteAsync(item); return await msgPromise.ConfigureAwait(continueOnCapturedContext: false); } private async Task RunClientLoop(CancellationToken token) { _ = 4; try { UTF8Encoding utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); Task<WebSocketMessageReadStream> readTask = _ws.ReadMessageAsync(token); Task<string> writeTask = _channel.Reader.ReadAsync(token).AsTask(); while (_ws.IsConnected && !token.IsCancellationRequested) { await Task.WhenAny(new Task[2] { readTask, writeTask }); if (readTask.IsCompleted) { WebSocketMessageReadStream val = await readTask.ConfigureAwait(continueOnCapturedContext: false); if (val == null) { break; } if ((int)val.MessageType == 1) { string text = string.Empty; using (StreamReader reader = new StreamReader((Stream)(object)val, utf8NoBom)) { text = await reader.ReadToEndAsync(); } ((ButtplugRemoteJSONConnector)this).ReceiveMessages(text); } readTask = _ws.ReadMessageAsync(token); continue; } if (readTask.IsCanceled) { break; } if (writeTask.IsCompleted) { try { string text2 = await writeTask.ConfigureAwait(continueOnCapturedContext: false); if (text2 != null) { WebSocket ws = _ws; if (ws != null && ws.IsConnected) { await WebSocketStringExtensions.WriteStringAsync(_ws, text2, token).ConfigureAwait(continueOnCapturedContext: false); writeTask = _channel.Reader.ReadAsync(token).AsTask(); continue; } } } catch (WebSocketException val2) { WebSocketException val3 = val2; throw new ButtplugClientConnectorException("Websocket Client Read Error", (Exception)(object)val3); } break; } if (writeTask.IsCanceled) { Console.WriteLine("Write cancelled"); } } } catch (Exception) { } finally { _ws.CloseAsync().Dispose(); _ws = null; _owningDispatcher.Send(delegate { ((ButtplugRemoteJSONConnector)this).Dispose(); }, null); _owningDispatcher.Send(delegate { this.Disconnected?.Invoke(this, EventArgs.Empty); }, null); } } void IButtplugClientConnector.add_MessageReceived(EventHandler<MessageReceivedEventArgs> value) { ((ButtplugRemoteJSONConnector)this).MessageReceived += value; } void IButtplugClientConnector.remove_MessageReceived(EventHandler<MessageReceivedEventArgs> value) { ((ButtplugRemoteJSONConnector)this).MessageReceived -= value; } void IButtplugClientConnector.add_InvalidMessageReceived(EventHandler<ButtplugExceptionEventArgs> value) { ((ButtplugRemoteJSONConnector)this).InvalidMessageReceived += value; } void IButtplugClientConnector.remove_InvalidMessageReceived(EventHandler<ButtplugExceptionEventArgs> value) { ((ButtplugRemoteJSONConnector)this).InvalidMessageReceived -= value; } }
plugins/Buttplug.dll
Decompiled 2 years agousing System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using Buttplug.Core; using Buttplug.Core.Messages; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Buttplug.Test")] [assembly: InternalsVisibleTo("Buttplug.Client.Test")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Nonpolynomial Labs, LLC")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright Nonpolynomial Labs, LLC")] [assembly: AssemblyDescription("Buttplug Sex Toy Control Library. Contains Core (messages, errors, etc), and Client components. Server can be found in Buttplug.FFI.Server (.Net Standard 2.0+)")] [assembly: AssemblyFileVersion("3.0.1.0")] [assembly: AssemblyInformationalVersion("3.0.1+4dbc02a18cc93accd82c59632d17bf779d09bf97")] [assembly: AssemblyProduct("Buttplug")] [assembly: AssemblyTitle("Buttplug")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/buttplugio/buttplug-csharp")] [assembly: AssemblyVersion("3.0.1.0")] namespace Buttplug.Core { public static class ButtplugConsts { public const uint SystemMsgId = 0u; public const uint DefaultMsgId = 1u; public const uint CurrentSpecVersion = 3u; } public class ButtplugDeviceException : ButtplugException { public ButtplugDeviceException(string message, uint id = 0u, Exception inner = null) : base(message, Error.ErrorClass.ERROR_DEVICE, id, inner) { } } public class ButtplugException : Exception { public Error ButtplugErrorMessage { get; } public static ButtplugException FromError(Error msg) { return msg.ErrorCode switch { Error.ErrorClass.ERROR_DEVICE => new ButtplugDeviceException(msg.ErrorMessage, msg.Id), Error.ErrorClass.ERROR_INIT => new ButtplugHandshakeException(msg.ErrorMessage, msg.Id), Error.ErrorClass.ERROR_MSG => new ButtplugMessageException(msg.ErrorMessage, msg.Id), Error.ErrorClass.ERROR_PING => new ButtplugPingException(msg.ErrorMessage, msg.Id), Error.ErrorClass.ERROR_UNKNOWN => new ButtplugException(msg.ErrorMessage, msg.Id), _ => new ButtplugException(msg.ErrorMessage, msg.Id), }; } public ButtplugException(string message, uint id = 0u, Exception inner = null) : this(message, Error.ErrorClass.ERROR_UNKNOWN, id, inner) { } public ButtplugException(string message, Error.ErrorClass err = Error.ErrorClass.ERROR_UNKNOWN, uint id = 0u, Exception inner = null) : base(message, inner) { ButtplugErrorMessage = new Error(message, err, id); } } public class ButtplugExceptionEventArgs : EventArgs { public ButtplugException Exception { get; } public ButtplugExceptionEventArgs(ButtplugException ex) { Exception = ex; } } public class ButtplugHandshakeException : ButtplugException { public ButtplugHandshakeException(string message, uint id = 0u, Exception inner = null) : base(message, Error.ErrorClass.ERROR_INIT, id, inner) { } } public class ButtplugJsonMessageParser { private readonly Dictionary<string, Type> _messageTypes; private readonly JsonSerializerOptions _serializerOptions; public ButtplugJsonMessageParser() { _serializerOptions = new JsonSerializerOptions { IncludeFields = true }; _messageTypes = new Dictionary<string, Type>(); foreach (Type allMessageType in ButtplugUtils.GetAllMessageTypes()) { _messageTypes.Add(allMessageType.Name, allMessageType); } if (!_messageTypes.Any()) { throw new ButtplugMessageException("No message types available."); } } public IEnumerable<ButtplugMessage> Deserialize(string jsonMsg) { byte[] bytes = Encoding.UTF8.GetBytes(jsonMsg); List<ButtplugMessage> list = new List<ButtplugMessage>(); JsonDocument jsonDocument; try { jsonDocument = JsonDocument.Parse(bytes); } catch (JsonException ex) { throw new ButtplugMessageException("Not valid JSON: " + jsonMsg + " - " + ex.Message); } foreach (JsonElement item in jsonDocument.RootElement.EnumerateArray()) { string text = string.Empty; foreach (JsonProperty item2 in item.EnumerateObject()) { text = item2.Name; } if (!_messageTypes.ContainsKey(text)) { throw new ButtplugMessageException(text + " is not a valid message class"); } list.Add(DeserializeAs(item, _messageTypes[text])); } return list; } private ButtplugMessage DeserializeAs(JsonElement obj, Type msgType) { if (!msgType.IsSubclassOf(typeof(ButtplugMessage))) { throw new ButtplugMessageException("Type " + msgType.Name + " is not a subclass of ButtplugMessage"); } if (msgType.Namespace != "Buttplug.Core.Messages") { throw new ButtplugMessageException("Type " + msgType.Name + " (" + msgType.Namespace + ") is not in the namespace of Buttplug.Core.Messages"); } string name = ButtplugMessage.GetName(msgType); try { return (ButtplugMessage)obj.GetProperty(name).Deserialize(msgType, _serializerOptions); } catch (InvalidCastException ex) { throw new ButtplugMessageException($"Could not create message for JSON {obj}: {ex.Message}"); } catch (JsonException ex2) { throw new ButtplugMessageException($"Could not create message for JSON {obj}: {ex2.Message}"); } } public string Serialize(ButtplugMessage msg) { if (msg.GetType().Namespace != "Buttplug.Core.Messages") { throw new ButtplugMessageException("Type " + msg.GetType().Name + " (" + msg.GetType().Namespace + ") is not in the namespace of Buttplug.Core.Messages"); } JsonNode jsonNode = ButtplugMessageToJObject(msg); if (jsonNode == null) { throw new ButtplugMessageException("Message cannot be converted to JSON.", msg.Id); } return new JsonArray { jsonNode }.ToJsonString(); } public string Serialize(IEnumerable<ButtplugMessage> msgs) { JsonArray jsonArray = new JsonArray(); foreach (ButtplugMessage msg in msgs) { JsonNode jsonNode = ButtplugMessageToJObject(msg); if (jsonNode != null) { jsonArray.Add(jsonNode); } } if (!jsonArray.Any()) { throw new ButtplugMessageException("No messages serialized."); } return jsonArray.ToJsonString(); } private JsonNode ButtplugMessageToJObject(ButtplugMessage msg) { return new JsonObject(new List<KeyValuePair<string, JsonNode>> { new KeyValuePair<string, JsonNode>(msg.Name, JsonSerializer.SerializeToNode(msg, msg.GetType(), _serializerOptions)) }); } } public class ButtplugMessageException : ButtplugException { public ButtplugMessageException(string message, uint id = 0u, Exception inner = null) : base(message, Error.ErrorClass.ERROR_MSG, id, inner) { } } public class ButtplugPingException : ButtplugException { public ButtplugPingException(string message, uint id = 0u, Exception inner = null) : base(message, Error.ErrorClass.ERROR_PING, id, inner) { } } public static class ButtplugUtils { public static IEnumerable<Type> GetAllMessageTypes() { IEnumerable<Type> enumerable; try { enumerable = Assembly.GetAssembly(typeof(ButtplugMessage))?.GetTypes(); } catch (ReflectionTypeLoadException ex) { enumerable = ex.Types; } return (enumerable ?? throw new InvalidOperationException()).Where((Type type) => type != null && type.IsClass && type.IsSubclassOf(typeof(ButtplugMessage)) && type != typeof(ButtplugDeviceMessage)); } [DebuggerStepThrough] public static void ArgumentNotNull(object argument, string argumentName) { if (argument == null) { throw new ArgumentNullException(argumentName); } } public static Type GetMessageType(string messageName) { return Type.GetType("Buttplug.Core.Messages." + messageName); } } } namespace Buttplug.Core.Messages { public class ButtplugDeviceMessage : ButtplugMessage { [JsonRequired] public uint DeviceIndex { get; set; } public ButtplugDeviceMessage(uint id = 1u, uint deviceIndex = uint.MaxValue) : base(id) { DeviceIndex = deviceIndex; } } public abstract class ButtplugMessage { private static readonly Dictionary<Type, ButtplugMessageMetadata> _metadataCache = new Dictionary<Type, ButtplugMessageMetadata>(); [JsonRequired] public uint Id { get; set; } [JsonIgnore] public string Name => GetName(GetType()); protected ButtplugMessage(uint id) { Id = id; } private static T GetMessageAttribute<T>(Type msgType, Func<ButtplugMessageMetadata, T> func) { ButtplugUtils.ArgumentNotNull(msgType, "msgType"); ButtplugUtils.ArgumentNotNull(func, "func"); if (!msgType.IsSubclassOf(typeof(ButtplugMessage))) { throw new ArgumentException("Argument " + msgType.Name + " must be a subclass of ButtplugMessage"); } if (_metadataCache.ContainsKey(msgType)) { return func(_metadataCache[msgType]); } Attribute[] customAttributes = Attribute.GetCustomAttributes(msgType); for (int i = 0; i < customAttributes.Length; i++) { if (customAttributes[i] is ButtplugMessageMetadata buttplugMessageMetadata) { _metadataCache[msgType] = buttplugMessageMetadata; return func(buttplugMessageMetadata); } } throw new ArgumentException($"Type {msgType} does not have ButtplugMessageMetadata Attributes"); } public static string GetName(Type msgType) { return GetMessageAttribute(msgType, (ButtplugMessageMetadata md) => md.Name); } } public interface IButtplugMessageOutgoingOnly { } public interface IButtplugDeviceInfoMessage { string DeviceName { get; } uint DeviceIndex { get; } DeviceMessageAttributes DeviceMessages { get; } string DeviceDisplayName { get; } uint DeviceMessageTimingGap { get; } } [AttributeUsage(AttributeTargets.Class)] public class ButtplugMessageMetadata : Attribute { public string Name { get; } public ButtplugMessageMetadata(string name) { Name = name; } } [JsonConverter(typeof(JsonStringEnumConverter))] public enum ActuatorType { [EnumMember(Value = "Unknown")] Unknown, [EnumMember(Value = "Vibrate")] Vibrate, [EnumMember(Value = "Rotate")] Rotate, [EnumMember(Value = "Oscillate")] Oscillate, [EnumMember(Value = "Constrict")] Constrict, [EnumMember(Value = "Inflate")] Inflate, [EnumMember(Value = "Position")] Position } [JsonConverter(typeof(JsonStringEnumConverter))] public enum SensorType { [EnumMember(Value = "Unknown")] Unknown, [EnumMember(Value = "Battery")] Battery, [EnumMember(Value = "RSSI")] RSSI, [EnumMember(Value = "Button")] Button, [EnumMember(Value = "Pressure")] Pressure } public class GenericDeviceMessageAttributes { [JsonIgnore] internal uint _index; [JsonRequired] public string FeatureDescriptor; [JsonRequired] [JsonConverter(typeof(JsonStringEnumConverter))] public ActuatorType ActuatorType; [JsonRequired] public uint StepCount; [JsonIgnore] public uint Index => _index; } public class SensorDeviceMessageAttributes { [JsonIgnore] internal uint _index; [JsonRequired] public string FeatureDescriptor; [JsonRequired] [JsonConverter(typeof(JsonStringEnumConverter))] public SensorType SensorType; [JsonRequired] public uint[][] SensorRange; [JsonIgnore] public uint Index => _index; } public class RawDeviceMessageAttributes { public readonly string[] Endpoints; } public class NullDeviceMessageAttributes { } public class DeviceMessageAttributes { public GenericDeviceMessageAttributes[] ScalarCmd; public GenericDeviceMessageAttributes[] RotateCmd; public GenericDeviceMessageAttributes[] LinearCmd; public SensorDeviceMessageAttributes[] SensorReadCmd; public SensorDeviceMessageAttributes[] SensorSubscribeCmd; public readonly RawDeviceMessageAttributes[] RawReadCmd; public readonly RawDeviceMessageAttributes[] RawWriteCmd; public readonly RawDeviceMessageAttributes[] RawSubscribeCmd; public readonly NullDeviceMessageAttributes StopDeviceCmd; [OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { ScalarCmd?.Select((GenericDeviceMessageAttributes x, int i) => (x, i)).ToList().ForEach(delegate((GenericDeviceMessageAttributes x, int i) x) { x.x._index = (uint)x.i; }); RotateCmd?.Select((GenericDeviceMessageAttributes x, int i) => (x, i)).ToList().ForEach(delegate((GenericDeviceMessageAttributes x, int i) x) { x.x._index = (uint)x.i; }); LinearCmd?.Select((GenericDeviceMessageAttributes x, int i) => (x, i)).ToList().ForEach(delegate((GenericDeviceMessageAttributes x, int i) x) { x.x._index = (uint)x.i; }); SensorReadCmd?.Select((SensorDeviceMessageAttributes x, int i) => (x, i)).ToList().ForEach(delegate((SensorDeviceMessageAttributes x, int i) x) { x.x._index = (uint)x.i; }); SensorSubscribeCmd?.Select((SensorDeviceMessageAttributes x, int i) => (x, i)).ToList().ForEach(delegate((SensorDeviceMessageAttributes x, int i) x) { x.x._index = (uint)x.i; }); } } public class MessageReceivedEventArgs : EventArgs { public ButtplugMessage Message { get; } public MessageReceivedEventArgs(ButtplugMessage message) { Message = message; } } [ButtplugMessageMetadata("Ok")] public class Ok : ButtplugMessage, IButtplugMessageOutgoingOnly { public Ok(uint id) : base(id) { } } [ButtplugMessageMetadata("Test")] public class Test : ButtplugMessage { private string _testStringImpl; [JsonRequired] public string TestString { get { return _testStringImpl; } set { if (value == "Error") { throw new ArgumentException("Got an Error Message"); } _testStringImpl = value; } } public Test(string str, uint id = 1u) : base(id) { TestString = str; } } [ButtplugMessageMetadata("Error")] public class Error : ButtplugMessage, IButtplugMessageOutgoingOnly { public enum ErrorClass { ERROR_UNKNOWN, ERROR_INIT, ERROR_PING, ERROR_MSG, ERROR_DEVICE } [JsonRequired] public ErrorClass ErrorCode; [JsonRequired] public string ErrorMessage; public Error(string errorMessage, ErrorClass errorCode, uint id) : base(id) { ErrorMessage = errorMessage; ErrorCode = errorCode; } } public class MessageAttributes : IEquatable<MessageAttributes> { [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public uint? FeatureCount; public MessageAttributes() { } public MessageAttributes(uint featureCount) { FeatureCount = featureCount; } public bool Equals(MessageAttributes attrs) { return FeatureCount == attrs.FeatureCount; } } public class DeviceMessageInfo : IButtplugDeviceInfoMessage { [JsonRequired] public string DeviceName; [JsonRequired] public uint DeviceIndex; public readonly string DeviceDisplayName; public readonly uint DeviceMessageTimingGap; [JsonRequired] public DeviceMessageAttributes DeviceMessages; string IButtplugDeviceInfoMessage.DeviceName => DeviceName; uint IButtplugDeviceInfoMessage.DeviceIndex => DeviceIndex; DeviceMessageAttributes IButtplugDeviceInfoMessage.DeviceMessages => DeviceMessages; string IButtplugDeviceInfoMessage.DeviceDisplayName => DeviceDisplayName; uint IButtplugDeviceInfoMessage.DeviceMessageTimingGap => DeviceMessageTimingGap; public DeviceMessageInfo(uint deviceIndex, string deviceName, DeviceMessageAttributes deviceMessages) { DeviceName = deviceName; DeviceIndex = deviceIndex; DeviceMessages = deviceMessages; } } [ButtplugMessageMetadata("DeviceList")] public class DeviceList : ButtplugMessage, IButtplugMessageOutgoingOnly { [JsonRequired] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public DeviceMessageInfo[] Devices = new DeviceMessageInfo[0]; public DeviceList(DeviceMessageInfo[] devices, uint id) : base(id) { Devices = devices; } internal DeviceList() : base(0u) { } } [ButtplugMessageMetadata("DeviceAdded")] public class DeviceAdded : ButtplugDeviceMessage, IButtplugMessageOutgoingOnly, IButtplugDeviceInfoMessage { [JsonRequired] public string DeviceName; public readonly string DeviceDisplayName; public readonly uint DeviceMessageTimingGap; [JsonRequired] public DeviceMessageAttributes DeviceMessages; string IButtplugDeviceInfoMessage.DeviceName => DeviceName; uint IButtplugDeviceInfoMessage.DeviceIndex => base.DeviceIndex; DeviceMessageAttributes IButtplugDeviceInfoMessage.DeviceMessages => DeviceMessages; string IButtplugDeviceInfoMessage.DeviceDisplayName => DeviceDisplayName; uint IButtplugDeviceInfoMessage.DeviceMessageTimingGap => DeviceMessageTimingGap; public DeviceAdded(uint deviceIndex, string deviceName, DeviceMessageAttributes deviceMessages) : base(0u, deviceIndex) { DeviceName = deviceName; DeviceMessages = deviceMessages; } internal DeviceAdded() : base(0u) { } } [ButtplugMessageMetadata("DeviceRemoved")] public class DeviceRemoved : ButtplugMessage, IButtplugMessageOutgoingOnly { [JsonRequired] public uint DeviceIndex; public DeviceRemoved(uint deviceIndex) : base(0u) { DeviceIndex = deviceIndex; } } [ButtplugMessageMetadata("RequestDeviceList")] public class RequestDeviceList : ButtplugMessage { public RequestDeviceList(uint id = 1u) : base(id) { } } [ButtplugMessageMetadata("StartScanning")] public class StartScanning : ButtplugMessage { public StartScanning(uint id = 1u) : base(id) { } } [ButtplugMessageMetadata("StopScanning")] public class StopScanning : ButtplugMessage { public StopScanning(uint id = 1u) : base(id) { } } [ButtplugMessageMetadata("ScanningFinished")] public class ScanningFinished : ButtplugMessage, IButtplugMessageOutgoingOnly { public ScanningFinished() : base(0u) { } } [ButtplugMessageMetadata("RequestServerInfo")] public class RequestServerInfo : ButtplugMessage { [JsonRequired] public string ClientName; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public uint MessageVersion; public RequestServerInfo(string clientName, uint id = 1u, uint messageVersion = 3u) : base(id) { ClientName = clientName; MessageVersion = messageVersion; } } [ButtplugMessageMetadata("ServerInfo")] public class ServerInfo : ButtplugMessage, IButtplugMessageOutgoingOnly { [JsonRequired] public uint MessageVersion; [JsonRequired] public uint MaxPingTime; [JsonRequired] public string ServerName; public ServerInfo(string serverName, uint messageVersion, uint maxPingTime, uint id = 1u) : base(id) { ServerName = serverName; MessageVersion = messageVersion; MaxPingTime = maxPingTime; } } [ButtplugMessageMetadata("Ping")] public class Ping : ButtplugMessage { public Ping(uint id = 1u) : base(id) { } } public class GenericMessageSubcommand { [JsonRequired] public uint Index; protected GenericMessageSubcommand(uint index) { Index = index; } } [ButtplugMessageMetadata("ScalarCmd")] public class ScalarCmd : ButtplugDeviceMessage { public class ScalarSubcommand : GenericMessageSubcommand { private double _scalarImpl; public readonly ActuatorType ActuatorType; [JsonRequired] public double Scalar { get { return _scalarImpl; } set { if (value < 0.0) { throw new ArgumentException("ScalarCmd value cannot be less than 0!"); } if (value > 1.0) { throw new ArgumentException("ScalarCmd value cannot be greater than 1!"); } _scalarImpl = value; } } public ScalarSubcommand(uint index, double scalar, ActuatorType actuatorType) : base(index) { Scalar = scalar; ActuatorType = actuatorType; } } [JsonRequired] public List<ScalarSubcommand> Scalars; [JsonConstructor] public ScalarCmd(uint deviceIndex, List<ScalarSubcommand> scalars, uint id = 1u) : base(id, deviceIndex) { Scalars = scalars; } public ScalarCmd(List<ScalarSubcommand> scalars) : this(uint.MaxValue, scalars) { } } [ButtplugMessageMetadata("RotateCmd")] public class RotateCmd : ButtplugDeviceMessage { public class RotateSubcommand : GenericMessageSubcommand { private double _speedImpl; [JsonRequired] public bool Clockwise; [JsonRequired] public double Speed { get { return _speedImpl; } set { if (value < 0.0) { throw new ArgumentException("RotateCmd Speed cannot be less than 0!"); } if (value > 1.0) { throw new ArgumentException("RotateCmd Speed cannot be greater than 1!"); } _speedImpl = value; } } public RotateSubcommand(uint index, double speed, bool clockwise) : base(index) { Speed = speed; Clockwise = clockwise; } } [JsonRequired] public List<RotateSubcommand> Rotations; public static RotateCmd Create(double speed, bool clockwise, uint cmdCount) { return Create(uint.MaxValue, 1u, Enumerable.Repeat((speed, clockwise), (int)cmdCount)); } public static RotateCmd Create(IEnumerable<(double speed, bool clockwise)> cmds) { return Create(uint.MaxValue, 1u, cmds); } public static RotateCmd Create(uint deviceIndex, uint msgId, double speed, bool clockwise, uint cmdCount) { return Create(deviceIndex, msgId, Enumerable.Repeat((speed, clockwise), (int)cmdCount)); } public static RotateCmd Create(uint deviceIndex, uint msgId, IEnumerable<(double speed, bool clockwise)> cmds) { List<RotateSubcommand> list = new List<RotateSubcommand>(cmds.Count()); uint num = 0u; foreach (var (speed, clockwise) in cmds) { list.Add(new RotateSubcommand(num, speed, clockwise)); num++; } return new RotateCmd(deviceIndex, list, msgId); } [JsonConstructor] public RotateCmd(uint deviceIndex, List<RotateSubcommand> rotations, uint id = 1u) : base(id, deviceIndex) { Rotations = rotations; } public RotateCmd(List<RotateSubcommand> rotations) : this(uint.MaxValue, rotations) { } } [ButtplugMessageMetadata("LinearCmd")] public class LinearCmd : ButtplugDeviceMessage { public class VectorSubcommand : GenericMessageSubcommand { private double _positionImpl; [JsonRequired] public uint Duration; [JsonRequired] public double Position { get { return _positionImpl; } set { if (value < 0.0) { throw new ArgumentException("LinearCmd Speed cannot be less than 0!"); } if (value > 1.0) { throw new ArgumentException("LinearCmd Speed cannot be greater than 1!"); } _positionImpl = value; } } public VectorSubcommand(uint index, uint duration, double position) : base(index) { Duration = duration; Position = position; } } [JsonRequired] public List<VectorSubcommand> Vectors; public static LinearCmd Create(uint duration, double position, uint cmdCount) { return Create(uint.MaxValue, 1u, Enumerable.Repeat((duration, position), (int)cmdCount)); } public static LinearCmd Create(uint deviceIndex, uint msgId, uint duration, double position, uint cmdCount) { return Create(deviceIndex, msgId, Enumerable.Repeat((duration, position), (int)cmdCount)); } public static LinearCmd Create(IEnumerable<(uint duration, double position)> cmds) { return Create(uint.MaxValue, 1u, cmds); } public static LinearCmd Create(uint deviceIndex, uint msgId, IEnumerable<(uint duration, double position)> cmds) { List<VectorSubcommand> list = new List<VectorSubcommand>(cmds.Count()); uint num = 0u; foreach (var (duration, position) in cmds) { list.Add(new VectorSubcommand(num, duration, position)); num++; } return new LinearCmd(deviceIndex, list, msgId); } [JsonConstructor] public LinearCmd(uint deviceIndex, List<VectorSubcommand> vectors, uint id = 1u) : base(id, deviceIndex) { Vectors = vectors; } public LinearCmd(List<VectorSubcommand> vectors) : this(uint.MaxValue, vectors) { } } [ButtplugMessageMetadata("StopDeviceCmd")] public class StopDeviceCmd : ButtplugDeviceMessage { public StopDeviceCmd(uint deviceIndex = uint.MaxValue, uint id = 1u) : base(id, deviceIndex) { } } [ButtplugMessageMetadata("StopAllDevices")] public class StopAllDevices : ButtplugMessage { public StopAllDevices(uint id = 1u) : base(id) { } } [ButtplugMessageMetadata("SensorReadCmd")] public class SensorReadCmd : ButtplugDeviceMessage { [JsonRequired] public uint SensorIndex; [JsonRequired] public SensorType SensorType; [JsonConstructor] public SensorReadCmd(uint deviceIndex, uint sensorIndex, SensorType sensorType, uint id = 1u) : base(id, deviceIndex) { SensorIndex = sensorIndex; SensorType = sensorType; } public SensorReadCmd(uint sensorIndex, SensorType sensorType) : this(uint.MaxValue, sensorIndex, sensorType) { } } [ButtplugMessageMetadata("SensorReading")] public class SensorReading : ButtplugDeviceMessage { [JsonRequired] public uint SensorIndex; [JsonRequired] public SensorType SensorType; [JsonRequired] public List<int> data; } } namespace Buttplug.Client { public class ButtplugClient : IDisposable { protected Timer _pingTimer; internal ButtplugClientMessageHandler _handler; private readonly ConcurrentDictionary<uint, ButtplugClientDevice> _devices = new ConcurrentDictionary<uint, ButtplugClientDevice>(); private IButtplugClientConnector _connector; public string Name { get; } public ButtplugClientDevice[] Devices => _devices.Values.ToArray(); public bool Connected => _connector?.Connected ?? false; public event EventHandler<DeviceAddedEventArgs> DeviceAdded; public event EventHandler<DeviceRemovedEventArgs> DeviceRemoved; public event EventHandler<ButtplugExceptionEventArgs> ErrorReceived; public event EventHandler ScanningFinished; public event EventHandler PingTimeout; public event EventHandler ServerDisconnect; public ButtplugClient(string clientName) { Name = clientName; } public async Task ConnectAsync(IButtplugClientConnector connector, CancellationToken token = default(CancellationToken)) { if (Connected) { throw new ButtplugHandshakeException("Client already connected to a server."); } ButtplugUtils.ArgumentNotNull(connector, "connector"); _connector = connector; _connector.Disconnected += delegate(object obj, EventArgs eventArgs) { this.ServerDisconnect?.Invoke(obj, eventArgs); }; _connector.InvalidMessageReceived += ConnectorErrorHandler; _connector.MessageReceived += MessageReceivedHandler; _devices.Clear(); _handler = new ButtplugClientMessageHandler(connector); await _connector.ConnectAsync(token).ConfigureAwait(continueOnCapturedContext: false); ButtplugMessage res = await _handler.SendMessageAsync(new RequestServerInfo(Name), token).ConfigureAwait(continueOnCapturedContext: false); if (!(res is ServerInfo si)) { if (res is Error e) { await DisconnectAsync().ConfigureAwait(continueOnCapturedContext: false); throw ButtplugException.FromError(e); } await DisconnectAsync().ConfigureAwait(continueOnCapturedContext: false); throw new ButtplugHandshakeException("Unrecognized message " + res.Name + " during handshake", res.Id); } if (si.MaxPingTime != 0) { _pingTimer?.Dispose(); _pingTimer = new Timer(OnPingTimer, null, 0, Convert.ToInt32(Math.Round((double)si.MaxPingTime / 2.0, 0))); } if (si.MessageVersion < 3) { await DisconnectAsync().ConfigureAwait(continueOnCapturedContext: false); throw new ButtplugHandshakeException($"Buttplug Server's schema version ({si.MessageVersion}) is less than the client's ({3u}). A newer server is required.", res.Id); } ButtplugMessage resp = await _handler.SendMessageAsync(new RequestDeviceList()).ConfigureAwait(continueOnCapturedContext: false); if (resp is DeviceList deviceList) { DeviceMessageInfo[] devices = deviceList.Devices; foreach (DeviceMessageInfo deviceMessageInfo in devices) { if (!_devices.ContainsKey(deviceMessageInfo.DeviceIndex)) { ButtplugClientDevice buttplugClientDevice = new ButtplugClientDevice(_handler, deviceMessageInfo); _devices[deviceMessageInfo.DeviceIndex] = buttplugClientDevice; this.DeviceAdded?.Invoke(this, new DeviceAddedEventArgs(buttplugClientDevice)); } } return; } await DisconnectAsync().ConfigureAwait(continueOnCapturedContext: false); if (resp is Error msg) { throw ButtplugException.FromError(msg); } throw new ButtplugHandshakeException("Received unknown response to DeviceList handshake query"); } public async Task DisconnectAsync() { if (Connected) { _connector.MessageReceived -= MessageReceivedHandler; await _connector.DisconnectAsync().ConfigureAwait(continueOnCapturedContext: false); this.ServerDisconnect?.Invoke(this, EventArgs.Empty); } } public async Task StartScanningAsync(CancellationToken token = default(CancellationToken)) { await _handler.SendMessageExpectOk(new StartScanning(), token).ConfigureAwait(continueOnCapturedContext: false); } public async Task StopScanningAsync(CancellationToken token = default(CancellationToken)) { await _handler.SendMessageExpectOk(new StopScanning(), token).ConfigureAwait(continueOnCapturedContext: false); } public async Task StopAllDevicesAsync(CancellationToken token = default(CancellationToken)) { await _handler.SendMessageExpectOk(new StopAllDevices(), token).ConfigureAwait(continueOnCapturedContext: false); } private void ConnectorErrorHandler(object sender, ButtplugExceptionEventArgs exception) { this.ErrorReceived?.Invoke(this, exception); } private async void MessageReceivedHandler(object sender, MessageReceivedEventArgs args) { ButtplugMessage message = args.Message; if (!(message is DeviceAdded deviceAdded)) { ButtplugClientDevice value; if (!(message is DeviceRemoved deviceRemoved)) { if (!(message is ScanningFinished)) { if (message is Error error) { this.ErrorReceived?.Invoke(this, new ButtplugExceptionEventArgs(ButtplugException.FromError(error))); if (error.ErrorCode == Error.ErrorClass.ERROR_PING) { this.PingTimeout?.Invoke(this, EventArgs.Empty); await DisconnectAsync().ConfigureAwait(continueOnCapturedContext: false); } } else { this.ErrorReceived?.Invoke(this, new ButtplugExceptionEventArgs(new ButtplugMessageException($"Got unhandled message: {message}", message.Id))); } } else { this.ScanningFinished?.Invoke(this, EventArgs.Empty); } } else if (!_devices.ContainsKey(deviceRemoved.DeviceIndex)) { this.ErrorReceived?.Invoke(this, new ButtplugExceptionEventArgs(new ButtplugDeviceException("Got device removed message for unknown device.", message.Id))); } else if (_devices.TryRemove(deviceRemoved.DeviceIndex, out value)) { this.DeviceRemoved?.Invoke(this, new DeviceRemovedEventArgs(value)); } } else { ButtplugClientDevice dev = new ButtplugClientDevice(_handler, deviceAdded); _devices.AddOrUpdate(deviceAdded.DeviceIndex, dev, (uint u, ButtplugClientDevice device) => dev); this.DeviceAdded?.Invoke(this, new DeviceAddedEventArgs(dev)); } } private async void OnPingTimer(object state) { try { await _handler.SendMessageExpectOk(new Ping()).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception inner) { this.ErrorReceived?.Invoke(this, new ButtplugExceptionEventArgs(new ButtplugPingException("Exception thrown during ping update", 0u, inner))); await DisconnectAsync().ConfigureAwait(continueOnCapturedContext: false); } } protected virtual void Dispose(bool disposing) { DisconnectAsync().GetAwaiter().GetResult(); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public class ButtplugClientConnectorException : ButtplugException { public ButtplugClientConnectorException(string message, Exception inner = null) : base(message, Error.ErrorClass.ERROR_UNKNOWN, 0u, inner) { } } public class ButtplugClientDevice { private readonly ButtplugClientMessageHandler _handler; public uint Index { get; } public string Name { get; } public string DisplayName { get; } public uint MessageTimingGap { get; } public DeviceMessageAttributes MessageAttributes { get; } public List<GenericDeviceMessageAttributes> VibrateAttributes => GenericAcutatorAttributes(ActuatorType.Vibrate); public List<GenericDeviceMessageAttributes> OscillateAttributes => GenericAcutatorAttributes(ActuatorType.Oscillate); public List<GenericDeviceMessageAttributes> RotateAttributes { get { if (MessageAttributes.RotateCmd != null) { return MessageAttributes.RotateCmd.ToList(); } return Enumerable.Empty<GenericDeviceMessageAttributes>().ToList(); } } public List<GenericDeviceMessageAttributes> LinearAttributes { get { if (MessageAttributes.LinearCmd != null) { return MessageAttributes.LinearCmd.ToList(); } return Enumerable.Empty<GenericDeviceMessageAttributes>().ToList(); } } public bool HasBattery => SensorReadAttributes(SensorType.Battery).Any(); internal ButtplugClientDevice(ButtplugClientMessageHandler handler, IButtplugDeviceInfoMessage devInfo) : this(handler, devInfo.DeviceIndex, devInfo.DeviceName, devInfo.DeviceMessages, devInfo.DeviceDisplayName, devInfo.DeviceMessageTimingGap) { ButtplugUtils.ArgumentNotNull(devInfo, "devInfo"); } internal ButtplugClientDevice(ButtplugClientMessageHandler handler, uint index, string name, DeviceMessageAttributes messages, string displayName, uint messageTimingGap) { ButtplugUtils.ArgumentNotNull(handler, "handler"); _handler = handler; Index = index; Name = name; MessageAttributes = messages; DisplayName = displayName; MessageTimingGap = messageTimingGap; } public List<GenericDeviceMessageAttributes> GenericAcutatorAttributes(ActuatorType actuator) { if (MessageAttributes.ScalarCmd != null) { return MessageAttributes.ScalarCmd.Where((GenericDeviceMessageAttributes x) => x.ActuatorType == actuator).ToList(); } return Enumerable.Empty<GenericDeviceMessageAttributes>().ToList(); } public async Task ScalarAsync(ScalarCmd.ScalarSubcommand command) { List<ScalarCmd.ScalarSubcommand> scalars = new List<ScalarCmd.ScalarSubcommand>(); GenericAcutatorAttributes(command.ActuatorType).ForEach(delegate(GenericDeviceMessageAttributes x) { scalars.Add(new ScalarCmd.ScalarSubcommand(x.Index, command.Scalar, command.ActuatorType)); }); if (!scalars.Any()) { throw new ButtplugDeviceException("Scalar command for device " + Name + " did not generate any commands. Are you sure the device supports the ActuatorType sent?"); } await _handler.SendMessageExpectOk(new ScalarCmd(Index, scalars)).ConfigureAwait(continueOnCapturedContext: false); } public async Task ScalarAsync(List<ScalarCmd.ScalarSubcommand> command) { if (!command.Any()) { throw new ArgumentException("Command List for ScalarAsync must have at least 1 command."); } await _handler.SendMessageExpectOk(new ScalarCmd(Index, command)).ConfigureAwait(continueOnCapturedContext: false); } public async Task VibrateAsync(double speed) { await ScalarAsync(new ScalarCmd.ScalarSubcommand(uint.MaxValue, speed, ActuatorType.Vibrate)); } public async Task VibrateAsync(IEnumerable<double> cmds) { List<GenericDeviceMessageAttributes> vibrateAttributes = VibrateAttributes; if (cmds.Count() > vibrateAttributes.Count()) { throw new ButtplugDeviceException($"Device {Name} only has {vibrateAttributes.Count()} vibrators, but {cmds.Count()} commands given."); } await ScalarAsync(vibrateAttributes.Select((GenericDeviceMessageAttributes x, int i) => new ScalarCmd.ScalarSubcommand(x.Index, cmds.ElementAt(i), ActuatorType.Vibrate)).ToList()).ConfigureAwait(continueOnCapturedContext: false); } public async Task VibrateAsync(IEnumerable<(uint, double)> cmds) { await ScalarAsync(cmds.Select(((uint, double) x) => new ScalarCmd.ScalarSubcommand(x.Item1, x.Item2, ActuatorType.Vibrate)).ToList()).ConfigureAwait(continueOnCapturedContext: false); } public async Task OscillateAsync(double speed) { await ScalarAsync(new ScalarCmd.ScalarSubcommand(uint.MaxValue, speed, ActuatorType.Oscillate)); } public async Task OscillateAsync(IEnumerable<double> cmds) { List<GenericDeviceMessageAttributes> oscillateAttributes = OscillateAttributes; if (cmds.Count() > oscillateAttributes.Count()) { throw new ButtplugDeviceException($"Device {Name} only has {oscillateAttributes.Count()} vibrators, but {cmds.Count()} commands given."); } await ScalarAsync(oscillateAttributes.Select((GenericDeviceMessageAttributes x, int i) => new ScalarCmd.ScalarSubcommand(x.Index, cmds.ElementAt(i), ActuatorType.Oscillate)).ToList()).ConfigureAwait(continueOnCapturedContext: false); } public async Task OscillateAsync(IEnumerable<(uint, double)> cmds) { await ScalarAsync(cmds.Select(((uint, double) x) => new ScalarCmd.ScalarSubcommand(x.Item1, x.Item2, ActuatorType.Oscillate)).ToList()).ConfigureAwait(continueOnCapturedContext: false); } public async Task RotateAsync(double speed, bool clockwise) { if (!RotateAttributes.Any()) { throw new ButtplugDeviceException("Device " + Name + " does not support rotation"); } RotateCmd rotateCmd = RotateCmd.Create(speed, clockwise, (uint)RotateAttributes.Count); rotateCmd.DeviceIndex = Index; await _handler.SendMessageExpectOk(rotateCmd).ConfigureAwait(continueOnCapturedContext: false); } public async Task RotateAsync(IEnumerable<(double, bool)> cmds) { if (!RotateAttributes.Any()) { throw new ButtplugDeviceException("Device " + Name + " does not support rotation"); } RotateCmd rotateCmd = RotateCmd.Create(cmds); rotateCmd.DeviceIndex = Index; await _handler.SendMessageExpectOk(rotateCmd).ConfigureAwait(continueOnCapturedContext: false); } public async Task LinearAsync(uint duration, double position) { if (!LinearAttributes.Any()) { throw new ButtplugDeviceException("Device " + Name + " does not support linear position"); } LinearCmd linearCmd = LinearCmd.Create(duration, position, (uint)LinearAttributes.Count); linearCmd.DeviceIndex = Index; await _handler.SendMessageExpectOk(linearCmd).ConfigureAwait(continueOnCapturedContext: false); } public async Task LinearAsync(IEnumerable<(uint, double)> cmds) { if (!LinearAttributes.Any()) { throw new ButtplugDeviceException("Device " + Name + " does not support linear position"); } LinearCmd linearCmd = LinearCmd.Create(cmds); linearCmd.DeviceIndex = Index; await _handler.SendMessageExpectOk(linearCmd).ConfigureAwait(continueOnCapturedContext: false); } public List<SensorDeviceMessageAttributes> SensorReadAttributes(SensorType sensor) { if (MessageAttributes.SensorReadCmd != null) { return MessageAttributes.SensorReadCmd.Where((SensorDeviceMessageAttributes x) => x.SensorType == sensor).ToList(); } return Enumerable.Empty<SensorDeviceMessageAttributes>().ToList(); } public async Task<double> BatteryAsync() { if (!HasBattery) { throw new ButtplugDeviceException("Device " + Name + " does not have battery capabilities."); } ButtplugMessage buttplugMessage = await _handler.SendMessageAsync(new SensorReadCmd(Index, SensorReadAttributes(SensorType.Battery).ElementAt(0).Index, SensorType.Battery)).ConfigureAwait(continueOnCapturedContext: false); if (!(buttplugMessage is SensorReading sensorReading)) { if (buttplugMessage is Error msg) { throw ButtplugException.FromError(msg); } throw new ButtplugMessageException("Message type " + buttplugMessage.Name + " not handled by BatteryAsync", buttplugMessage.Id); } return (double)sensorReading.data[0] / 100.0; } public async Task Stop() { await _handler.SendMessageExpectOk(new StopDeviceCmd(Index)).ConfigureAwait(continueOnCapturedContext: false); } } internal class ButtplugClientMessageHandler { private IButtplugClientConnector _connector; internal ButtplugClientMessageHandler(IButtplugClientConnector connector) { _connector = connector; } public async Task<ButtplugMessage> SendMessageAsync(ButtplugMessage msg, CancellationToken token = default(CancellationToken)) { if (!_connector.Connected) { throw new ButtplugClientConnectorException("Client not connected."); } return await _connector.SendAsync(msg, token).ConfigureAwait(continueOnCapturedContext: false); } public async Task SendMessageExpectOk(ButtplugMessage msg, CancellationToken token = default(CancellationToken)) { ButtplugMessage buttplugMessage = await SendMessageAsync(msg, token).ConfigureAwait(continueOnCapturedContext: false); if (!(buttplugMessage is Ok)) { if (buttplugMessage is Error msg2) { throw ButtplugException.FromError(msg2); } throw new ButtplugMessageException("Message type " + msg.Name + " not handled by SendMessageExpectOk", msg.Id); } } } public class ButtplugConnectorJSONParser { private readonly ButtplugJsonMessageParser _parser = new ButtplugJsonMessageParser(); public string Serialize(ButtplugMessage msg) { return _parser.Serialize(msg); } public string Serialize(ButtplugMessage[] msgs) { return _parser.Serialize(msgs); } public IEnumerable<ButtplugMessage> Deserialize(string msg) { return _parser.Deserialize(msg); } } public class ButtplugConnectorMessageSorter : IDisposable { private int _counter; private readonly ConcurrentDictionary<uint, TaskCompletionSource<ButtplugMessage>> _waitingMsgs = new ConcurrentDictionary<uint, TaskCompletionSource<ButtplugMessage>>(); public uint NextMsgId => Convert.ToUInt32(Interlocked.Increment(ref _counter)); public Task<ButtplugMessage> PrepareMessage(ButtplugMessage msg) { msg.Id = NextMsgId; TaskCompletionSource<ButtplugMessage> taskCompletionSource = new TaskCompletionSource<ButtplugMessage>(); _waitingMsgs.TryAdd(msg.Id, taskCompletionSource); return taskCompletionSource.Task; } public void CheckMessage(ButtplugMessage msg) { if (msg.Id == 0) { throw new ButtplugMessageException("Cannot sort message with System ID", msg.Id); } if (!_waitingMsgs.TryRemove(msg.Id, out var value)) { throw new ButtplugMessageException("Message with non-matching ID received.", msg.Id); } if (msg is Error msg2) { value.SetException(ButtplugException.FromError(msg2)); } else { value.SetResult(msg); } } protected virtual void Dispose(bool disposing) { foreach (TaskCompletionSource<ButtplugMessage> value in _waitingMsgs.Values) { value.TrySetException(new Exception("Sorter has been destroyed with live tasks still in queue.")); } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public class ButtplugRemoteJSONConnector : IDisposable { private readonly ButtplugConnectorJSONParser _jsonSerializer = new ButtplugConnectorJSONParser(); private readonly ButtplugConnectorMessageSorter _msgSorter = new ButtplugConnectorMessageSorter(); public event EventHandler<MessageReceivedEventArgs> MessageReceived; public event EventHandler<ButtplugExceptionEventArgs> InvalidMessageReceived; protected Tuple<string, Task<ButtplugMessage>> PrepareMessage(ButtplugMessage msg) { Task<ButtplugMessage> item = _msgSorter.PrepareMessage(msg); return new Tuple<string, Task<ButtplugMessage>>(_jsonSerializer.Serialize(msg), item); } protected void ReceiveMessages(string jSONMsg) { IEnumerable<ButtplugMessage> enumerable; try { enumerable = _jsonSerializer.Deserialize(jSONMsg); } catch (ButtplugMessageException ex) { this.InvalidMessageReceived?.Invoke(this, new ButtplugExceptionEventArgs(ex)); return; } foreach (ButtplugMessage item in enumerable) { if (item.Id == 0) { this.MessageReceived?.Invoke(this, new MessageReceivedEventArgs(item)); continue; } try { _msgSorter.CheckMessage(item); } catch (ButtplugMessageException ex2) { this.InvalidMessageReceived?.Invoke(this, new ButtplugExceptionEventArgs(ex2)); } } } protected virtual void Dispose(bool disposing) { _msgSorter.Dispose(); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public class DeviceAddedEventArgs { public readonly ButtplugClientDevice Device; public DeviceAddedEventArgs(ButtplugClientDevice device) { Device = device; } } public class DeviceRemovedEventArgs { public readonly ButtplugClientDevice Device; public DeviceRemovedEventArgs(ButtplugClientDevice device) { Device = device; } } public interface IButtplugClientConnector { bool Connected { get; } event EventHandler<MessageReceivedEventArgs> MessageReceived; event EventHandler<ButtplugExceptionEventArgs> InvalidMessageReceived; event EventHandler Disconnected; Task ConnectAsync(CancellationToken token = default(CancellationToken)); Task DisconnectAsync(CancellationToken token = default(CancellationToken)); Task<ButtplugMessage> SendAsync(ButtplugMessage msg, CancellationToken token = default(CancellationToken)); } }
plugins/deniszykov.WebSocketListener.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.IO.Pipes; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using vtortola.WebSockets.Async; using vtortola.WebSockets.Extensibility; using vtortola.WebSockets.Http; using vtortola.WebSockets.Rfc6455.Header; using vtortola.WebSockets.Tools; using vtortola.WebSockets.Transports; using vtortola.WebSockets.Transports.NamedPipes; using vtortola.WebSockets.Transports.Sockets; using vtortola.WebSockets.Transports.Tcp; using vtortola.WebSockets.Transports.UnixSockets; [assembly: AssemblyCompany("deniszykov")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("A lightweight and highly scalable asynchronous WebSocket listener for .NET Core, .NET and Mono.\r\nhttps://github.com/deniszykov/WebSocketListener")] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/deniszykov/WebSocketListener")] [assembly: AssemblyTitle("deniszykov.WebSocketListener")] [assembly: AssemblyInformationalVersion("4.2.16+74d663e28a86c4c5628270bc9d6458831d9a9702")] [assembly: AssemblyProduct("deniszykov.WebSocketListener")] [assembly: AssemblyFileVersion("4.2.16.0")] [assembly: AssemblyVersion("4.2.16.0")] namespace vtortola.WebSockets.Deflate { public sealed class WebSocketDeflateContext : IWebSocketMessageExtensionContext { public WebSocketMessageReadStream ExtendReader(WebSocketMessageReadStream message) { if (message == null) { throw new ArgumentNullException("message"); } if (message.Flags.Rsv1) { return new WebSocketDeflateReadStream(message); } return message; } public WebSocketMessageWriteStream ExtendWriter(WebSocketMessageWriteStream message) { if (message == null) { throw new ArgumentNullException("message"); } message.ExtensionFlags.Rsv1 = true; return new WebSocketDeflateWriteStream(message); } } public sealed class WebSocketDeflateExtension : IWebSocketMessageExtension { public const string EXTENSION_NAME = "permessage-deflate"; private static readonly ReadOnlyCollection<WebSocketExtensionOption> DefaultOptions = new ReadOnlyCollection<WebSocketExtensionOption>(new WebSocketExtensionOption[1] { new WebSocketExtensionOption("client_no_context_takeover") }); private static readonly WebSocketExtension DefaultResponse = new WebSocketExtension("permessage-deflate", DefaultOptions); public string Name => "permessage-deflate"; public bool TryNegotiate(WebSocketHttpRequest request, out WebSocketExtension extensionResponse, out IWebSocketMessageExtensionContext context) { if (request == null) { throw new ArgumentNullException("request"); } extensionResponse = DefaultResponse; context = new WebSocketDeflateContext(); return true; } public IWebSocketMessageExtension Clone() { return (WebSocketDeflateExtension)MemberwiseClone(); } public override string ToString() { return DefaultResponse.ToString(); } } public sealed class WebSocketDeflateReadStream : WebSocketMessageReadStream { private const int STATE_OPEN = 0; private const int STATE_CLOSED = 1; private const int STATE_DISPOSED = 2; private readonly WebSocketMessageReadStream innerStream; private readonly DeflateStream deflateStream; private volatile int state; public override WebSocketMessageType MessageType => innerStream.MessageType; public override WebSocketExtensionFlags Flags => innerStream.Flags; internal override WebSocketListenerOptions Options => innerStream.Options; public WebSocketDeflateReadStream([NotNull] WebSocketMessageReadStream innerStream) { if (innerStream == null) { throw new ArgumentNullException("innerStream"); } this.innerStream = innerStream; deflateStream = new DeflateStream(innerStream, CompressionMode.Decompress, leaveOpen: true); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return deflateStream.ReadAsync(buffer, offset, count, cancellationToken); } public override Task CloseAsync() { if (Interlocked.CompareExchange(ref state, 1, 0) != 0) { return TaskHelper.CompletedTask; } return innerStream.CloseAsync(); } protected override void Dispose(bool disposing) { if (Interlocked.Exchange(ref state, 2) != 2) { SafeEnd.Dispose(deflateStream); SafeEnd.Dispose(innerStream); } } } public sealed class WebSocketDeflateWriteStream : WebSocketMessageWriteStream { private static readonly byte[] FINAL_BYTE = new byte[1]; private const int STATE_OPEN = 0; private const int STATE_CLOSED = 1; private const int STATE_DISPOSED = 2; private readonly WebSocketMessageWriteStream innerStream; private readonly DeflateStream deflateStream; private volatile int state; internal override WebSocketListenerOptions Options => innerStream.Options; public WebSocketDeflateWriteStream([NotNull] WebSocketMessageWriteStream innerStream) { if (innerStream == null) { throw new ArgumentNullException("innerStream"); } this.innerStream = innerStream; deflateStream = new DeflateStream(innerStream, CompressionLevel.Optimal, leaveOpen: true); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset + count > buffer.Length) { throw new ArgumentOutOfRangeException("count"); } if (count == 0) { return Task.FromResult(0); } return deflateStream.WriteAsync(buffer, offset, count, cancellationToken); } public override async Task WriteAndCloseAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset + count > buffer.Length) { throw new ArgumentOutOfRangeException("count"); } if (count > 0) { await deflateStream.WriteAsync(buffer, offset, count, cancellationToken); } await CloseAsync().ConfigureAwait(continueOnCapturedContext: false); } public override async Task CloseAsync() { if (Interlocked.CompareExchange(ref state, 1, 0) == 0) { await deflateStream.FlushAsync(CancellationToken.None); deflateStream.Dispose(); await innerStream.WriteAndCloseAsync(FINAL_BYTE, 0, 1, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } } protected override void Dispose(bool disposing) { if (Interlocked.Exchange(ref state, 2) != 2) { SafeEnd.Dispose(deflateStream); SafeEnd.Dispose(innerStream); base.Dispose(disposing); } } } public static class WebSocketMessageExtensionCollectionExtensions { public static WebSocketMessageExtensionCollection RegisterDeflateCompression(this WebSocketMessageExtensionCollection collection) { if (collection == null) { throw new ArgumentNullException("collection"); } collection.Add(new WebSocketDeflateExtension()); return collection; } } } namespace JetBrains.Annotations { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.GenericParameter)] internal sealed class CanBeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.GenericParameter)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Delegate)] internal sealed class ItemNotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Delegate)] internal sealed class ItemCanBeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Delegate)] internal sealed class StringFormatMethodAttribute : Attribute { [NotNull] public string FormatParameterName { get; private set; } public StringFormatMethodAttribute([NotNull] string formatParameterName) { FormatParameterName = formatParameterName; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true)] internal sealed class ValueProviderAttribute : Attribute { [NotNull] public string Name { get; private set; } public ValueProviderAttribute([NotNull] string name) { Name = name; } } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class InvokerParameterNameAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class NotifyPropertyChangedInvocatorAttribute : Attribute { [CanBeNull] public string ParameterName { get; private set; } public NotifyPropertyChangedInvocatorAttribute() { } public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] internal sealed class ContractAnnotationAttribute : Attribute { [NotNull] public string Contract { get; private set; } public bool ForceFullStates { get; private set; } public ContractAnnotationAttribute([NotNull] string contract) : this(contract, forceFullStates: false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } } [AttributeUsage(AttributeTargets.All)] internal sealed class LocalizationRequiredAttribute : Attribute { public bool Required { get; private set; } public LocalizationRequiredAttribute() : this(required: true) { } public LocalizationRequiredAttribute(bool required) { Required = required; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] internal sealed class CannotApplyEqualityOperatorAttribute : Attribute { } [BaseTypeRequired(typeof(Attribute))] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal sealed class BaseTypeRequiredAttribute : Attribute { [NotNull] public Type BaseType { get; private set; } public BaseTypeRequiredAttribute([NotNull] Type baseType) { BaseType = baseType; } } [AttributeUsage(AttributeTargets.All)] internal sealed class UsedImplicitlyAttribute : Attribute { public ImplicitUseKindFlags UseKindFlags { get; private set; } public ImplicitUseTargetFlags TargetFlags { get; private set; } public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)] internal sealed class MeansImplicitUseAttribute : Attribute { [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [Flags] internal enum ImplicitUseKindFlags { Default = 7, Access = 1, Assign = 2, InstantiatedWithFixedConstructorSignature = 4, InstantiatedNoFixedConstructorSignature = 8 } [Flags] internal enum ImplicitUseTargetFlags { Default = 1, Itself = 1, Members = 2, WithMembers = 3 } [MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)] internal sealed class PublicAPIAttribute : Attribute { [CanBeNull] public string Comment { get; private set; } public PublicAPIAttribute() { } public PublicAPIAttribute([NotNull] string comment) { Comment = comment; } } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class InstantHandleAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class PureAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class MustUseReturnValueAttribute : Attribute { [CanBeNull] public string Justification { get; private set; } public MustUseReturnValueAttribute() { } public MustUseReturnValueAttribute([NotNull] string justification) { Justification = justification; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.GenericParameter)] internal sealed class ProvidesContextAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class PathReferenceAttribute : Attribute { [CanBeNull] public string BasePath { get; private set; } public PathReferenceAttribute() { } public PathReferenceAttribute([PathReference][NotNull] string basePath) { BasePath = basePath; } } [AttributeUsage(AttributeTargets.Method)] internal sealed class SourceTemplateAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)] internal sealed class MacroAttribute : Attribute { [CanBeNull] public string Expression { get; set; } public int Editable { get; set; } [CanBeNull] public string Target { get; set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] internal sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute { [NotNull] public string Format { get; private set; } public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format) { Format = format; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] internal sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute { [NotNull] public string Format { get; private set; } public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] internal sealed class AspMvcAreaViewLocationFormatAttribute : Attribute { [NotNull] public string Format { get; private set; } public AspMvcAreaViewLocationFormatAttribute([NotNull] string format) { Format = format; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] internal sealed class AspMvcMasterLocationFormatAttribute : Attribute { [NotNull] public string Format { get; private set; } public AspMvcMasterLocationFormatAttribute([NotNull] string format) { Format = format; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] internal sealed class AspMvcPartialViewLocationFormatAttribute : Attribute { [NotNull] public string Format { get; private set; } public AspMvcPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] internal sealed class AspMvcViewLocationFormatAttribute : Attribute { [NotNull] public string Format { get; private set; } public AspMvcViewLocationFormatAttribute([NotNull] string format) { Format = format; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter)] internal sealed class AspMvcActionAttribute : Attribute { [CanBeNull] public string AnonymousProperty { get; private set; } public AspMvcActionAttribute() { } public AspMvcActionAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcAreaAttribute : Attribute { [CanBeNull] public string AnonymousProperty { get; private set; } public AspMvcAreaAttribute() { } public AspMvcAreaAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter)] internal sealed class AspMvcControllerAttribute : Attribute { [CanBeNull] public string AnonymousProperty { get; private set; } public AspMvcControllerAttribute() { } public AspMvcControllerAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcMasterAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcModelTypeAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter)] internal sealed class AspMvcPartialViewAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] internal sealed class AspMvcSuppressViewErrorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcDisplayTemplateAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcEditorTemplateAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcTemplateAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter)] internal sealed class AspMvcViewAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcViewComponentAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter)] internal sealed class AspMvcViewComponentViewAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] internal sealed class AspMvcActionSelectorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] internal sealed class HtmlElementAttributesAttribute : Attribute { [CanBeNull] public string Name { get; private set; } public HtmlElementAttributesAttribute() { } public HtmlElementAttributesAttribute([NotNull] string name) { Name = name; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] internal sealed class HtmlAttributeValueAttribute : Attribute { [NotNull] public string Name { get; private set; } public HtmlAttributeValueAttribute([NotNull] string name) { Name = name; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter)] internal sealed class RazorSectionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)] internal sealed class CollectionAccessAttribute : Attribute { public CollectionAccessType CollectionAccessType { get; private set; } public CollectionAccessAttribute(CollectionAccessType collectionAccessType) { CollectionAccessType = collectionAccessType; } } [Flags] internal enum CollectionAccessType { None = 0, Read = 1, ModifyExistingContent = 2, UpdatedContent = 6 } [AttributeUsage(AttributeTargets.Method)] internal sealed class AssertionMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AssertionConditionAttribute : Attribute { public AssertionConditionType ConditionType { get; private set; } public AssertionConditionAttribute(AssertionConditionType conditionType) { ConditionType = conditionType; } } internal enum AssertionConditionType { IS_TRUE, IS_FALSE, IS_NULL, IS_NOT_NULL } [AttributeUsage(AttributeTargets.Method)] [Obsolete("Use [ContractAnnotation('=> halt')] instead")] internal sealed class TerminatesProgramAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class LinqTunnelAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class NoEnumerationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class RegexPatternAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface)] internal sealed class NoReorderAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class)] internal sealed class XamlItemsControlAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] internal sealed class XamlItemBindingOfItemsControlAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal sealed class AspChildControlTypeAttribute : Attribute { [NotNull] public string TagName { get; private set; } [NotNull] public Type ControlType { get; private set; } public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType) { TagName = tagName; ControlType = controlType; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)] internal sealed class AspDataFieldAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)] internal sealed class AspDataFieldsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] internal sealed class AspMethodPropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal sealed class AspRequiredAttributeAttribute : Attribute { [NotNull] public string Attribute { get; private set; } public AspRequiredAttributeAttribute([NotNull] string attribute) { Attribute = attribute; } } [AttributeUsage(AttributeTargets.Property)] internal sealed class AspTypePropertyAttribute : Attribute { public bool CreateConstructorReferences { get; private set; } public AspTypePropertyAttribute(bool createConstructorReferences) { CreateConstructorReferences = createConstructorReferences; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorImportNamespaceAttribute : Attribute { [NotNull] public string Name { get; private set; } public RazorImportNamespaceAttribute([NotNull] string name) { Name = name; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorInjectionAttribute : Attribute { [NotNull] public string Type { get; private set; } [NotNull] public string FieldName { get; private set; } public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName) { Type = type; FieldName = fieldName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorDirectiveAttribute : Attribute { [NotNull] public string Directive { get; private set; } public RazorDirectiveAttribute([NotNull] string directive) { Directive = directive; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorPageBaseTypeAttribute : Attribute { [NotNull] public string BaseType { get; private set; } [CanBeNull] public string PageName { get; private set; } public RazorPageBaseTypeAttribute([NotNull] string baseType) { BaseType = baseType; } public RazorPageBaseTypeAttribute([NotNull] string baseType, string pageName) { BaseType = baseType; PageName = pageName; } } [AttributeUsage(AttributeTargets.Method)] internal sealed class RazorHelperCommonAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] internal sealed class RazorLayoutAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class RazorWriteLiteralMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class RazorWriteMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class RazorWriteMethodParameterAttribute : Attribute { } } namespace vtortola.WebSockets { public abstract class BufferManager { [Obsolete("Is not used")] public abstract int SmallBufferSize { get; } public abstract int LargeBufferSize { get; } public static BufferManager CreateBufferManager(long maxBufferPoolSize, int maxBufferSize) { if (maxBufferPoolSize < 0) { throw new ArgumentOutOfRangeException("maxBufferPoolSize"); } if (maxBufferSize < 0) { throw new ArgumentOutOfRangeException("maxBufferSize"); } if (maxBufferSize < 256) { maxBufferSize = 256; } if (maxBufferPoolSize < maxBufferSize) { maxBufferPoolSize = maxBufferSize * 10; } int num = (int)Math.Pow(2.0, Math.Ceiling(Math.Log(maxBufferSize) / Math.Log(2.0))); int num2 = (int)Math.Max(2.0, Math.Ceiling((float)maxBufferPoolSize / 2f / (float)num)); int num3 = Math.Max(32, num / 256); int smallPoolSizeLimit = (int)Math.Max(2L, (maxBufferPoolSize - num2 * num) / num3); return new DefaultBufferManager(num3, smallPoolSizeLimit, num, num2); } [NotNull] public static BufferManager CreateBufferManager(int smallBufferSize, int smallBufferPoolSize, int largeBufferSize, int largeBufferPoolSize) { if (smallBufferSize < 0) { throw new ArgumentOutOfRangeException("smallBufferSize"); } if (largeBufferSize < 0) { throw new ArgumentOutOfRangeException("largeBufferSize"); } if (smallBufferPoolSize < 0) { throw new ArgumentOutOfRangeException("smallBufferPoolSize"); } if (largeBufferPoolSize < 0) { throw new ArgumentOutOfRangeException("largeBufferPoolSize"); } return new DefaultBufferManager(smallBufferSize, smallBufferPoolSize, largeBufferSize, largeBufferPoolSize); } [Obsolete("Is not used")] public abstract void Clear(); public abstract void ReturnBuffer(byte[] buffer); public abstract byte[] TakeBuffer(int bufferSize); } public sealed class ConsoleLogger : ILogger { public static ConsoleLogger Instance = new ConsoleLogger(); public bool IsDebugEnabled { get; set; } public bool IsWarningEnabled { get; set; } public bool IsErrorEnabled { get; set; } public ConsoleLogger() { IsDebugEnabled = true; IsWarningEnabled = true; IsErrorEnabled = true; } public void Debug(string message, Exception error = null) { if (IsDebugEnabled) { if (!string.IsNullOrEmpty(message)) { Console.WriteLine(message); } if (error != null) { Console.WriteLine(error); } } } public void Warning(string message, Exception error = null) { if (IsWarningEnabled) { string.IsNullOrEmpty(message); if (error != null) { Console.WriteLine(error); } } } public void Error(string message, Exception error = null) { if (IsErrorEnabled) { string.IsNullOrEmpty(message); if (error != null) { Console.WriteLine(error); } } } } public sealed class DebugLogger : ILogger { public static DebugLogger Instance = new DebugLogger(); public bool IsDebugEnabled { get; set; } public bool IsWarningEnabled { get; set; } public bool IsErrorEnabled { get; set; } public DebugLogger() { IsDebugEnabled = true; IsWarningEnabled = true; IsErrorEnabled = true; } public void Debug(string message, Exception error = null) { if (IsDebugEnabled) { string.IsNullOrEmpty(message); } } public void Warning(string message, Exception error = null) { if (IsWarningEnabled) { string.IsNullOrEmpty(message); } } public void Error(string message, Exception error = null) { if (IsErrorEnabled) { string.IsNullOrEmpty(message); } } } internal sealed class DefaultBufferManager : BufferManager { private readonly ObjectPool<byte[]> smallPool; private readonly ObjectPool<byte[]> largePool; public override int SmallBufferSize { get; } public override int LargeBufferSize { get; } public DefaultBufferManager(int smallBufferSize, int smallPoolSizeLimit, int largeBufferSize, int largePoolSizeLimit) { SmallBufferSize = smallBufferSize; LargeBufferSize = largeBufferSize; smallPool = new ObjectPool<byte[]>(() => new byte[smallBufferSize], smallPoolSizeLimit); largePool = new ObjectPool<byte[]>(() => new byte[largeBufferSize], largePoolSizeLimit); } public override void Clear() { smallPool.Clear(); largePool.Clear(); } public override void ReturnBuffer(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (buffer.Length >= LargeBufferSize) { largePool.Return(buffer); return; } if (buffer.Length >= SmallBufferSize) { smallPool.Return(buffer); return; } throw new ArgumentException("Length of buffer does not match the pool's buffer length property.", "buffer"); } public override byte[] TakeBuffer(int bufferSize) { if (bufferSize < 0 || bufferSize > LargeBufferSize) { throw new ArgumentOutOfRangeException("bufferSize"); } if (bufferSize >= SmallBufferSize) { return largePool.Take(); } return smallPool.Take(); } } [PublicAPI] public interface IHttpFallback { void Post([NotNull] IHttpRequest request, [NotNull] NetworkConnection networkConnection); } [PublicAPI] public interface IHttpRequest { EndPoint LocalEndPoint { get; } EndPoint RemoteEndPoint { get; } Uri RequestUri { get; } Version HttpVersion { get; } bool IsSecure { get; } CookieCollection Cookies { get; } Headers<RequestHeader> Headers { get; } IDictionary<string, object> Items { get; } } public interface IWebSocketConnectionExtension { [NotNull] [ItemNotNull] Task<NetworkConnection> ExtendConnectionAsync([NotNull] NetworkConnection networkConnection); [NotNull] IWebSocketConnectionExtension Clone(); } public interface IWebSocketMessageExtension { string Name { get; } bool TryNegotiate(WebSocketHttpRequest request, out WebSocketExtension extensionResponse, out IWebSocketMessageExtensionContext context); IWebSocketMessageExtension Clone(); new string ToString(); } public interface IWebSocketMessageExtensionContext { [NotNull] WebSocketMessageReadStream ExtendReader([NotNull] WebSocketMessageReadStream message); [NotNull] WebSocketMessageWriteStream ExtendWriter([NotNull] WebSocketMessageWriteStream message); } [PublicAPI] public sealed class WebSocketConnectionExtensionCollection : IReadOnlyCollection<IWebSocketConnectionExtension>, IEnumerable<IWebSocketConnectionExtension>, IEnumerable { private readonly List<IWebSocketConnectionExtension> extensions; private volatile int useCounter; public int Count => extensions.Count; public bool IsReadOnly => useCounter > 0; public WebSocketConnectionExtensionCollection() { extensions = new List<IWebSocketConnectionExtension>(); } public void Add(IWebSocketConnectionExtension extension) { if (extension == null) { throw new ArgumentNullException("extension"); } if (IsReadOnly) { throw new WebSocketException("New entries cannot be added because this collection is used in running WebSocketClient or WebSocketListener."); } if (extensions.Any((IWebSocketConnectionExtension ext) => ext.GetType() == extension.GetType())) { throw new WebSocketException($"Can't add extension '{extension}' because another extension of type '{extension.GetType().Name}' is already exists in collection."); } extensions.Add(extension); } public WebSocketConnectionExtensionCollection RegisterSecureConnection(X509Certificate2 certificate, RemoteCertificateValidationCallback validation = null, SslProtocols supportedSslProtocols = SslProtocols.Tls12) { if (certificate == null) { throw new ArgumentNullException("certificate"); } WebSocketSecureConnectionExtension extension = new WebSocketSecureConnectionExtension(certificate, validation, supportedSslProtocols); Add(extension); return this; } IEnumerator<IWebSocketConnectionExtension> IEnumerable<IWebSocketConnectionExtension>.GetEnumerator() { return extensions.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return extensions.GetEnumerator(); } public List<IWebSocketConnectionExtension>.Enumerator GetEnumerator() { return extensions.GetEnumerator(); } internal WebSocketConnectionExtensionCollection Clone() { WebSocketConnectionExtensionCollection webSocketConnectionExtensionCollection = new WebSocketConnectionExtensionCollection(); foreach (IWebSocketConnectionExtension extension in extensions) { webSocketConnectionExtensionCollection.extensions.Add(extension.Clone()); } return webSocketConnectionExtensionCollection; } internal void SetUsed(bool isUsed) { int num = 0; num = ((!isUsed) ? Interlocked.Decrement(ref useCounter) : Interlocked.Increment(ref useCounter)); if (num < 0) { throw new InvalidOperationException("The collection is released more than once."); } } public override string ToString() { return string.Join(", ", extensions); } } public sealed class WebSocketFactoryCollection : IReadOnlyCollection<WebSocketFactory>, IEnumerable<WebSocketFactory>, IEnumerable { private readonly Dictionary<short, WebSocketFactory> factoryByVersion; private volatile int useCounter; public IEnumerable<short> SupportedVersions => factoryByVersion.Keys; public int Count => factoryByVersion.Count; public bool IsReadOnly => useCounter > 0; public WebSocketFactoryCollection() { factoryByVersion = new Dictionary<short, WebSocketFactory>(); } public void Add(WebSocketFactory factory) { if (factory == null) { throw new ArgumentNullException("factory"); } if (IsReadOnly) { throw new WebSocketException("New entries cannot be added because this collection is used in running WebSocketClient or WebSocketListener."); } if (factoryByVersion.ContainsKey(factory.Version)) { throw new WebSocketException(string.Format("Can't add {0} '{1}' because another {2} with ", "WebSocketFactory", factory, "WebSocketFactory") + $"version '{factory.Version}' is already exists in collection."); } factoryByVersion.Add(factory.Version, factory); } IEnumerator IEnumerable.GetEnumerator() { return factoryByVersion.Values.GetEnumerator(); } IEnumerator<WebSocketFactory> IEnumerable<WebSocketFactory>.GetEnumerator() { return factoryByVersion.Values.GetEnumerator(); } public Dictionary<short, WebSocketFactory>.ValueCollection.Enumerator GetEnumerator() { return factoryByVersion.Values.GetEnumerator(); } internal WebSocketFactoryCollection Clone() { WebSocketFactoryCollection webSocketFactoryCollection = new WebSocketFactoryCollection(); foreach (KeyValuePair<short, WebSocketFactory> item in factoryByVersion) { webSocketFactoryCollection.factoryByVersion[item.Key] = item.Value.Clone(); } return webSocketFactoryCollection; } internal void SetUsed(bool isUsed) { int num = 0; num = ((!isUsed) ? Interlocked.Decrement(ref useCounter) : Interlocked.Increment(ref useCounter)); if (num < 0) { throw new InvalidOperationException("The collection is released more than once."); } } internal WebSocketFactory GetLast() { return factoryByVersion[factoryByVersion.Keys.Max()]; } public bool TryGetWebSocketFactory(WebSocketHttpRequest request, out WebSocketFactory factory) { if (request == null) { throw new ArgumentNullException("request"); } factory = null; short result = 0; if (short.TryParse(request.Headers[RequestHeader.WebSocketVersion], out result) && factoryByVersion.TryGetValue(result, out factory)) { return true; } return false; } } public sealed class WebSocketMessageExtensionCollection : IReadOnlyCollection<IWebSocketMessageExtension>, IEnumerable<IWebSocketMessageExtension>, IEnumerable { private readonly List<IWebSocketMessageExtension> extensions; private volatile int useCounter; public int Count => extensions.Count; public bool IsReadOnly => useCounter > 0; public WebSocketMessageExtensionCollection() { extensions = new List<IWebSocketMessageExtension>(); } public void Add(IWebSocketMessageExtension extension) { if (extension == null) { throw new ArgumentNullException("extension"); } if (IsReadOnly) { throw new WebSocketException("New entries cannot be added because this collection is used in running WebSocketClient or WebSocketListener."); } if (extensions.Any((IWebSocketMessageExtension ext) => ext.GetType() == extension.GetType())) { throw new WebSocketException($"Can't add extension '{extension}' because another extension of type '{extension.GetType().Name}' is already exists in collection."); } extensions.Add(extension); } IEnumerator<IWebSocketMessageExtension> IEnumerable<IWebSocketMessageExtension>.GetEnumerator() { return extensions.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return extensions.GetEnumerator(); } public List<IWebSocketMessageExtension>.Enumerator GetEnumerator() { return extensions.GetEnumerator(); } internal WebSocketMessageExtensionCollection Clone() { WebSocketMessageExtensionCollection webSocketMessageExtensionCollection = new WebSocketMessageExtensionCollection(); foreach (IWebSocketMessageExtension extension in extensions) { webSocketMessageExtensionCollection.extensions.Add(extension.Clone()); } return webSocketMessageExtensionCollection; } internal void SetUsed(bool isUsed) { int num = 0; num = ((!isUsed) ? Interlocked.Decrement(ref useCounter) : Interlocked.Increment(ref useCounter)); if (num < 0) { throw new InvalidOperationException("The collection is released more than once."); } } public override string ToString() { return string.Join(", ", extensions); } } public sealed class WebSocketSecureConnectionExtension : IWebSocketConnectionExtension { private readonly X509Certificate2 _certificate; private readonly RemoteCertificateValidationCallback _validation; private readonly SslProtocols _protocols; public WebSocketSecureConnectionExtension(X509Certificate2 certificate) { if (certificate == null) { throw new ArgumentNullException("certificate"); } _certificate = certificate; _protocols = SslProtocols.Tls12; } public WebSocketSecureConnectionExtension(X509Certificate2 certificate, RemoteCertificateValidationCallback validation) { if (certificate == null) { throw new ArgumentNullException("certificate"); } _certificate = certificate; _validation = validation; _protocols = SslProtocols.Tls12; } public WebSocketSecureConnectionExtension(X509Certificate2 certificate, RemoteCertificateValidationCallback validation, SslProtocols supportedSslProtocols) { if (certificate == null) { throw new ArgumentNullException("certificate"); } _certificate = certificate; _validation = validation; _protocols = supportedSslProtocols; } public async Task<NetworkConnection> ExtendConnectionAsync(NetworkConnection networkConnection) { if (networkConnection == null) { throw new ArgumentNullException("networkConnection"); } SslStream ssl = new SslStream(networkConnection.AsStream(), leaveInnerStreamOpen: false, _validation); try { await ssl.AuthenticateAsServerAsync(_certificate, _validation != null, _protocols, checkCertificateRevocation: false).ConfigureAwait(continueOnCapturedContext: false); return new SslNetworkConnection(ssl, networkConnection); } catch { SafeEnd.Dispose(ssl); throw; } } public IWebSocketConnectionExtension Clone() { return (IWebSocketConnectionExtension)MemberwiseClone(); } public override string ToString() { return $"Secure Connection: protocols: {_protocols}, certificate: {_certificate.SubjectName}"; } } public sealed class WebSocketExtensionFlags { private bool _rsv1; private bool _rsv2; private bool _rsv3; private readonly bool _none; public static readonly WebSocketExtensionFlags None = new WebSocketExtensionFlags(none: true); public bool Rsv1 { get { return _rsv1; } set { _rsv1 = value && !_none; } } public bool Rsv2 { get { return _rsv2; } set { _rsv2 = value && !_none; } } public bool Rsv3 { get { return _rsv3; } set { _rsv3 = value && !_none; } } public WebSocketExtensionFlags() { _none = false; } private WebSocketExtensionFlags(bool none) { _none = true; } } public enum WebSocketMessageType { Text = 1, Binary } public delegate Task<bool> HttpAuthenticationCallback(WebSocketHttpRequest request, WebSocketHttpResponse response); public static class CookieParser { public static IEnumerable<Cookie> Parse([CanBeNull] string cookieString) { if (string.IsNullOrWhiteSpace(cookieString)) { yield break; } string text = string.Empty; string text2 = string.Empty; for (int i = 0; i < cookieString.Length; i++) { char c = cookieString[i]; if (c == '=' && string.IsNullOrWhiteSpace(text2)) { text2 = text; text = string.Empty; } else if (c == ';') { if (!string.IsNullOrWhiteSpace(text2)) { yield return CreateCookie(text2, text); } else { yield return CreateCookie(text, string.Empty); } text2 = string.Empty; text = string.Empty; } else { text += c; } } if (!string.IsNullOrWhiteSpace(text2) && !string.IsNullOrWhiteSpace(text)) { yield return CreateCookie(text2, text); } } private static Cookie CreateCookie(string key, string value) { return new Cookie(key.Trim(), WebUtility.UrlDecode(value.Trim())); } } public sealed class WebSocketExtension { public static readonly ReadOnlyCollection<WebSocketExtensionOption> Empty = new ReadOnlyCollection<WebSocketExtensionOption>(new List<WebSocketExtensionOption>()); private readonly string extensionString; public readonly string Name; public readonly ReadOnlyCollection<WebSocketExtensionOption> Options; public WebSocketExtension(string name, IList<WebSocketExtensionOption> options) { if (name == null) { throw new ArgumentNullException("name"); } if (options == null) { throw new ArgumentNullException("options"); } Name = name; Options = (options as ReadOnlyCollection<WebSocketExtensionOption>) ?? new ReadOnlyCollection<WebSocketExtensionOption>(options); extensionString = ((Options.Count > 0) ? (Name + ";" + string.Join(";", Options)) : Name); } public WebSocketExtension(string name) { Name = name; Options = Empty; } public override string ToString() { return extensionString; } } public class WebSocketExtensionOption { public readonly string Name; public readonly string Value; public readonly bool ClientAvailableOption; public WebSocketExtensionOption(string name) { if (name == null) { throw new ArgumentNullException("name"); } Name = name; } public WebSocketExtensionOption(string name, bool clientAvailableOption) { if (name == null) { throw new ArgumentNullException("name"); } Name = name; ClientAvailableOption = clientAvailableOption; } public WebSocketExtensionOption(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } Name = name; Value = value; } public override string ToString() { if (string.IsNullOrEmpty(Value)) { return Name; } return Name + "=" + Value; } } internal class WebSocketHandshake : IComparable<WebSocketHandshake>, IEquatable<WebSocketHandshake> { private static long LastId = 1L; private bool _invalidated; public readonly long Id; [NotNull] public readonly WebSocketHttpRequest Request; public readonly WebSocketHttpResponse Response; public readonly List<IWebSocketMessageExtensionContext> NegotiatedMessageExtensions; public bool IsWebSocketRequest { get; internal set; } public bool IsVersionSupported { get; internal set; } public bool IsResponseSent { get; internal set; } public WebSocketFactory Factory { get; internal set; } public ExceptionDispatchInfo Error { get; internal set; } public bool IsValidWebSocketRequest { get { if (!_invalidated && Error == null && IsWebSocketRequest && IsVersionSupported) { return Response.Status == HttpStatusCode.SwitchingProtocols; } return false; } set { _invalidated = !value; } } public bool IsValidHttpRequest { get { if (!_invalidated) { return Error == null; } return false; } set { _invalidated = !value; } } public WebSocketHandshake([NotNull] WebSocketHttpRequest request) { if (request == null) { throw new ArgumentNullException("request"); } Id = Interlocked.Increment(ref LastId); Request = request; Response = new WebSocketHttpResponse(); NegotiatedMessageExtensions = new List<IWebSocketMessageExtensionContext>(); } public string ComputeHandshake() { string text = Request.Headers[RequestHeader.WebSocketKey]; if (string.IsNullOrEmpty(text)) { throw new InvalidOperationException("Missing or wrong " + Headers<RequestHeader>.GetHeaderName(RequestHeader.WebSocketKey) + " header in request."); } using SHA1 sHA = SHA1.Create(); return Convert.ToBase64String(sHA.ComputeHash(Encoding.UTF8.GetBytes(text + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))); } public string GenerateClientNonce() { return Convert.ToBase64String(Guid.NewGuid().ToByteArray()); } public int CompareTo(WebSocketHandshake other) { if (other == null) { return 1; } long id = Id; return id.CompareTo(other.Id); } public bool Equals(WebSocketHandshake other) { if (other == null) { return false; } if (this == other) { return true; } return Id == other.Id; } public override bool Equals(object obj) { return Equals(obj as WebSocketHandshake); } public override int GetHashCode() { long id = Id; return id.GetHashCode(); } public override string ToString() { return $"Handshake, id: {Id}, request: {Request}, response: {Response}"; } } internal class WebSocketHandshaker { private static readonly Version HttpVersion11 = new Version(1, 1); private static readonly Version HttpVersion10 = new Version(1, 0); private readonly ILogger log; private readonly WebSocketListenerOptions options; private readonly WebSocketFactoryCollection factories; public WebSocketHandshaker(WebSocketFactoryCollection factories, WebSocketListenerOptions options) { if (factories == null) { throw new ArgumentNullException("factories"); } if (options == null) { throw new ArgumentNullException("options"); } log = options.Logger; this.factories = factories; this.options = options; } public async Task<WebSocketHandshake> HandshakeAsync(NetworkConnection networkConnection) { if (networkConnection == null) { throw new ArgumentNullException("networkConnection"); } WebSocketHttpRequest request = new WebSocketHttpRequest(HttpRequestDirection.Incoming) { LocalEndPoint = (networkConnection.LocalEndPoint ?? WebSocketHttpRequest.NoAddress), RemoteEndPoint = (networkConnection.RemoteEndPoint ?? WebSocketHttpRequest.NoAddress), IsSecure = (networkConnection is SslNetworkConnection) }; WebSocketHandshake handshake = new WebSocketHandshake(request); try { await ReadHttpRequestAsync(networkConnection, handshake).ConfigureAwait(continueOnCapturedContext: false); if (!IsWebSocketRequestValid(handshake)) { await WriteHttpResponseAsync(handshake, networkConnection).ConfigureAwait(continueOnCapturedContext: false); return handshake; } handshake.IsWebSocketRequest = true; WebSocketFactory factory = null; if (!factories.TryGetWebSocketFactory(handshake.Request, out factory)) { await WriteHttpResponseAsync(handshake, networkConnection).ConfigureAwait(continueOnCapturedContext: false); return handshake; } handshake.Factory = factory; handshake.IsVersionSupported = true; ConsolidateObjectModel(handshake); SelectExtensions(handshake); if (!(await RunHttpNegotiationHandlerAsync(handshake).ConfigureAwait(continueOnCapturedContext: false))) { throw new WebSocketException("HTTP authentication failed."); } await WriteHttpResponseAsync(handshake, networkConnection).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception ex) { if (log.IsDebugEnabled) { log.Debug("Failed to handshake request.", ex); } handshake.Error = ExceptionDispatchInfo.Capture(ex); if (!handshake.IsResponseSent) { try { await WriteHttpResponseAsync(handshake, networkConnection).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception error) { if (log.IsDebugEnabled) { log.Debug("Failed to write error response.", error); } } } } return handshake; } private static bool IsWebSocketRequestValid(WebSocketHandshake handShake) { if (handShake == null) { throw new ArgumentNullException("handShake"); } Headers<RequestHeader> headers = handShake.Request.Headers; if (headers.Contains(RequestHeader.Host) && headers.Contains(RequestHeader.Upgrade) && headers.GetValues(RequestHeader.Upgrade).Contains("websocket", StringComparison.OrdinalIgnoreCase) && headers.Contains(RequestHeader.Connection) && !string.IsNullOrWhiteSpace(headers.Get(RequestHeader.WebSocketKey))) { return headers.Contains(RequestHeader.WebSocketVersion); } return false; } private async Task<bool> RunHttpNegotiationHandlerAsync(WebSocketHandshake handshake) { if (handshake == null) { throw new ArgumentNullException("handshake"); } if (options.HttpAuthenticationHandler != null) { try { return await options.HttpAuthenticationHandler(handshake.Request, handshake.Response).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception source) { handshake.Response.Status = HttpStatusCode.InternalServerError; handshake.Error = ExceptionDispatchInfo.Capture(source); return false; } } return true; } private void SelectExtensions(WebSocketHandshake handshake) { if (handshake == null) { throw new ArgumentNullException("handshake"); } foreach (WebSocketExtension extRequest in handshake.Request.WebSocketExtensions) { IWebSocketMessageExtension webSocketMessageExtension = handshake.Factory.MessageExtensions.SingleOrDefault((IWebSocketMessageExtension x) => x.Name.Equals(extRequest.Name, StringComparison.OrdinalIgnoreCase)); if (webSocketMessageExtension != null && webSocketMessageExtension.TryNegotiate(handshake.Request, out var extensionResponse, out var context)) { handshake.NegotiatedMessageExtensions.Add(context); handshake.Response.WebSocketExtensions.Add(extensionResponse); } } } private async Task WriteHttpResponseAsync(WebSocketHandshake handshake, NetworkConnection networkConnection) { if (handshake == null) { throw new ArgumentNullException("handshake"); } if (networkConnection == null) { throw new ArgumentNullException("networkConnection"); } if (handshake.IsWebSocketRequest || !handshake.IsValidHttpRequest || options.HttpFallback == null) { handshake.IsResponseSent = true; using StreamWriter writer = new StreamWriter(networkConnection.AsStream(), Encoding.ASCII, 1024, leaveOpen: true); await WriteResponseInternal(handshake, writer).ConfigureAwait(continueOnCapturedContext: false); await writer.FlushAsync().ConfigureAwait(continueOnCapturedContext: false); } } private async Task WriteResponseInternal(WebSocketHandshake handshake, StreamWriter writer) { if (handshake == null) { throw new ArgumentNullException("handshake"); } if (writer == null) { throw new ArgumentNullException("writer"); } if (!handshake.IsWebSocketRequest) { handshake.Response.Status = HttpStatusCode.BadRequest; await SendNegotiationErrorResponseAsync(writer, handshake.Response.Status); } else if (!handshake.IsVersionSupported) { handshake.Response.Status = HttpStatusCode.UpgradeRequired; await SendVersionNegotiationErrorResponse(writer); } else if (handshake.IsValidWebSocketRequest) { await SendNegotiationResponse(handshake, writer); } else { handshake.Response.Status = ((handshake.Response.Status != HttpStatusCode.SwitchingProtocols) ? handshake.Response.Status : HttpStatusCode.BadRequest); await SendNegotiationErrorResponseAsync(writer, handshake.Response.Status); } } private async Task ReadHttpRequestAsync(NetworkConnection clientStream, WebSocketHandshake handshake) { if (clientStream == null) { throw new ArgumentNullException("clientStream"); } if (handshake == null) { throw new ArgumentNullException("handshake"); } using StreamReader sr = new StreamReader(clientStream.AsStream(), Encoding.ASCII, detectEncodingFromByteOrderMarks: false, 1024, leaveOpen: true); ParseGET(await sr.ReadLineAsync(), handshake); string header; while (!string.IsNullOrWhiteSpace(header = await sr.ReadLineAsync())) { handshake.Request.Headers.TryParseAndAdd(header); } ParseCookies(handshake); } private void ParseGET(string line, WebSocketHandshake handshake) { if (handshake == null) { throw new ArgumentNullException("handshake"); } if (string.IsNullOrWhiteSpace(line)) { throw new WebSocketException("Empty request line is received. Probably connection is closed."); } string[] array = line.Split(new char[1] { ' ' }); if (!line.StartsWith("GET", StringComparison.Ordinal)) { throw new WebSocketException($"Invalid request method '{array.FirstOrDefault() ?? line}' while 'GET' is expected."); } handshake.Request.RequestUri = new Uri(array[1], UriKind.Relative); string text = array[2]; handshake.Request.HttpVersion = (text.EndsWith("1.1") ? HttpVersion11 : HttpVersion10); } private async Task SendNegotiationResponse(WebSocketHandshake handshake, StreamWriter writer) { await writer.WriteAsync("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"); if (handshake.Response.Cookies.Count > 0) { foreach (object cookie in handshake.Response.Cookies) { await writer.WriteAsync("Set-Cookie: "); await writer.WriteAsync(cookie.ToString()); await writer.WriteAsync("\r\n"); } } await writer.WriteAsync("Sec-WebSocket-Accept: "); await writer.WriteAsync(handshake.ComputeHandshake()); if (handshake.Response.Headers.Contains(ResponseHeader.WebSocketProtocol)) { await writer.WriteAsync("\r\nSec-WebSocket-Protocol: "); await writer.WriteAsync(handshake.Response.Headers[ResponseHeader.WebSocketProtocol]); } WriteHandshakeCookies(handshake, writer); await writer.WriteAsync("\r\n\r\n"); } private static void WriteHandshakeCookies(WebSocketHandshake handshake, StreamWriter writer) { if (handshake == null) { throw new ArgumentNullException("handshake"); } if (writer == null) { throw new ArgumentNullException("writer"); } if (!handshake.Response.WebSocketExtensions.Any()) { return; } bool flag = true; bool flag2 = true; writer.Write("\r\nSec-WebSocket-Extensions: "); foreach (WebSocketExtension webSocketExtension in handshake.Response.WebSocketExtensions) { if (!flag) { writer.Write(","); } writer.Write(webSocketExtension.Name); IEnumerable<WebSocketExtensionOption> enumerable = webSocketExtension.Options.Where((WebSocketExtensionOption x) => !x.ClientAvailableOption); if (!webSocketExtension.Options.Any()) { continue; } writer.Write(";"); foreach (WebSocketExtensionOption item in enumerable) { if (!flag2) { writer.Write(";"); } writer.Write(item.Name); if (item.Value != null) { writer.Write("="); writer.Write(item.Value); } flag2 = false; } flag = false; } } private async Task SendNegotiationErrorResponseAsync(StreamWriter writer, HttpStatusCode code) { if (writer == null) { throw new ArgumentNullException("writer"); } await writer.WriteAsync($"HTTP/1.1 {(int)code} {HttpStatusDescription.Get(code)}\r\nConnection: close\r\n\r\n"); } private async Task SendVersionNegotiationErrorResponse(StreamWriter writer) { await writer.WriteAsync("HTTP/1.1 426 Upgrade Required\r\nSec-WebSocket-Version: "); bool first = true; foreach (WebSocketFactory standard in factories) { if (!first) { await writer.WriteAsync(","); } first = false; await writer.WriteAsync(standard.Version.ToString()); } await writer.WriteAsync("\r\n\r\n"); } private void ConsolidateObjectModel(WebSocketHandshake handshake) { if (handshake == null) { throw new ArgumentNullException("handshake"); } ParseWebSocketProtocol(handshake); ParseWebSocketExtensions(handshake); } private void ParseWebSocketProtocol(WebSocketHandshake handshake) { if (handshake == null) { throw new ArgumentNullException("handshake"); } if (!options.SubProtocols.Any() || !handshake.Request.Headers.Contains(RequestHeader.WebSocketProtocol)) { return; } foreach (string value in handshake.Request.Headers.GetValues(RequestHeader.WebSocketProtocol)) { if (options.SubProtocols.Contains<string>(value, StringComparer.OrdinalIgnoreCase)) { handshake.Response.Headers[ResponseHeader.WebSocketProtocol] = value; break; } } } private void ParseWebSocketExtensions(WebSocketHandshake handshake) { if (handshake == null) { throw new ArgumentNullException("handshake"); } List<WebSocketExtension> list = new List<WebSocketExtension>(); Headers<RequestHeader> headers = handshake.Request.Headers; if (headers.Contains(RequestHeader.WebSocketExtensions)) { foreach (string value in headers.GetValues(RequestHeader.WebSocketExtensions)) { List<WebSocketExtensionOption> list2 = new List<WebSocketExtensionOption>(); string text = null; foreach (KeyValuePair<string, string> item in HeadersHelper.SplitAndTrimKeyValue(value, ';', '=', StringSplitOptions.RemoveEmptyEntries)) { if (text == null) { text = item.Value; } else if (string.IsNullOrEmpty(item.Key)) { list2.Add(new WebSocketExtensionOption(item.Value, clientAvailableOption: true)); } else { list2.Add(new WebSocketExtensionOption(item.Key, item.Value)); } } if (string.IsNullOrEmpty(text)) { throw new WebSocketException("Wrong value '" + headers[RequestHeader.WebSocketExtensions] + "' of " + Headers<ResponseHeader>.GetHeaderName(ResponseHeader.WebSocketExtensions) + " header in request."); } list.Add(new WebSocketExtension(text, list2)); } } handshake.Request.SetExtensions(list); } private void ParseCookies(WebSocketHandshake handshake) { if (handshake == null) { throw new ArgumentNullException("handshake"); } string domain = handshake.Request.Headers[RequestHeader.Host]; foreach (string value in handshake.Request.Headers.GetValues(RequestHeader.Cookie)) { try { foreach (Cookie item in CookieParser.Parse(value)) { item.Domain = domain; item.Path = string.Empty; handshake.Request.Cookies.Add(item); } } catch (Exception ex) { throw new WebSocketException("Cannot parse cookie string: '" + value + "' because: " + ex.Message); } } } } public sealed class WebSocketHttpRequest : IHttpRequest { public static readonly IPEndPoint NoAddress = new IPEndPoint(IPAddress.None, 0); public EndPoint LocalEndPoint { get; internal set; } public EndPoint RemoteEndPoint { get; internal set; } public Uri RequestUri { get; internal set; } public Version HttpVersion { get; internal set; } public bool IsSecure { get; internal set; } public CookieCollection Cookies { get; } public Headers<RequestHeader> Headers { get; } public IDictionary<string, object> Items { get; } public HttpRequestDirection Direction { get; } public IReadOnlyList<WebSocketExtension> WebSocketExtensions { get; private set; } public WebSocketHttpRequest(HttpRequestDirection direction) { Headers = new Headers<RequestHeader>(); Cookies = new CookieCollection(); Items = new Dictionary<string, object>(); LocalEndPoint = NoAddress; RemoteEndPoint = NoAddress; Direction = direction; } internal void SetExtensions(List<WebSocketExtension> extensions) { if (extensions == null) { throw new ArgumentNullException("extensions"); } WebSocketExtensions = new ReadOnlyCollection<WebSocketExtension>(extensions); } public override string ToString() { if (RequestUri != null) { return RequestUri.ToString(); } return $"{LocalEndPoint}->{RemoteEndPoint}"; } } public sealed class WebSocketHttpResponse { public readonly CookieCollection Cookies; public readonly Headers<ResponseHeader> Headers; public HttpStatusCode Status; public string StatusDescription; public readonly List<WebSocketExtension> WebSocketExtensions; public WebSocketHttpResponse() { Headers = new Headers<ResponseHeader>(); Cookies = new CookieCollection(); WebSocketExtensions = new List<WebSocketExtension>(); Status = HttpStatusCode.SwitchingProtocols; StatusDescription = "Web Socket Protocol Handshake"; } public void ThrowIfInvalid(string computedHandshake) { if (computedHandshake == null) { throw new ArgumentNullException("computedHandshake"); } string b = Headers[ResponseHeader.Upgrade]; if (!string.Equals("websocket", b, StringComparison.OrdinalIgnoreCase)) { throw new WebSocketException("Missing or wrong " + Headers<ResponseHeader>.GetHeaderName(ResponseHeader.Upgrade) + " header in response."); } if (!Headers.GetValues(ResponseHeader.Connection).Contains("Upgrade", StringComparison.OrdinalIgnoreCase)) { throw new WebSocketException("Missing or wrong " + Headers<ResponseHeader>.GetHeaderName(ResponseHeader.Connection) + " header in response."); } string b2 = Headers[ResponseHeader.WebSocketAccept]; if (!string.Equals(computedHandshake, b2, StringComparison.OrdinalIgnoreCase)) { throw new WebSocketException("Missing or wrong " + Headers<ResponseHeader>.GetHeaderName(ResponseHeader.WebSocketAccept) + " header in response."); } } public override string ToString() { return $"{Status} {StatusDescription}"; } } public interface ILogger { bool IsDebugEnabled { get; } bool IsWarningEnabled { get; } bool IsErrorEnabled { get; } void Debug(string message, Exception error = null); void Warning(string message, Exception error = null); void Error(string message, Exception error = null); } public sealed class NullLogger : ILogger { public static readonly NullLogger Instance = new NullLogger(); public bool IsDebugEnabled => false; public bool IsWarningEnabled => false; public bool IsErrorEnabled => false; public void Debug(string message, Exception error = null) { } public void Warning(string message, Exception error = null) { } public void Error(string message, Exception error = null) { } } public enum PingMode { Manual, LatencyControl, BandwidthSaving } public abstract class WebSocketMessageReadStream : WebSocketMessageStream { public abstract WebSocketMessageType MessageType { get; } public abstract WebSocketExtensionFlags Flags { get; } public sealed override bool CanRead => true; [Obsolete("Writing to the read stream is not allowed", true)] public sealed override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { throw new NotSupportedException(); } } public abstract class WebSocketMessageStream : Stream { public override bool CanRead => false; public sealed override bool CanSeek => false; public override bool CanWrite => false; public sealed override long Length { get { throw new NotSupportedException(); } } public sealed override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } internal abstract WebSocketListenerOptions Options { get; } public override Task FlushAsync(CancellationToken cancellationToken) { return TaskHelper.CompletedTask; } public abstract Task CloseAsync(); public abstract override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken); public abstract override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken); public sealed override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public sealed override void SetLength(long value) { throw new NotSupportedException(); } [Obsolete("Do not use synchronous IO operation on network streams. Use ReadAsync() instead.")] public sealed override int ReadByte() { throw new NotSupportedException(); } [Obsolete("Do not use synchronous IO operation on network streams. Use ReadAsync() instead.")] public override int Read(byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count, CancellationToken.None).Result; } [Obsolete("Do not use synchronous IO operation on network streams. Use WriteAsync() instead.")] public sealed override void WriteByte(byte value) { throw new NotSupportedException(); } [Obsolete("Do not use synchronous IO operation on network streams. Use WriteAsync() instead.")] public override void Write(byte[] buffer, int offset, int count) { WriteAsync(buffer, offset, count).Wait(); } [Obsolete("Do not use synchronous IO operation on network streams. Use FlushAsync() instead.")] public override void Flush() { } } public abstract class WebSocketMessageWriteStream : WebSocketMessageStream { public sealed override bool CanWrite => true; [NotNull] public WebSocketExtensionFlags ExtensionFlags { get; } protected WebSocketMessageWriteStream() { ExtensionFlags = new WebSocketExtensionFlags(); } [Obsolete("Reading from the write stream is not allowed", true)] public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { throw new NotSupportedException(); } public abstract Task WriteAndCloseAsync([NotNull] byte[] buffer, int offset, int count, CancellationToken cancellationToken); } internal static class SafeEnd { public static void Dispose<T>([CanBeNull] T disposable, ILogger log = null) where T : class, IDisposable { if (log == null) { log = NullLogger.Instance; } try { disposable?.Dispose(); } catch (Exception error) { if (log.IsDebugEnabled) { log.Debug($"{typeof(T)} dispose cause error.", error); } } } public static void ReleaseSemaphore(SemaphoreSlim semaphore, ILogger log = null) { try { semaphore.Release(); } catch (ObjectDisposedException) { } catch (Exception error) { if (log != null && log.IsDebugEnabled) { log.Debug("Semaphore release cause error.", error); } } } } [PublicAPI] public abstract class WebSocket : IDisposable { [NotNull] public WebSocketHttpRequest HttpRequest { get; } [NotNull] public WebSocketHttpResponse HttpResponse { get; } public abstract bool IsConnected { get; } public abstract EndPoint RemoteEndpoint { get; } public abstract EndPoint LocalEndpoint { get; } public abstract TimeSpan Latency { get; } public abstract string SubProtocol { get; } public abstract WebSocketCloseReason? CloseReason { get; } protected WebSocket([NotNull] WebSocketHttpRequest request, [NotNull] WebSocketHttpResponse response) { if (request == null) { throw new ArgumentNullException("request"); } if (response == null) { throw new ArgumentNullException("response"); } HttpRequest = request; HttpResponse = response; } [ItemCanBeNull] [NotNull] public abstract Task<WebSocketMessageReadStream> ReadMessageAsync(CancellationToken token); [NotNull] public abstract WebSocketMessageWriteStream CreateMessageWriter(WebSocketMessageType messageType); public Task SendPingAsync() { return SendPingAsync(null, 0, 0); } public abstract Task SendPingAsync(byte[] data, int offset, int count); public abstract Task CloseAsync(); public abstract Task CloseAsync(WebSocketCloseReason closeCode); public abstract void Dispose(); public override string ToString() { return $"{GetType().Name}, remote: {RemoteEndpoint}, connected: {IsConnected}"; } } [PublicAPI] public sealed class WebSocketClient { private const string WEB_SOCKET_HTTP_VERSION = "HTTP/1.1"; private readonly ILogger log; private readonly AsyncConditionSource closeEvent; private readonly CancellationTokenSource workCancellationSource; private readonly WebSocketListenerOptions options; private readonly ConcurrentDictionary<WebSocketHandshake, Task<WebSocket>> pendingRequests; private readonly CancellationQueue negotiationsTimeoutQueue; private readonly PingQueue pingQueue; public bool HasPendingRequests => !pendingRequests.IsEmpty; public WebSocketClient([NotNull] WebSocketListenerOptions options) { if (options == null) { throw new ArgumentNullException("options"); } if (options.Standards.Count == 0) { throw new ArgumentException("Empty list of WebSocket standards.", "options"); } options.CheckCoherence(); this.options = options.Clone(); this.options.SetUsed(isUsed: true); if (this.options.NegotiationTimeout > TimeSpan.Zero) { negotiationsTimeoutQueue = new CancellationQueue(this.options.NegotiationTimeout); } if (this.options.PingMode != 0) { pingQueue = new PingQueue(options.PingInterval); } log = this.options.Logger; closeEvent = new AsyncConditionSource(isSet: true) { ContinueOnCapturedContext = false }; workCancellationSource = new CancellationTokenSource(); pendingRequests = new ConcurrentDictionary<WebSocketHandshake, Task<WebSocket>>(); if (this.options.BufferManager == null) { this.options.BufferManager = BufferManager.CreateBufferManager(this.options.SendBufferSize * 2 * 100, this.options.SendBufferSize * 2); } if (this.options.CertificateValidationHandler == null) { this.options.CertificateValidationHandler = ValidateRemoteCertificate; } } private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { return true; } if (log.IsWarningEnabled) { log.Warning($"Certificate validation error: {sslPolicyErrors}."); } return false; } public Task<WebSocket> ConnectAsync([NotNull] Uri address, CancellationToken cancellation = default(CancellationToken)) { return ConnectAsync(address, null, cancellation); } public async Task<WebSocket> ConnectAsync([NotNull] Uri address, Headers<RequestHeader> requestHeaders = null, CancellationToken cancellation = default(CancellationToken)) { _ = 1; try { cancellation.ThrowIfCancellationRequested(); if (workCancellationSource.IsCancellationRequested) { throw new WebSocketException("Client is currently closing or closed."); } CancellationToken workCancellation = workCancellationSource.Token; CancellationToken negotiationCancellation = negotiationsTimeoutQueue?.GetSubscriptionList().Token ?? CancellationToken.None; if (cancellation.CanBeCanceled || workCancellation.CanBeCanceled || negotiationCancellation.CanBeCanceled) { cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellation, workCancellation, negotiationCancellation).Token; } WebSocketHttpRequest webSocketHttpRequest = new WebSocketHttpRequest(HttpRequestDirection.Outgoing) { RequestUri = address }; if (requestHeaders != null) { webSocketHttpRequest.Headers.AddMany(requestHeaders); } WebSocketHandshake handshake = new WebSocketHandshake(webSocketHttpRequest); Task<WebSocket> value = OpenConnectionAsync(handshake, cancellation); pendingRequests.TryAdd(handshake, value); WebSocket disposable = await value.IgnoreFaultOrCancellation().ConfigureAwait(continueOnCapturedContext: false); if (!workCancellation.IsCancellationRequested && negotiationCancellation.IsCancellationRequested) { SafeEnd.Dispose(disposable, log); throw new WebSocketException("Negotiation timeout."); } if (pendingRequests.TryRemove(handshake, out value) && workCancellationSource.IsCancellationRequested && pendingRequests.IsEmpty) { closeEvent.Set(); } disposable = await value.ConfigureAwait(continueOnCapturedContext: false); pingQueue?.GetSubscriptionList().Add(disposable); return disposable; } catch (Exception exception) when (!(exception.Unwrap() is ThreadAbortException) && !(exception.Unwrap() is OperationCanceledException) && !(exception.Unwrap() is WebSocketException)) { throw new WebSocketException($"An unknown error occurred while connection to '{address}'. More detailed information in inner exception.", exception.Unwrap()); } } public async Task CloseAsync() { workCancellationSource.Cancel(throwOnFirstException: false); await closeEvent; SafeEnd.Dispose(pingQueue, log); SafeEnd.Dispose(negotiationsTimeoutQueue, log); SafeEnd.Dispose(workCancellationSource, log); options.SetUsed(isUsed: false); } private async Task<WebSocket> OpenConnectionAsync(WebSocketHandshake handshake, CancellationToken cancellation) { if (handshake == null) { throw new ArgumentNullException("handshake"); } NetworkConnection connection = null; WebSocket webSocket = null; try { cancellation.ThrowIfCancellationRequested(); Uri requestUri = handshake.Request.RequestUri; WebSocketTransport transport = null; if (!options.Transports.TryGetWebSocketTransport(requestUri, out transport)) { throw new WebSocketException($"Unable to find transport for '{requestUri}'. " + "Available transports are: " + string.Join(", ", options.Transports.SelectMany((WebSocketTransport t) => t.Schemes).Distinct()) + "."); } connection = await transport.ConnectAsync(requestUri, options, cancellation).ConfigureAwait(continueOnCapturedContext: false); handshake.Request.IsSecure = transport.ShouldUseSsl(requestUri); handshake.Request.LocalEndPoint = connection.LocalEndPoint ?? WebSocketHttpRequest.NoAddress; handshake.Request.RemoteEndPoint = connection.RemoteEndPoint ?? WebSocketHttpRequest.NoAddress; webSocket = await NegotiateRequestAsync(handshake, connection, cancellation).ConfigureAwait(continueOnCapturedContext: false); return webSocket; } finally { if (webSocket == null) { SafeEnd.Dispose(connection, log); } } } private async Task<WebSocket> NegotiateRequestAsync(WebSocketHandshake handshake, NetworkConnection connection, CancellationToken cancellation) { if (handshake == null) { throw new ArgumentNullException("handshake"); } if (connection == null) { throw new ArgumentNullException("connection"); } cancellation.ThrowIfCancellationRequested(); Stream stream = connection.AsStream(); if (handshake.Request.IsSecure) { SslProtocols supportedSslProtocols = options.SupportedSslProtocols; string dnsSafeHost = handshake.Request.RequestUri.DnsSafeHost; SslStream secureStream = new SslStream(stream, leaveInnerStreamOpen: false, options.CertificateValidationHandler); await secureStream.AuthenticateAsClientAsync(dnsSafeHost, null, supportedSslProtocols, checkCertificateRevocation: false).ConfigureAwait(continueOnCapturedContext: false); connection = new SslNetworkConnection(secureStream, connection); stream = secureStream; } handshake.Factory = options.Standards.GetLast(); await WriteRequestAsync(handshake, stream).ConfigureAwait(continueOnCapturedContext: false); cancellation.ThrowIfCancellationRequested(); await ReadResponseAsync(handshake, stream).ConfigureAwait(continueOnCapturedContext: false); cancellation.ThrowIfCancellationRequested(); if (await (options.HttpAuthenticationHandler?.Invoke(handshake.Request, handshake.Response) ?? Task.FromResult(result: false)).ConfigureAwait(continueOnCapturedContext: false)) { throw new WebSocketException("HTTP authentication failed."); } return handshake.Factory.CreateWebSocket(connection, options, handshake.Request, handshake.Response, handshake.NegotiatedMessageExtensions); } private async Task WriteRequestAsync(WebSocketHandshake handshake, Stream stream) { Uri url = handshake.Request.RequestUri; string value2 = handshake.GenerateClientNonce(); int largeBufferSize = options.BufferManager.LargeBufferSize; using StreamWriter writer = new StreamWriter(stream, Encoding.ASCII, largeBufferSize, leaveOpen: true); Headers<RequestHeader> requestHeaders = handshake.Request.Headers; requestHeaders[RequestHeader.Host] = url.DnsSafeHost; requestHeaders[RequestHeader.Upgrade] = "websocket"; requestHeaders[RequestHeader.Connection] = "keep-alive, Upgrade"; requestHeaders[RequestHeader.WebSocketKey] = value2; requestHeaders[RequestHeader.WebSocketVersion] = handshake.Factory.Version.ToString(); requestHeaders[RequestHeader.CacheControl] = "no-cache"; requestHeaders[RequestHeader.Pragma] = "no-cache"; foreach (IWebSocketMessageExtension messageExtension in handshake.Factory.MessageExtensions) { requestHeaders.Add(RequestHeader.WebSocketExtensions, messageExtension.ToString()); } string[] subProtocols = options.SubProtocols; foreach (string value3 in subProtocols) { requestHeaders.Add(RequestHeader.WebSocketProtocol, value3); } writer.NewLine = "\r\n"; await writer.WriteAsync("GET ").ConfigureAwait(continueOnCapturedContext: false); await writer.WriteAsync(url.PathAndQuery).ConfigureAwait(continueOnCapturedContext: false); await writer.WriteLineAsync(" HTTP/1.1").ConfigureAwait(continueOnCapturedContext: false); foreach (KeyValuePair<string, Headers<RequestHeader>.ValueCollection> item in requestHeaders) { string headerName = item.Key; foreach (string value in item.Value) { await writer.WriteAsync(headerName).ConfigureAwait(continueOnCapturedContext: false); await writer.WriteAsync(": ").ConfigureAwait(continueOnCapturedContext: false); await writer.WriteLineAsync(value).ConfigureAwait(continueOnCapturedContext: false); } } await writer.WriteLineAsync().ConfigureAwait(continueOnCapturedContext: false); await writer.FlushAsync().ConfigureAwait(continueOnCapturedContext: false); } private async Task ReadResponseAsync(WebSocketHandshake handshake, Stream stream) { int largeBufferSize = options.BufferManager.LargeBufferSize; using (StreamReader reader = new StreamReader(stream, Encoding.ASCII, detectEncodingFromByteOrderMarks: false, largeBufferSize, leaveOpen: true)) { Headers<ResponseHeader> responseHeaders = handshake.Response.Headers; string text = (await reader.ReadLineAsync().ConfigureAwait(continueOnCapturedContext: false)) ?? string.Empty; if (!HttpHelper.TryParseHttpResponse(text, out handshake.Response.Status, out handshake.Response.StatusDescription)) { if (string.IsNullOrEmpty(text)) { throw new WebSocketException("Empty response. Probably connection is closed by remote party."); } throw new WebSocketException("Invalid handshake response: " + text + "."); } if (handshake.Response.Status != HttpStatusCode.SwitchingProtocols) { throw new WebSocketException("Invalid handshake response: " + text + "."); } string text2 = await reader.ReadLineAsync().ConfigureAwait(continueOnCapturedContext: false); while (!string.IsNullOrEmpty(text2)) { responseHeaders.TryParseAndAdd(text2); text2 = await reader.ReadLineAsync().ConfigureAwait(continueOnCapturedContext: false); } handshake.Response.ThrowIfInvalid(handshake.ComputeHandshake()); } ParseWebSocketExtensions(handshake); SelectExtensions(handshake); } private void SelectExtensions(WebSocketHandshake handshake) { if (handshake == null) { throw new ArgumentNullException("handshake"); } foreach (WebSocketExtension responseExtension in handshake.Response.WebSocketExtensions) { IWebSocketMessageExtension webSocketMessageExtension = handshake.Factory.MessageExtensions.SingleOrDefault((IWebSocketMessageExtension x) => x.Name.Equals(responseExtension.Name, StringComparison.OrdinalIgnoreCase)); if (webSocketMessageExtension != null && webSocketMessageExtension.TryNegotiate(handshake.Request, out var _, out var context)) { handshake.NegotiatedMessageExtensions.Add(context); } } } private void ParseWebSocketExtensions(WebSocketHandshake handshake) { if (handshake == null) { throw new ArgumentNullException("handshake"); } Headers<ResponseHeader> headers = handshake.Response.Headers; if (!headers.Contains(ResponseHeader.WebSocketExtensions)) { return; } foreach (string value in headers.GetValues(ResponseHeader.WebSocketExtensions)) { List<WebSocketExtensionOption> list = new List<WebSocketExtensionOption>(); string text = null; foreach (KeyValuePair<string, string> item in HeadersHelper.SplitAndTrimKeyValue(value, ';', '=', StringSplitOptions.RemoveEmptyEntries)) { if (text == null) { text = item.Value; } else if (string.IsNullOrEmpty(item.Key)) { list.Add(new WebSocketExtensionOption(item.Value, clientAvailableOption: true)); } else { list.Add(new WebSocketExtensionOption(item.Key, item.Value)); } } if (string.IsNullOrEmpty(text)) { throw new WebSocketException("Wrong value '" + headers[ResponseHeader.WebSocketExtensions] + "' of " + Headers<ResponseHeader>.GetHeaderName(ResponseHeader.WebSocketExtensions) + " header in request."); } handshake.Response.WebSocketExtensions.Add(new WebSocketExtension(text, list)); } } } public enum WebSocketCloseReason : short { NormalClose = 1000, GoingAway = 1001, ProtocolError = 1002, UnacceptableDataType = 1003, InvalidData = 1007, MessageViolatesPolicy = 1008, MessageToLarge = 1009, ExtensionRequired = 1010, UnexpectedCondition = 1011, TLSFailure = 105 } public class WebSocketException : Exception { public WebSocketException(string message) : base(message) { } public WebSocketException(string message, Exception inner) : base(message, inner) { } } [PublicAPI] public abstract class WebSocketFactory { public abstract short Version { get; } public WebSocketMessageExtensionCollection MessageExtensions { get; private set; } protected WebSocketFactory() { MessageExtensions = new WebSocketMessageExtensionCollection(); } public abstract WebSocket CreateWebSocket(NetworkConnection networkConnection, WebSocketListenerOptions options, WebSocketHttpRequest httpRequest, WebSocketHttpResponse httpResponse, List<IWebSocketMessageExtensionContext> negotiatedExtensions); public virtual WebSocketFactory Clone() { WebSocketFactory webSocketFactory = (WebSocketFactory)MemberwiseClone(); webSocketFactory.MessageExtensions = new WebSocketMessageExtensionCollection(); foreach (IWebSocketMessageExtension messageExtension in MessageExtensions) { webSocketFactory.MessageExtensions.Add(messageExtension.Clone()); } return webSocketFactory; } } public sealed class WebSocketListener : IDisposable { private const int STATE_STOPPED = 0; private const int STATE_STARTING = 1; private const int STATE_STARTED = 2; private const int STATE_STOPPING = 3; private const int STATE_DISPOSED = 5; private static readonly Listener[] EmptyListeners = new Listener[0]; private static readonly EndPoint[] EmptyEndPoints = new EndPoint[0]; private readonly ILogger log; private readonly HttpNegotiationQueue negotiationQueue; private readonly WebSocketListenerOptions options; private readonly Uri[] listenEndPoints; private volatile AsyncConditionSource stopConditionSource; private volatile Listener[] listeners; private volatile EndPoint[] localEndPoints; private volatile int state; public bool IsStarted => state == 2; public IReadOnlyCollection<EndPoint> LocalEndpoints => (IReadOnlyCollection<EndPoint>)(object)localEndPoints; public WebSocketListener(IPEndPoint endpoint) : this(endpoint, new WebSocketListenerOptions()) { } public WebSocketListener(IPEndPoint endpoint, WebSocketListenerOptions options) : this(new Uri[1] { new Uri("tcp://" + endpoint) }, options) { } public WebSocketListener(Uri[] listenEndPoints, WebSocketListenerOptions options) { if (listenEndPoints == null) { throw new ArgumentNullException("listenEndPoints"); } if (listenEndPoints.Length == 0) { throw new ArgumentException("At least one prefix should be specified.", "listenEndPoints"); } if (listenEndPoints.Any((Uri p) => p == null)) { throw new ArgumentException("Null objects passed in array.", "listenEndPoints"); } if (options == null) { throw new ArgumentNullException("options"); } options.CheckCoherence(); this.options = options.Clone(); if (this.options.BufferManager == null) { this.options.BufferManager = BufferManager.CreateBufferManager(this.options.SendBufferSize * 100, this.options.SendBufferSize); } if (this.options.Logger == null) { this.options.Logger = NullLogger.Instance; } log = this.options.Logger; listeners = EmptyListeners; localEndPoints = EmptyEndPoints; this.listenEndPoints = listenEndPoints; negotiationQueue = new HttpNegotiationQueue(options.Standards, options.ConnectionExtensions, this.options); } public async Task StartAsync() { if (options.Standards.Count <= 0) { throw new WebSocketException("There are no WebSocket standards. Please, register standards using WebSocketListenerOptions.Standards."); } if (options.Transports.Count <= 0) { throw new WebSocketException("There are no WebSocket transports. Please, register transports using WebSocketListenerOptions.Transports."); } if (Interlocked.CompareExchange(ref state, 1, 0) != 0) { throw new WebSocketException("Failed to start listener from current state. Maybe it is disposed or already started."); } options.SetUsed(isUsed: true); Listener[] listeners = null; try { if (log.IsDebugEnabled) { log.Debug("WebSocketListener is starting."); } Tuple<Uri, WebSocketTransport>[] endPoints = new Tuple<Uri, WebSocketTransport>[listenEndPoints.Length]; for (int j = 0; j < listenEndPoints.Length; j++) { Uri uri = listenEndPoints[j]; WebSocketTransport transport = null; if (!options.Transports.TryGetWebSocketTransport(uri, out transport)) { string arg = string.Join(", ", options.Transports.SelectMany((WebSocketTransport t) => t.Schemes).Distinct()); throw new WebSocketException($"Unable to find transport for '{uri}'. Available transports are: {arg}."); } endPoints[j] = Tuple.Create(uri, transport); } listeners = new Listener[endPoints.Length]; for (int i = 0; i < endPoints.Length; i++) { Listener[] array = listeners; int num = i; array[num] = await endPoints[i].Item2.ListenAsync(endPoints[i].Item1, options).ConfigureAwait(continueOnCapturedContext: false); } this.listeners = listeners; localEndPoints = this.listeners.SelectMany((Listener l) => l.LocalEndpoints).ToArray(); stopConditionSource = new AsyncConditionSource(isSet: true) { ContinueOnCapturedContext = false }; if (Interlocked.CompareExchange(ref state, 2, 1) != 1) { throw new WebSocketException("Failed to start listener from current state. Maybe it is disposed."); } AcceptConnectionsAsync().LogFault(log, null, "StartAsync", "E:\\D\\Visual Studio\\Projects\\RoR2Stuff\\WebSocketListener\\vtortola.WebSockets\\WebSocketListener.cs", 117); if (log.IsDebugEnabled) { log.Debug("WebSocketListener is started."); } listeners = null; } catch { options.SetUsed(isUsed: false); throw; } finally { Interlocked.CompareExchange(ref state, 0, 1); if (listeners != null) { Listener[] array2 = listeners; for (int k = 0; k < array2.Length; k++) { SafeEnd.Dispose(array2[k]); } this.listeners = EmptyListeners; localEndPoints = EmptyEndPoints; stopConditionSource = null; } } } public async Task StopAsync() { if (Interlocked.CompareExchange(ref state, 3, 2) != 2) { throw new WebSocketException("Failed to stop listener from current state. Maybe it is disposed or not started."); } options.SetUsed(isUsed: false); AsyncConditionSource asyncConditionSource = stopConditionSource; if (log.IsDebugEnabled) { log.Debug("WebSocketListener is stopping."); } localEndPoints = EmptyEndPoints; Listener[] array = Interlocked.Exchange(ref listeners, EmptyListeners); for (int i = 0; i < array.Length; i++) { SafeEnd.Dispose(array[i], log); } if (asyncConditionSource != null) { await asyncConditionSource; } if (Interlocked.CompareExchange(ref state, 0, 3) != 3) { throw new WebSocketException("Failed to stop listener from current state. Maybe it is disposed."); } if (log.IsDebugEnabled) { log.Debug("WebSocketListener is stopped."); } } private async Task AcceptConnectionsAsync() { await Task.Yield(); Listener[] listeners = this.listeners; Task<NetworkConnection>[] acceptTasks = new Task<NetworkConnection>[listeners.Length]; int acceptOffset = 0; try { while (IsStarted) { for (int i = 0; i < acceptTasks.Length; i++) { if (acceptTasks[i] == null) { try { acceptTasks[i] = listeners[i].AcceptConnectionAsync(); } catch (Exception ex) when (!(ex is ThreadAbortException)) { acceptTasks[i] = TaskHelper.FailedTask<NetworkConnection>(ex); } } } await Task.WhenAny(acceptTasks).ConfigureAwait(continueOnCapturedContext: false); if (acceptOffset == 65535) { acceptOffset = 0; } acceptOffset++; for (int j = 0; j < acceptTasks.Length; j++) { int num = (acceptOffset + j) % acceptTasks.Length; Task<NetworkConnection> task = acceptTasks[num]; if (task != null && task.IsCompleted) { acceptTasks[num] = null; AcceptNewConnection(task, listeners[num]); } } } } finally { CleanupPendingConnections(acceptTasks); } } private void CleanupPendingConnections(Task<NetworkConnection>[] acceptTasks) { if (acceptTasks == null) { throw new ArgumentNullException("acceptTasks"); } for (int i = 0; i < acceptTasks.Length; i++) { acceptTasks[i]?.ContinueWith(delegate(Task<NetworkConnection> t) { SafeEnd.Dispose(t.Result, log); }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current).LogFault(log, null, "CleanupPendingConnections", "E:\\D\\Visual Studio\\Projects\\RoR2Stuff\\WebSocketListener\\vtortola.WebSockets\\WebSocketListener.cs", 234); } Array.Clear(acceptTasks, 0, acceptTasks.Length); } private void AcceptNewConnection(Task<NetworkConnection> acceptTask, Listener listener) { if (acceptTask == null) { throw new ArgumentNullException("acceptTask"); } if (listener == null) { throw new ArgumentNullException("listener"); } Exception ex = acceptTask.Exception.Unwrap(); if (acceptTask.Status != TaskStatus.RanToCompletion) { if (log.IsDebugEnabled && ex != null && !(ex is OperationCanceledException)) { log.Debug($"Accept from '{listener}' has failed.", ex); } return; } NetworkConnection result = acceptTask.Result; if (log.IsDebugEnabled) { log.Debug($"New client from '{result}' is connected."); } negotiationQueue.Queue(result); } public async Task<WebSocket> AcceptWebSocketAsync(CancellationToken token) { try { WebSocketNegotiationResult webSocketNegotiationResult = await negotiationQueue.DequeueAsync(token).ConfigureAwait(continueOnCapturedContext: false); if (webSocketNegotiationResult.Error != null) { if (log.IsDebugEnabled && !(webSocketNegotiationResult.Error.SourceException.Unwrap() is OperationCanceledException)) { log.Debug("AcceptWebSocketAsync is complete with error.", webSocketNegotiationResult.Error.SourceException); } webSocketNegotiationResult.Error.Throw(); return null; } return webSocketNegotiationResult.Result; } catch (OperationCanceledException) { return null; } } public void Dispose() { if (Interlocked.Exchange(ref state, 5) != 5) { stopConditionSource?.Set(); localEndPoints = EmptyEndPoints; Listener[] array = Interlocked.Exchange(ref listeners, EmptyListeners); for (int i = 0; i < array.Length; i++) { SafeEnd.Dispose(array[i], log); } SafeEnd.Dispose(negotiationQueue, log); } } } [PublicAPI] public sealed class WebSocketListenerOptions { public const int DEFAULT_SEND_BUFFER_SIZE = 8192; public static readonly string[] NoSubProtocols = new string[0]; [NotNull] public WebSocketTransportCollection Transports { get; private set; } [NotNull] public WebSocketFactoryCollection Standards { get; private set; } [NotNull] public WebSocketConnectionExtensionCollection ConnectionExtensions { get; private set; } public TimeSpan PingTimeout { get; set; } public TimeSpan PingInterval { get { if (!(PingTimeout > TimeSpan.Zero)) { return TimeSpan.FromSeconds(5.0); } return TimeSpan.FromTicks(PingTimeout.Ticks / 3); } } public int NegotiationQueueCapacity { get; set; } public int ParallelNegotiations { get; set; } public TimeSpan NegotiationTimeout { get; set; } public int SendBufferSize { get; set; } public string[] SubProtocols { get; set; } public BufferManager BufferManager { get; set; } public HttpAuthenticationCallback HttpAuthenticationHandler { get; set; } public RemoteCertificateValidationCallback CertificateValidationHandler { get; set; } public SslProtocols SupportedSslProtocols { get; set; } public PingMode PingMode { get; set; } public IHttpFallback HttpFallback { get; set; } public ILogger Logger { get; set; } public WebSocketListenerOptions() { PingTimeout = TimeSpan.FromSeconds(5.0); Transports = new WebSocketTransportCollection(); Standards = new WebSocketFactoryCollection(); ConnectionExtensions = new WebSocketConnectionExtensionCollection(); NegotiationQueueCapacity = Environment.ProcessorCount * 10; ParallelNegotiations = Environment.ProcessorCount * 2; NegotiationTimeout = TimeSpan.FromSeconds(5.0); SendBufferSize = 8192; SubProtocols = NoSubProtocols; HttpAuthenticationHandler = null; CertificateValidationHandler = null; PingMode = PingMode.LatencyControl; SupportedSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; Logger = NullLogger.Instance; } public void CheckCoherence() { if (PingTimeout <= TimeSpan.Zero) { PingTimeout = Timeout.InfiniteTimeSpan; } if (PingTimeout <= TimeSpan.FromSeconds(1.0)) { PingTimeout = TimeSpan.FromSeconds(1.0); } if (NegotiationQueueCapacity < 0) { throw new WebSocketException(string.Format("{0} must be 0 or more. Actual value: {1}", "NegotiationQueueCapacity", NegotiationQueueCapacity)); } if (ParallelNegotiations < 1) { throw new WebSocketException(string.Format("{0} cannot be less than 1. Actual value: {1}", "ParallelNegotiations", ParallelNegotiations)); } if (NegotiationTimeout == TimeSpan.Zero) { NegotiationTimeout = Timeout.InfiniteTimeSpan; } if (SendBufferSize < 1024) { throw new WebSocketException(string.Format("{0} must be bigger than 1024. Actual value: {1}", "SendBufferSize", SendBufferSize)); } if (BufferManager != null && BufferManager.LargeBufferSize < SendBufferSize) { throw new WebSocketException("WebSocketListenerOptions.BufferManager.LargeBufferSize must be larger or equals to WebSocketListenerOptions.SendBufferSize. " + string.Format("Value of {0}: {1}. Value of {2}: {3}.", "SendBufferSize", SendBufferSize, "LargeBufferSize", BufferManager.LargeBufferSize)); } if (Logger == null) { throw new WebSocketException(string.Format("{0} should be set. You can use {1}.{2} to disable logging.", Logger, "NullLogger", "Instance")); } } public WebSocketListenerOptions Clone() { WebSocketListenerOptions obj = (WebSocketListenerOptions)MemberwiseClone(); obj.SubProtocols = (string[])SubProtocols.Clone(); obj.Transports = Transports.Clone(); obj.Standards = Standards.Clone(); obj.ConnectionExtensions = ConnectionExtensions.Clone(); return obj; } public void SetUsed(bool isUsed) { Standards.SetUsed(isUsed); foreach (WebSocketFactory standard in Standards) { standard.MessageExtensions.SetUsed(isUsed: true); } ConnectionExtensions.SetUsed(isUsed); Transports.SetUsed(isUsed); } } public static class WebSocketStringExtensions { private static readonly UTF8Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); [ItemCanBeNull] [NotNull] public static async Task<string> ReadStringAsync([NotNull] this WebSocket webSocket, CancellationToken cancellationToken = default(CancellationToken)) { if (webSocket == null) { throw new ArgumentNullException("webSocket"); } using WebSocketMessageReadStream readStream = await webSocket.ReadMessageAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (readStream == null) { return null; } using StreamReader reader = new StreamReader(readStream, Utf8NoBom); return await reader.ReadToEndAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task WriteStringAsync([NotNull] this WebSocket webSocket, [NotNull] string data, CancellationToken cancellationToken = default(CancellationToken)) { if (webSocket == null) { throw new Argume
plugins/Microsoft.Bcl.AsyncInterfaces.dll
Decompiled 2 years agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; 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(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Bcl.AsyncInterfaces")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides the IAsyncEnumerable<T> and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0.\r\n\r\nCommonly Used Types:\r\nSystem.IAsyncDisposable\r\nSystem.Collections.Generic.IAsyncEnumerable\r\nSystem.Collections.Generic.IAsyncEnumerator")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System { public interface IAsyncDisposable { ValueTask DisposeAsync(); } } 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.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)); } public interface IAsyncEnumerator<out T> : IAsyncDisposable { T Current { get; } ValueTask<bool> MoveNextAsync(); } } 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 { [StructLayout(LayoutKind.Auto)] public struct AsyncIteratorMethodBuilder { private AsyncTaskMethodBuilder _methodBuilder; private object _id; internal object ObjectIdForDebugger => _id ?? Interlocked.CompareExchange(ref _id, new object(), null) ?? _id; public static AsyncIteratorMethodBuilder Create() { AsyncIteratorMethodBuilder result = default(AsyncIteratorMethodBuilder); result._methodBuilder = AsyncTaskMethodBuilder.Create(); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void MoveNext<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { _methodBuilder.Start(ref stateMachine); } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } public void Complete() { _methodBuilder.SetResult(); } } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public sealed class AsyncIteratorStateMachineAttribute : StateMachineAttribute { public AsyncIteratorStateMachineAttribute(Type stateMachineType) : base(stateMachineType) { } } [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredAsyncDisposable { private readonly IAsyncDisposable _source; private readonly bool _continueOnCapturedContext; internal ConfiguredAsyncDisposable(IAsyncDisposable source, bool continueOnCapturedContext) { _source = source; _continueOnCapturedContext = continueOnCapturedContext; } public ConfiguredValueTaskAwaitable DisposeAsync() { return _source.DisposeAsync().ConfigureAwait(_continueOnCapturedContext); } } [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredCancelableAsyncEnumerable<T> { [StructLayout(LayoutKind.Auto)] public readonly struct Enumerator { private readonly IAsyncEnumerator<T> _enumerator; private readonly bool _continueOnCapturedContext; public T Current => _enumerator.Current; internal Enumerator(IAsyncEnumerator<T> enumerator, bool continueOnCapturedContext) { _enumerator = enumerator; _continueOnCapturedContext = continueOnCapturedContext; } public ConfiguredValueTaskAwaitable<bool> MoveNextAsync() { return _enumerator.MoveNextAsync().ConfigureAwait(_continueOnCapturedContext); } public ConfiguredValueTaskAwaitable DisposeAsync() { return _enumerator.DisposeAsync().ConfigureAwait(_continueOnCapturedContext); } } private readonly IAsyncEnumerable<T> _enumerable; private readonly CancellationToken _cancellationToken; private readonly bool _continueOnCapturedContext; internal ConfiguredCancelableAsyncEnumerable(IAsyncEnumerable<T> enumerable, bool continueOnCapturedContext, CancellationToken cancellationToken) { _enumerable = enumerable; _continueOnCapturedContext = continueOnCapturedContext; _cancellationToken = cancellationToken; } public ConfiguredCancelableAsyncEnumerable<T> ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredCancelableAsyncEnumerable<T>(_enumerable, continueOnCapturedContext, _cancellationToken); } public ConfiguredCancelableAsyncEnumerable<T> WithCancellation(CancellationToken cancellationToken) { return new ConfiguredCancelableAsyncEnumerable<T>(_enumerable, _continueOnCapturedContext, cancellationToken); } public Enumerator GetAsyncEnumerator() { return new Enumerator(_enumerable.GetAsyncEnumerator(_cancellationToken), _continueOnCapturedContext); } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class EnumeratorCancellationAttribute : Attribute { } } namespace System.Threading.Tasks { public static class TaskAsyncEnumerableExtensions { public static ConfiguredAsyncDisposable ConfigureAwait(this IAsyncDisposable source, bool continueOnCapturedContext) { return new ConfiguredAsyncDisposable(source, continueOnCapturedContext); } public static ConfiguredCancelableAsyncEnumerable<T> ConfigureAwait<T>(this IAsyncEnumerable<T> source, bool continueOnCapturedContext) { return new ConfiguredCancelableAsyncEnumerable<T>(source, continueOnCapturedContext, default(CancellationToken)); } public static ConfiguredCancelableAsyncEnumerable<T> WithCancellation<T>(this IAsyncEnumerable<T> source, CancellationToken cancellationToken) { return new ConfiguredCancelableAsyncEnumerable<T>(source, continueOnCapturedContext: true, cancellationToken); } } } namespace System.Threading.Tasks.Sources { [StructLayout(LayoutKind.Auto)] public struct ManualResetValueTaskSourceCore<TResult> { private Action<object> _continuation; private object _continuationState; private ExecutionContext _executionContext; private object _capturedContext; private bool _completed; private TResult _result; private ExceptionDispatchInfo _error; private short _version; public bool RunContinuationsAsynchronously { get; set; } public short Version => _version; public void Reset() { _version++; _completed = false; _result = default(TResult); _error = null; _executionContext = null; _capturedContext = null; _continuation = null; _continuationState = null; } public void SetResult(TResult result) { _result = result; SignalCompletion(); } public void SetException(Exception error) { _error = ExceptionDispatchInfo.Capture(error); SignalCompletion(); } public ValueTaskSourceStatus GetStatus(short token) { ValidateToken(token); if (_continuation != null && _completed) { if (_error != null) { if (!(_error.SourceException is OperationCanceledException)) { return ValueTaskSourceStatus.Faulted; } return ValueTaskSourceStatus.Canceled; } return ValueTaskSourceStatus.Succeeded; } return ValueTaskSourceStatus.Pending; } public TResult GetResult(short token) { ValidateToken(token); if (!_completed) { throw new InvalidOperationException(); } _error?.Throw(); return _result; } public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) { if (continuation == null) { throw new ArgumentNullException("continuation"); } ValidateToken(token); if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) { _executionContext = ExecutionContext.Capture(); } if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { SynchronizationContext current = SynchronizationContext.Current; if (current != null && current.GetType() != typeof(SynchronizationContext)) { _capturedContext = current; } else { TaskScheduler current2 = TaskScheduler.Current; if (current2 != TaskScheduler.Default) { _capturedContext = current2; } } } object obj = _continuation; if (obj == null) { _continuationState = state; obj = Interlocked.CompareExchange(ref _continuation, continuation, null); } if (obj == null) { return; } if (obj != System.Threading.Tasks.Sources.ManualResetValueTaskSourceCoreShared.s_sentinel) { throw new InvalidOperationException(); } object capturedContext = _capturedContext; if (capturedContext != null) { if (!(capturedContext is SynchronizationContext synchronizationContext)) { if (capturedContext is TaskScheduler scheduler) { Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, scheduler); } } else { synchronizationContext.Post(delegate(object s) { Tuple<Action<object>, object> tuple = (Tuple<Action<object>, object>)s; tuple.Item1(tuple.Item2); }, Tuple.Create(continuation, state)); } } else { Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } } private void ValidateToken(short token) { if (token != _version) { throw new InvalidOperationException(); } } private void SignalCompletion() { if (_completed) { throw new InvalidOperationException(); } _completed = true; if (_continuation == null && Interlocked.CompareExchange(ref _continuation, System.Threading.Tasks.Sources.ManualResetValueTaskSourceCoreShared.s_sentinel, null) == null) { return; } if (_executionContext != null) { ExecutionContext.Run(_executionContext, delegate(object s) { ((ManualResetValueTaskSourceCore<TResult>)s).InvokeContinuation(); }, this); } else { InvokeContinuation(); } } private void InvokeContinuation() { object capturedContext = _capturedContext; if (capturedContext != null) { if (!(capturedContext is SynchronizationContext synchronizationContext)) { if (capturedContext is TaskScheduler scheduler) { Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, scheduler); } } else { synchronizationContext.Post(delegate(object s) { Tuple<Action<object>, object> tuple = (Tuple<Action<object>, object>)s; tuple.Item1(tuple.Item2); }, Tuple.Create(_continuation, _continuationState)); } } else if (RunContinuationsAsynchronously) { Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { _continuation(_continuationState); } } } internal static class ManualResetValueTaskSourceCoreShared { internal static readonly Action<object> s_sentinel = CompletionSentinel; private static void CompletionSentinel(object _) { throw new InvalidOperationException(); } } }
plugins/Microsoft.CSharp.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Text; using System.Threading; using FxResources.Microsoft.CSharp; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Semantics; using Microsoft.CSharp.RuntimeBinder.Syntax; using Microsoft.CodeAnalysis; [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyDefaultAlias("Microsoft.CSharp")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Microsoft.CSharp")] [assembly: AssemblyFileVersion("4.700.19.56404")] [assembly: AssemblyInformationalVersion("3.1.0+0f7f38c4fd323b26da10cce95f857f77f0f09b48")] [assembly: AssemblyProduct("Microsoft® .NET Core")] [assembly: AssemblyTitle("Microsoft.CSharp")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("4.0.5.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class IsReadOnlyAttribute : Attribute { } } namespace FxResources.Microsoft.CSharp { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string InternalCompilerError => GetResourceString("InternalCompilerError"); internal static string BindPropertyFailedMethodGroup => GetResourceString("BindPropertyFailedMethodGroup"); internal static string BindPropertyFailedEvent => GetResourceString("BindPropertyFailedEvent"); internal static string BindInvokeFailedNonDelegate => GetResourceString("BindInvokeFailedNonDelegate"); internal static string NullReferenceOnMemberException => GetResourceString("NullReferenceOnMemberException"); internal static string BindCallToConditionalMethod => GetResourceString("BindCallToConditionalMethod"); internal static string BindToVoidMethodButExpectResult => GetResourceString("BindToVoidMethodButExpectResult"); internal static string EmptyDynamicView => GetResourceString("EmptyDynamicView"); internal static string GetValueonWriteOnlyProperty => GetResourceString("GetValueonWriteOnlyProperty"); internal static string BadBinaryOps => GetResourceString("BadBinaryOps"); internal static string BadIndexLHS => GetResourceString("BadIndexLHS"); internal static string BadIndexCount => GetResourceString("BadIndexCount"); internal static string BadUnaryOp => GetResourceString("BadUnaryOp"); internal static string NoImplicitConv => GetResourceString("NoImplicitConv"); internal static string NoExplicitConv => GetResourceString("NoExplicitConv"); internal static string ConstOutOfRange => GetResourceString("ConstOutOfRange"); internal static string AmbigBinaryOps => GetResourceString("AmbigBinaryOps"); internal static string AmbigUnaryOp => GetResourceString("AmbigUnaryOp"); internal static string ValueCantBeNull => GetResourceString("ValueCantBeNull"); internal static string NoSuchMember => GetResourceString("NoSuchMember"); internal static string ObjectRequired => GetResourceString("ObjectRequired"); internal static string AmbigCall => GetResourceString("AmbigCall"); internal static string BadAccess => GetResourceString("BadAccess"); internal static string AssgLvalueExpected => GetResourceString("AssgLvalueExpected"); internal static string NoConstructors => GetResourceString("NoConstructors"); internal static string PropertyLacksGet => GetResourceString("PropertyLacksGet"); internal static string ObjectProhibited => GetResourceString("ObjectProhibited"); internal static string AssgReadonly => GetResourceString("AssgReadonly"); internal static string AssgReadonlyStatic => GetResourceString("AssgReadonlyStatic"); internal static string AssgReadonlyProp => GetResourceString("AssgReadonlyProp"); internal static string UnsafeNeeded => GetResourceString("UnsafeNeeded"); internal static string BadBoolOp => GetResourceString("BadBoolOp"); internal static string MustHaveOpTF => GetResourceString("MustHaveOpTF"); internal static string ConstOutOfRangeChecked => GetResourceString("ConstOutOfRangeChecked"); internal static string AmbigMember => GetResourceString("AmbigMember"); internal static string NoImplicitConvCast => GetResourceString("NoImplicitConvCast"); internal static string InaccessibleGetter => GetResourceString("InaccessibleGetter"); internal static string InaccessibleSetter => GetResourceString("InaccessibleSetter"); internal static string BadArity => GetResourceString("BadArity"); internal static string TypeArgsNotAllowed => GetResourceString("TypeArgsNotAllowed"); internal static string HasNoTypeVars => GetResourceString("HasNoTypeVars"); internal static string NewConstraintNotSatisfied => GetResourceString("NewConstraintNotSatisfied"); internal static string GenericConstraintNotSatisfiedRefType => GetResourceString("GenericConstraintNotSatisfiedRefType"); internal static string GenericConstraintNotSatisfiedNullableEnum => GetResourceString("GenericConstraintNotSatisfiedNullableEnum"); internal static string GenericConstraintNotSatisfiedNullableInterface => GetResourceString("GenericConstraintNotSatisfiedNullableInterface"); internal static string GenericConstraintNotSatisfiedValType => GetResourceString("GenericConstraintNotSatisfiedValType"); internal static string CantInferMethTypeArgs => GetResourceString("CantInferMethTypeArgs"); internal static string RefConstraintNotSatisfied => GetResourceString("RefConstraintNotSatisfied"); internal static string ValConstraintNotSatisfied => GetResourceString("ValConstraintNotSatisfied"); internal static string AmbigUDConv => GetResourceString("AmbigUDConv"); internal static string BindToBogus => GetResourceString("BindToBogus"); internal static string CantCallSpecialMethod => GetResourceString("CantCallSpecialMethod"); internal static string ConvertToStaticClass => GetResourceString("ConvertToStaticClass"); internal static string IncrementLvalueExpected => GetResourceString("IncrementLvalueExpected"); internal static string BadArgCount => GetResourceString("BadArgCount"); internal static string BadArgTypes => GetResourceString("BadArgTypes"); internal static string BadProtectedAccess => GetResourceString("BadProtectedAccess"); internal static string BindToBogusProp2 => GetResourceString("BindToBogusProp2"); internal static string BindToBogusProp1 => GetResourceString("BindToBogusProp1"); internal static string BadDelArgCount => GetResourceString("BadDelArgCount"); internal static string BadDelArgTypes => GetResourceString("BadDelArgTypes"); internal static string BadCtorArgCount => GetResourceString("BadCtorArgCount"); internal static string NonInvocableMemberCalled => GetResourceString("NonInvocableMemberCalled"); internal static string BadNamedArgument => GetResourceString("BadNamedArgument"); internal static string BadNamedArgumentForDelegateInvoke => GetResourceString("BadNamedArgumentForDelegateInvoke"); internal static string DuplicateNamedArgument => GetResourceString("DuplicateNamedArgument"); internal static string NamedArgumentUsedInPositional => GetResourceString("NamedArgumentUsedInPositional"); internal static string TypeArgumentRequiredForStaticCall => GetResourceString("TypeArgumentRequiredForStaticCall"); internal static string DynamicArgumentNeedsValue => GetResourceString("DynamicArgumentNeedsValue"); internal static string BadNonTrailingNamedArgument => GetResourceString("BadNonTrailingNamedArgument"); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString = null) { if (UsingResourceKeys()) { return defaultString ?? resourceKey; } string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text)) { return defaultString; } return text; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } } } namespace System.Numerics.Hashing { internal static class HashHelpers { public static readonly int RandomSeed = new Random().Next(int.MinValue, int.MaxValue); public static int Combine(int h1, int h2) { uint num = (uint)(h1 << 5) | ((uint)h1 >> 27); return ((int)num + h1) ^ h2; } } } namespace Microsoft.CSharp.RuntimeBinder { internal readonly struct ArgumentObject { internal readonly object Value; internal readonly CSharpArgumentInfo Info; internal readonly Type Type; public ArgumentObject(object value, CSharpArgumentInfo info, Type type) { Value = value; Info = info; Type = type; } } [EditorBrowsable(EditorBrowsableState.Never)] public static class Binder { public static CallSiteBinder BinaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0; bool flag = (flags & CSharpBinderFlags.BinaryOperationLogical) != 0; CSharpBinaryOperationFlags cSharpBinaryOperationFlags = CSharpBinaryOperationFlags.None; if (flag) { cSharpBinaryOperationFlags |= CSharpBinaryOperationFlags.LogicalOperation; } return new CSharpBinaryOperationBinder(operation, isChecked, cSharpBinaryOperationFlags, context, argumentInfo).TryGetExisting(); } public static CallSiteBinder Convert(CSharpBinderFlags flags, Type type, Type context) { CSharpConversionKind conversionKind = (((flags & CSharpBinderFlags.ConvertExplicit) != 0) ? CSharpConversionKind.ExplicitConversion : (((flags & CSharpBinderFlags.ConvertArrayIndex) != 0) ? CSharpConversionKind.ArrayCreationConversion : CSharpConversionKind.ImplicitConversion)); bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0; return new CSharpConvertBinder(type, conversionKind, isChecked, context).TryGetExisting(); } public static CallSiteBinder GetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return new CSharpGetIndexBinder(context, argumentInfo).TryGetExisting(); } public static CallSiteBinder GetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { bool resultIndexed = (flags & CSharpBinderFlags.ResultIndexed) != 0; return new CSharpGetMemberBinder(name, resultIndexed, context, argumentInfo).TryGetExisting(); } public static CallSiteBinder Invoke(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { bool flag = (flags & CSharpBinderFlags.ResultDiscarded) != 0; CSharpCallFlags cSharpCallFlags = CSharpCallFlags.None; if (flag) { cSharpCallFlags |= CSharpCallFlags.ResultDiscarded; } return new CSharpInvokeBinder(cSharpCallFlags, context, argumentInfo).TryGetExisting(); } public static CallSiteBinder InvokeMember(CSharpBinderFlags flags, string name, IEnumerable<Type> typeArguments, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { bool flag = (flags & CSharpBinderFlags.InvokeSimpleName) != 0; bool flag2 = (flags & CSharpBinderFlags.InvokeSpecialName) != 0; bool flag3 = (flags & CSharpBinderFlags.ResultDiscarded) != 0; CSharpCallFlags cSharpCallFlags = CSharpCallFlags.None; if (flag) { cSharpCallFlags |= CSharpCallFlags.SimpleNameCall; } if (flag2) { cSharpCallFlags |= CSharpCallFlags.EventHookup; } if (flag3) { cSharpCallFlags |= CSharpCallFlags.ResultDiscarded; } return new CSharpInvokeMemberBinder(cSharpCallFlags, name, context, typeArguments, argumentInfo).TryGetExisting(); } public static CallSiteBinder InvokeConstructor(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return new CSharpInvokeConstructorBinder(CSharpCallFlags.None, context, argumentInfo).TryGetExisting(); } public static CallSiteBinder IsEvent(CSharpBinderFlags flags, string name, Type context) { return new CSharpIsEventBinder(name, context).TryGetExisting(); } public static CallSiteBinder SetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { bool isCompoundAssignment = (flags & CSharpBinderFlags.ValueFromCompoundAssignment) != 0; bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0; return new CSharpSetIndexBinder(isCompoundAssignment, isChecked, context, argumentInfo).TryGetExisting(); } public static CallSiteBinder SetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { bool isCompoundAssignment = (flags & CSharpBinderFlags.ValueFromCompoundAssignment) != 0; bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0; return new CSharpSetMemberBinder(name, isCompoundAssignment, isChecked, context, argumentInfo).TryGetExisting(); } public static CallSiteBinder UnaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0; return new CSharpUnaryOperationBinder(operation, isChecked, context, argumentInfo).TryGetExisting(); } } internal static class BinderEquivalence { internal class BinderEqualityComparer : IEqualityComparer<ICSharpBinder> { public bool Equals(ICSharpBinder x, ICSharpBinder y) { return x.IsEquivalentTo(y); } public int GetHashCode(ICSharpBinder obj) { return obj.GetGetBinderEquivalenceHash(); } } private static int cachedBinderCount; private static readonly ConcurrentDictionary<ICSharpBinder, ICSharpBinder> binderEquivalenceCache = new ConcurrentDictionary<ICSharpBinder, ICSharpBinder>(2, 32, new BinderEqualityComparer()); internal static T TryGetExisting<T>(this T binder) where T : ICSharpBinder { ICSharpBinder orAdd = binderEquivalenceCache.GetOrAdd(binder, binder); if (orAdd == (object)binder) { int num = Interlocked.Increment(ref cachedBinderCount); if ((uint)num > 4096u) { binderEquivalenceCache.Clear(); cachedBinderCount = 0; } } return (T)orAdd; } } internal static class BinderHelper { private static MethodInfo s_DoubleIsNaN; private static MethodInfo s_SingleIsNaN; internal static DynamicMetaObject Bind(ICSharpBinder action, RuntimeBinder binder, DynamicMetaObject[] args, IEnumerable<CSharpArgumentInfo> arginfos, DynamicMetaObject onBindingError) { Expression[] array = new Expression[args.Length]; BindingRestrictions bindingRestrictions = BindingRestrictions.Empty; ICSharpInvokeOrInvokeMemberBinder callPayload = action as ICSharpInvokeOrInvokeMemberBinder; ParameterExpression parameterExpression = null; IEnumerator<CSharpArgumentInfo> enumerator = (arginfos ?? Array.Empty<CSharpArgumentInfo>()).GetEnumerator(); for (int i = 0; i < args.Length; i++) { DynamicMetaObject dynamicMetaObject = args[i]; CSharpArgumentInfo cSharpArgumentInfo = (enumerator.MoveNext() ? enumerator.Current : null); if (i == 0 && IsIncrementOrDecrementActionOnLocal(action)) { object value = dynamicMetaObject.Value; parameterExpression = (ParameterExpression)(array[0] = Expression.Variable((value != null) ? value.GetType() : typeof(object), "t0")); } else { array[i] = dynamicMetaObject.Expression; } BindingRestrictions restrictions = DeduceArgumentRestriction(i, callPayload, dynamicMetaObject, cSharpArgumentInfo); bindingRestrictions = bindingRestrictions.Merge(restrictions); if (cSharpArgumentInfo != null && cSharpArgumentInfo.LiteralConstant) { if (dynamicMetaObject.Value is double && double.IsNaN((double)dynamicMetaObject.Value)) { MethodInfo method = s_DoubleIsNaN ?? (s_DoubleIsNaN = typeof(double).GetMethod("IsNaN")); Expression expression = Expression.Call(null, method, dynamicMetaObject.Expression); bindingRestrictions = bindingRestrictions.Merge(BindingRestrictions.GetExpressionRestriction(expression)); } else if (dynamicMetaObject.Value is float && float.IsNaN((float)dynamicMetaObject.Value)) { MethodInfo method2 = s_SingleIsNaN ?? (s_SingleIsNaN = typeof(float).GetMethod("IsNaN")); Expression expression2 = Expression.Call(null, method2, dynamicMetaObject.Expression); bindingRestrictions = bindingRestrictions.Merge(BindingRestrictions.GetExpressionRestriction(expression2)); } else { Expression expression3 = Expression.Equal(dynamicMetaObject.Expression, Expression.Constant(dynamicMetaObject.Value, dynamicMetaObject.Expression.Type)); restrictions = BindingRestrictions.GetExpressionRestriction(expression3); bindingRestrictions = bindingRestrictions.Merge(restrictions); } } } try { Expression expression4 = binder.Bind(action, array, args, out var deferredBinding); if (deferredBinding != null) { expression4 = ConvertResult(deferredBinding.Expression, action); bindingRestrictions = deferredBinding.Restrictions.Merge(bindingRestrictions); return new DynamicMetaObject(expression4, bindingRestrictions); } if (parameterExpression != null) { DynamicMetaObject dynamicMetaObject2 = args[0]; expression4 = Expression.Block(new ParameterExpression[1] { parameterExpression }, Expression.Assign(parameterExpression, Expression.Convert(dynamicMetaObject2.Expression, dynamicMetaObject2.Value.GetType())), expression4, Expression.Assign(dynamicMetaObject2.Expression, Expression.Convert(parameterExpression, dynamicMetaObject2.Expression.Type))); } expression4 = ConvertResult(expression4, action); return new DynamicMetaObject(expression4, bindingRestrictions); } catch (RuntimeBinderException ex) { if (onBindingError != null) { return onBindingError; } return new DynamicMetaObject(Expression.Throw(Expression.New(typeof(RuntimeBinderException).GetConstructor(new Type[1] { typeof(string) }), Expression.Constant(ex.Message)), GetTypeForErrorMetaObject(action, args)), bindingRestrictions); } } public static void ValidateBindArgument(DynamicMetaObject argument, string paramName) { if (argument == null) { throw Error.ArgumentNull(paramName); } if (!argument.HasValue) { throw Error.DynamicArgumentNeedsValue(paramName); } } public static void ValidateBindArgument(DynamicMetaObject[] arguments, string paramName) { if (arguments != null) { for (int i = 0; i != arguments.Length; i++) { ValidateBindArgument(arguments[i], $"{paramName}[{i}]"); } } } private static bool IsTypeOfStaticCall(int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload) { if (parameterIndex == 0 && callPayload != null) { return callPayload.StaticCall; } return false; } private static bool IsComObject(object obj) { if (obj != null) { return Marshal.IsComObject(obj); } return false; } private static bool IsTransparentProxy(object obj) { return false; } private static bool IsDynamicallyTypedRuntimeProxy(DynamicMetaObject argument, CSharpArgumentInfo info) { return info != null && !info.UseCompileTimeType && (IsComObject(argument.Value) || IsTransparentProxy(argument.Value)); } private static BindingRestrictions DeduceArgumentRestriction(int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload, DynamicMetaObject argument, CSharpArgumentInfo info) { if (argument.Value != null && !IsTypeOfStaticCall(parameterIndex, callPayload) && !IsDynamicallyTypedRuntimeProxy(argument, info)) { return BindingRestrictions.GetTypeRestriction(argument.Expression, argument.RuntimeType); } return BindingRestrictions.GetInstanceRestriction(argument.Expression, argument.Value); } private static Expression ConvertResult(Expression binding, ICSharpBinder action) { if (action is CSharpInvokeConstructorBinder) { return binding; } if (binding.Type == typeof(void)) { if (action is ICSharpInvokeOrInvokeMemberBinder iCSharpInvokeOrInvokeMemberBinder && iCSharpInvokeOrInvokeMemberBinder.ResultDiscarded) { return Expression.Block(binding, Expression.Default(action.ReturnType)); } throw Error.BindToVoidMethodButExpectResult(); } if (binding.Type.IsValueType && !action.ReturnType.IsValueType) { return Expression.Convert(binding, action.ReturnType); } return binding; } private static Type GetTypeForErrorMetaObject(ICSharpBinder action, DynamicMetaObject[] args) { if (action is CSharpInvokeConstructorBinder) { return args[0].Value as Type; } return action.ReturnType; } private static bool IsIncrementOrDecrementActionOnLocal(ICSharpBinder action) { if (action is CSharpUnaryOperationBinder cSharpUnaryOperationBinder) { if (cSharpUnaryOperationBinder.Operation != ExpressionType.Increment) { return cSharpUnaryOperationBinder.Operation == ExpressionType.Decrement; } return true; } return false; } internal static T[] Cons<T>(T sourceHead, T[] sourceTail) { if (sourceTail == null || sourceTail.Length != 0) { T[] array = new T[sourceTail.Length + 1]; array[0] = sourceHead; sourceTail.CopyTo(array, 1); return array; } return new T[1] { sourceHead }; } internal static T[] Cons<T>(T sourceHead, T[] sourceMiddle, T sourceLast) { if (sourceMiddle == null || sourceMiddle.Length != 0) { T[] array = new T[sourceMiddle.Length + 2]; array[0] = sourceHead; array[^1] = sourceLast; sourceMiddle.CopyTo(array, 1); return array; } return new T[2] { sourceHead, sourceLast }; } internal static T[] ToArray<T>(IEnumerable<T> source) { if (source != null) { return source.ToArray(); } return Array.Empty<T>(); } internal static CallInfo CreateCallInfo(ref IEnumerable<CSharpArgumentInfo> argInfos, int discard) { int num = 0; List<string> list = new List<string>(); CSharpArgumentInfo[] array = (CSharpArgumentInfo[])(argInfos = ToArray(argInfos)); foreach (CSharpArgumentInfo cSharpArgumentInfo in array) { if (cSharpArgumentInfo.NamedArgument) { list.Add(cSharpArgumentInfo.Name); } num++; } return new CallInfo(num - discard, list); } internal static string GetCLROperatorName(this ExpressionType p) { return p switch { ExpressionType.Add => "op_Addition", ExpressionType.Subtract => "op_Subtraction", ExpressionType.Multiply => "op_Multiply", ExpressionType.Divide => "op_Division", ExpressionType.Modulo => "op_Modulus", ExpressionType.LeftShift => "op_LeftShift", ExpressionType.RightShift => "op_RightShift", ExpressionType.LessThan => "op_LessThan", ExpressionType.GreaterThan => "op_GreaterThan", ExpressionType.LessThanOrEqual => "op_LessThanOrEqual", ExpressionType.GreaterThanOrEqual => "op_GreaterThanOrEqual", ExpressionType.Equal => "op_Equality", ExpressionType.NotEqual => "op_Inequality", ExpressionType.And => "op_BitwiseAnd", ExpressionType.ExclusiveOr => "op_ExclusiveOr", ExpressionType.Or => "op_BitwiseOr", ExpressionType.AddAssign => "op_Addition", ExpressionType.SubtractAssign => "op_Subtraction", ExpressionType.MultiplyAssign => "op_Multiply", ExpressionType.DivideAssign => "op_Division", ExpressionType.ModuloAssign => "op_Modulus", ExpressionType.AndAssign => "op_BitwiseAnd", ExpressionType.ExclusiveOrAssign => "op_ExclusiveOr", ExpressionType.OrAssign => "op_BitwiseOr", ExpressionType.LeftShiftAssign => "op_LeftShift", ExpressionType.RightShiftAssign => "op_RightShift", ExpressionType.Negate => "op_UnaryNegation", ExpressionType.UnaryPlus => "op_UnaryPlus", ExpressionType.Not => "op_LogicalNot", ExpressionType.OnesComplement => "op_OnesComplement", ExpressionType.IsTrue => "op_True", ExpressionType.IsFalse => "op_False", ExpressionType.Increment => "op_Increment", ExpressionType.Decrement => "op_Decrement", _ => null, }; } internal static int AddArgHashes(int hash, Type[] typeArguments, CSharpArgumentInfo[] argInfos) { foreach (Type type in typeArguments) { hash = HashHelpers.Combine(hash, type.GetHashCode()); } return AddArgHashes(hash, argInfos); } internal static int AddArgHashes(int hash, CSharpArgumentInfo[] argInfos) { foreach (CSharpArgumentInfo cSharpArgumentInfo in argInfos) { hash = HashHelpers.Combine(hash, (int)cSharpArgumentInfo.Flags); string name = cSharpArgumentInfo.Name; if (!string.IsNullOrEmpty(name)) { hash = HashHelpers.Combine(hash, name.GetHashCode()); } } return hash; } internal static bool CompareArgInfos(Type[] typeArgs, Type[] otherTypeArgs, CSharpArgumentInfo[] argInfos, CSharpArgumentInfo[] otherArgInfos) { for (int i = 0; i < typeArgs.Length; i++) { if (typeArgs[i] != otherTypeArgs[i]) { return false; } } return CompareArgInfos(argInfos, otherArgInfos); } internal static bool CompareArgInfos(CSharpArgumentInfo[] argInfos, CSharpArgumentInfo[] otherArgInfos) { for (int i = 0; i < argInfos.Length; i++) { CSharpArgumentInfo cSharpArgumentInfo = argInfos[i]; CSharpArgumentInfo cSharpArgumentInfo2 = otherArgInfos[i]; if (cSharpArgumentInfo.Flags != cSharpArgumentInfo2.Flags || cSharpArgumentInfo.Name != cSharpArgumentInfo2.Name) { return false; } } return true; } } [EditorBrowsable(EditorBrowsableState.Never)] public sealed class CSharpArgumentInfo { internal static readonly CSharpArgumentInfo None = new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null); internal CSharpArgumentInfoFlags Flags { get; } internal string Name { get; } internal bool UseCompileTimeType => (Flags & CSharpArgumentInfoFlags.UseCompileTimeType) != 0; internal bool LiteralConstant => (Flags & CSharpArgumentInfoFlags.Constant) != 0; internal bool NamedArgument => (Flags & CSharpArgumentInfoFlags.NamedArgument) != 0; internal bool IsByRefOrOut => (Flags & (CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.IsOut)) != 0; internal bool IsOut => (Flags & CSharpArgumentInfoFlags.IsOut) != 0; internal bool IsStaticType => (Flags & CSharpArgumentInfoFlags.IsStaticType) != 0; private CSharpArgumentInfo(CSharpArgumentInfoFlags flags, string name) { Flags = flags; Name = name; } public static CSharpArgumentInfo Create(CSharpArgumentInfoFlags flags, string name) { return new CSharpArgumentInfo(flags, name); } } [EditorBrowsable(EditorBrowsableState.Never)] [Flags] public enum CSharpArgumentInfoFlags { None = 0, UseCompileTimeType = 1, Constant = 2, NamedArgument = 4, IsRef = 8, IsOut = 0x10, IsStaticType = 0x20 } internal sealed class CSharpBinaryOperationBinder : BinaryOperationBinder, ICSharpBinder { private readonly CSharpBinaryOperationFlags _binopFlags; private readonly CSharpArgumentInfo[] _argumentInfo; private readonly RuntimeBinder _binder; private readonly Type _callingContext; [ExcludeFromCodeCoverage] public string Name => null; public BindingFlag BindingFlags => (BindingFlag)0; public bool IsBinderThatCanHaveRefReceiver => false; internal bool IsLogicalOperation => (_binopFlags & CSharpBinaryOperationFlags.LogicalOperation) != 0; private bool IsChecked => _binder.IsChecked; public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return runtimeBinder.BindBinaryOperation(this, arguments, locals); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { string cLROperatorName = base.Operation.GetCLROperatorName(); SymbolTable.PopulateSymbolTableWithName(cLROperatorName, null, arguments[0].Type); SymbolTable.PopulateSymbolTableWithName(cLROperatorName, null, arguments[1].Type); } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return _argumentInfo[index]; } public CSharpBinaryOperationBinder(ExpressionType operation, bool isChecked, CSharpBinaryOperationFlags binaryOperationFlags, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(operation) { _binopFlags = binaryOperationFlags; _callingContext = callingContext; _argumentInfo = BinderHelper.ToArray(argumentInfo); _binder = new RuntimeBinder(callingContext, isChecked); } public int GetGetBinderEquivalenceHash() { int h = _callingContext?.GetHashCode() ?? 0; h = HashHelpers.Combine(h, (int)_binopFlags); if (IsChecked) { h = HashHelpers.Combine(h, 1); } h = HashHelpers.Combine(h, (int)base.Operation); return BinderHelper.AddArgHashes(h, _argumentInfo); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpBinaryOperationBinder cSharpBinaryOperationBinder)) { return false; } if (_binopFlags != cSharpBinaryOperationBinder._binopFlags || base.Operation != cSharpBinaryOperationBinder.Operation || IsChecked != cSharpBinaryOperationBinder.IsChecked || _callingContext != cSharpBinaryOperationBinder._callingContext) { return false; } return BinderHelper.CompareArgInfos(_argumentInfo, cSharpBinaryOperationBinder._argumentInfo); } public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { BinderHelper.ValidateBindArgument(target, "target"); BinderHelper.ValidateBindArgument(arg, "arg"); return BinderHelper.Bind(this, _binder, new DynamicMetaObject[2] { target, arg }, _argumentInfo, errorSuggestion); } } [Flags] internal enum CSharpBinaryOperationFlags { None = 0, MemberAccess = 1, LogicalOperation = 2 } [Flags] [EditorBrowsable(EditorBrowsableState.Never)] public enum CSharpBinderFlags { None = 0, CheckedContext = 1, InvokeSimpleName = 2, InvokeSpecialName = 4, BinaryOperationLogical = 8, ConvertExplicit = 0x10, ConvertArrayIndex = 0x20, ResultIndexed = 0x40, ValueFromCompoundAssignment = 0x80, ResultDiscarded = 0x100 } [Flags] internal enum CSharpCallFlags { None = 0, SimpleNameCall = 1, EventHookup = 2, ResultDiscarded = 4 } internal enum CSharpConversionKind { ImplicitConversion, ExplicitConversion, ArrayCreationConversion } internal sealed class CSharpConvertBinder : ConvertBinder, ICSharpBinder { private readonly RuntimeBinder _binder; private readonly Type _callingContext; [ExcludeFromCodeCoverage] public string Name => null; public BindingFlag BindingFlags => (BindingFlag)0; public bool IsBinderThatCanHaveRefReceiver => false; private CSharpConversionKind ConversionKind { get; } private bool IsChecked => _binder.IsChecked; public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { if (!base.Explicit) { return runtimeBinder.BindImplicitConversion(arguments, base.Type, locals, ConversionKind == CSharpConversionKind.ArrayCreationConversion); } return runtimeBinder.BindExplicitConversion(arguments, base.Type, locals); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return CSharpArgumentInfo.None; } public CSharpConvertBinder(Type type, CSharpConversionKind conversionKind, bool isChecked, Type callingContext) : base(type, conversionKind == CSharpConversionKind.ExplicitConversion) { ConversionKind = conversionKind; _callingContext = callingContext; _binder = new RuntimeBinder(callingContext, isChecked); } public int GetGetBinderEquivalenceHash() { int h = _callingContext?.GetHashCode() ?? 0; h = HashHelpers.Combine(h, (int)ConversionKind); if (IsChecked) { h = HashHelpers.Combine(h, 1); } return HashHelpers.Combine(h, base.Type.GetHashCode()); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpConvertBinder cSharpConvertBinder)) { return false; } if (ConversionKind != cSharpConvertBinder.ConversionKind || IsChecked != cSharpConvertBinder.IsChecked || _callingContext != cSharpConvertBinder._callingContext || base.Type != cSharpConvertBinder.Type) { return false; } return true; } public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { BinderHelper.ValidateBindArgument(target, "target"); return BinderHelper.Bind(this, _binder, new DynamicMetaObject[1] { target }, null, errorSuggestion); } } internal sealed class CSharpGetIndexBinder : GetIndexBinder, ICSharpBinder { private readonly CSharpArgumentInfo[] _argumentInfo; private readonly RuntimeBinder _binder; private readonly Type _callingContext; public string Name => "$Item$"; public BindingFlag BindingFlags => BindingFlag.BIND_RVALUEREQUIRED; public bool IsBinderThatCanHaveRefReceiver => true; public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { Expr optionalIndexerArguments = runtimeBinder.CreateArgumentListEXPR(arguments, locals, 1, arguments.Length); return runtimeBinder.BindProperty(this, arguments[0], locals[0], optionalIndexerArguments); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { SymbolTable.PopulateSymbolTableWithName("$Item$", null, arguments[0].Type); } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return _argumentInfo[index]; } public CSharpGetIndexBinder(Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(BinderHelper.CreateCallInfo(ref argumentInfo, 1)) { _argumentInfo = argumentInfo as CSharpArgumentInfo[]; _callingContext = callingContext; _binder = new RuntimeBinder(callingContext); } public int GetGetBinderEquivalenceHash() { int hash = _callingContext?.GetHashCode() ?? 0; return BinderHelper.AddArgHashes(hash, _argumentInfo); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpGetIndexBinder cSharpGetIndexBinder)) { return false; } if (_callingContext != cSharpGetIndexBinder._callingContext || _argumentInfo.Length != cSharpGetIndexBinder._argumentInfo.Length) { return false; } return BinderHelper.CompareArgInfos(_argumentInfo, cSharpGetIndexBinder._argumentInfo); } public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion) { BinderHelper.ValidateBindArgument(target, "target"); BinderHelper.ValidateBindArgument(indexes, "indexes"); return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, indexes), _argumentInfo, errorSuggestion); } } internal sealed class CSharpGetMemberBinder : GetMemberBinder, IInvokeOnGetBinder, ICSharpBinder { private readonly CSharpArgumentInfo[] _argumentInfo; private readonly RuntimeBinder _binder; private readonly Type _callingContext; public BindingFlag BindingFlags => BindingFlag.BIND_RVALUEREQUIRED; public bool IsBinderThatCanHaveRefReceiver => false; bool IInvokeOnGetBinder.InvokeOnGet => !ResultIndexed; private bool ResultIndexed { get; } public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return runtimeBinder.BindProperty(this, arguments[0], locals[0], null); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { SymbolTable.PopulateSymbolTableWithName(base.Name, null, arguments[0].Type); } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return _argumentInfo[index]; } public CSharpGetMemberBinder(string name, bool resultIndexed, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(name, ignoreCase: false) { ResultIndexed = resultIndexed; _argumentInfo = BinderHelper.ToArray(argumentInfo); _callingContext = callingContext; _binder = new RuntimeBinder(callingContext); } public int GetGetBinderEquivalenceHash() { int h = _callingContext?.GetHashCode() ?? 0; if (ResultIndexed) { h = HashHelpers.Combine(h, 1); } h = HashHelpers.Combine(h, base.Name.GetHashCode()); return BinderHelper.AddArgHashes(h, _argumentInfo); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpGetMemberBinder cSharpGetMemberBinder)) { return false; } if (base.Name != cSharpGetMemberBinder.Name || ResultIndexed != cSharpGetMemberBinder.ResultIndexed || _callingContext != cSharpGetMemberBinder._callingContext || _argumentInfo.Length != cSharpGetMemberBinder._argumentInfo.Length) { return false; } return BinderHelper.CompareArgInfos(_argumentInfo, cSharpGetMemberBinder._argumentInfo); } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { BinderHelper.ValidateBindArgument(target, "target"); return BinderHelper.Bind(this, _binder, new DynamicMetaObject[1] { target }, _argumentInfo, errorSuggestion); } [SpecialName] string ICSharpBinder.get_Name() { return base.Name; } } internal sealed class CSharpInvokeBinder : InvokeBinder, ICSharpInvokeOrInvokeMemberBinder, ICSharpBinder { private readonly CSharpCallFlags _flags; private readonly CSharpArgumentInfo[] _argumentInfo; private readonly RuntimeBinder _binder; private readonly Type _callingContext; public BindingFlag BindingFlags => (BindingFlag)0; public bool IsBinderThatCanHaveRefReceiver => true; bool ICSharpInvokeOrInvokeMemberBinder.StaticCall { get { if (_argumentInfo[0] != null) { return _argumentInfo[0].IsStaticType; } return false; } } string ICSharpBinder.Name => "Invoke"; Type[] ICSharpInvokeOrInvokeMemberBinder.TypeArguments => Array.Empty<Type>(); CSharpCallFlags ICSharpInvokeOrInvokeMemberBinder.Flags => _flags; bool ICSharpInvokeOrInvokeMemberBinder.ResultDiscarded => (_flags & CSharpCallFlags.ResultDiscarded) != 0; public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return runtimeBinder.DispatchPayload(this, arguments, locals); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { RuntimeBinder.PopulateSymbolTableWithPayloadInformation(this, callingType, arguments); } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return _argumentInfo[index]; } public CSharpInvokeBinder(CSharpCallFlags flags, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(BinderHelper.CreateCallInfo(ref argumentInfo, 1)) { _flags = flags; _callingContext = callingContext; _argumentInfo = argumentInfo as CSharpArgumentInfo[]; _binder = new RuntimeBinder(callingContext); } public int GetGetBinderEquivalenceHash() { int h = _callingContext?.GetHashCode() ?? 0; h = HashHelpers.Combine(h, (int)_flags); return BinderHelper.AddArgHashes(h, _argumentInfo); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpInvokeBinder cSharpInvokeBinder)) { return false; } if (_flags != cSharpInvokeBinder._flags || _callingContext != cSharpInvokeBinder._callingContext || _argumentInfo.Length != cSharpInvokeBinder._argumentInfo.Length) { return false; } return BinderHelper.CompareArgInfos(_argumentInfo, cSharpInvokeBinder._argumentInfo); } public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { BinderHelper.ValidateBindArgument(target, "target"); BinderHelper.ValidateBindArgument(args, "args"); return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, args), _argumentInfo, errorSuggestion); } } internal sealed class CSharpInvokeConstructorBinder : DynamicMetaObjectBinder, ICSharpInvokeOrInvokeMemberBinder, ICSharpBinder { private readonly CSharpArgumentInfo[] _argumentInfo; private readonly RuntimeBinder _binder; private readonly Type _callingContext; public BindingFlag BindingFlags => (BindingFlag)0; public bool IsBinderThatCanHaveRefReceiver => true; public CSharpCallFlags Flags { get; } public bool StaticCall => true; public Type[] TypeArguments => Array.Empty<Type>(); public string Name => ".ctor"; bool ICSharpInvokeOrInvokeMemberBinder.ResultDiscarded => false; public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return runtimeBinder.DispatchPayload(this, arguments, locals); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { RuntimeBinder.PopulateSymbolTableWithPayloadInformation(this, callingType, arguments); } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return _argumentInfo[index]; } public CSharpInvokeConstructorBinder(CSharpCallFlags flags, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) { Flags = flags; _callingContext = callingContext; _argumentInfo = BinderHelper.ToArray(argumentInfo); _binder = new RuntimeBinder(callingContext); } public int GetGetBinderEquivalenceHash() { int h = _callingContext?.GetHashCode() ?? 0; h = HashHelpers.Combine(h, (int)Flags); h = HashHelpers.Combine(h, Name.GetHashCode()); return BinderHelper.AddArgHashes(h, TypeArguments, _argumentInfo); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpInvokeConstructorBinder cSharpInvokeConstructorBinder)) { return false; } if (Flags != cSharpInvokeConstructorBinder.Flags || _callingContext != cSharpInvokeConstructorBinder._callingContext || Name != cSharpInvokeConstructorBinder.Name || TypeArguments.Length != cSharpInvokeConstructorBinder.TypeArguments.Length || _argumentInfo.Length != cSharpInvokeConstructorBinder._argumentInfo.Length) { return false; } return BinderHelper.CompareArgInfos(TypeArguments, cSharpInvokeConstructorBinder.TypeArguments, _argumentInfo, cSharpInvokeConstructorBinder._argumentInfo); } public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { BinderHelper.ValidateBindArgument(target, "target"); BinderHelper.ValidateBindArgument(args, "args"); return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, args), _argumentInfo, null); } } internal sealed class CSharpInvokeMemberBinder : InvokeMemberBinder, ICSharpInvokeOrInvokeMemberBinder, ICSharpBinder { private readonly CSharpArgumentInfo[] _argumentInfo; private readonly RuntimeBinder _binder; public BindingFlag BindingFlags => (BindingFlag)0; public bool IsBinderThatCanHaveRefReceiver => true; bool ICSharpInvokeOrInvokeMemberBinder.StaticCall => _argumentInfo[0]?.IsStaticType ?? false; public CSharpCallFlags Flags { get; } public Type CallingContext { get; } public Type[] TypeArguments { get; } bool ICSharpInvokeOrInvokeMemberBinder.ResultDiscarded => (Flags & CSharpCallFlags.ResultDiscarded) != 0; public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return runtimeBinder.DispatchPayload(this, arguments, locals); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { RuntimeBinder.PopulateSymbolTableWithPayloadInformation(this, callingType, arguments); } public CSharpArgumentInfo GetArgumentInfo(int index) { return _argumentInfo[index]; } public CSharpArgumentInfo[] ArgumentInfoArray() { CSharpArgumentInfo[] array = new CSharpArgumentInfo[_argumentInfo.Length]; _argumentInfo.CopyTo(array, 0); return array; } public CSharpInvokeMemberBinder(CSharpCallFlags flags, string name, Type callingContext, IEnumerable<Type> typeArguments, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(name, ignoreCase: false, BinderHelper.CreateCallInfo(ref argumentInfo, 1)) { Flags = flags; CallingContext = callingContext; TypeArguments = BinderHelper.ToArray(typeArguments); _argumentInfo = BinderHelper.ToArray(argumentInfo); _binder = new RuntimeBinder(callingContext); } public int GetGetBinderEquivalenceHash() { int h = CallingContext?.GetHashCode() ?? 0; h = HashHelpers.Combine(h, (int)Flags); h = HashHelpers.Combine(h, base.Name.GetHashCode()); return BinderHelper.AddArgHashes(h, TypeArguments, _argumentInfo); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpInvokeMemberBinder cSharpInvokeMemberBinder)) { return false; } if (Flags != cSharpInvokeMemberBinder.Flags || CallingContext != cSharpInvokeMemberBinder.CallingContext || base.Name != cSharpInvokeMemberBinder.Name || TypeArguments.Length != cSharpInvokeMemberBinder.TypeArguments.Length || _argumentInfo.Length != cSharpInvokeMemberBinder._argumentInfo.Length) { return false; } return BinderHelper.CompareArgInfos(TypeArguments, cSharpInvokeMemberBinder.TypeArguments, _argumentInfo, cSharpInvokeMemberBinder._argumentInfo); } public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { BinderHelper.ValidateBindArgument(target, "target"); BinderHelper.ValidateBindArgument(args, "args"); return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, args), _argumentInfo, errorSuggestion); } public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { CSharpInvokeBinder cSharpInvokeBinder = new CSharpInvokeBinder(Flags, CallingContext, _argumentInfo).TryGetExisting(); return cSharpInvokeBinder.Defer(target, args); } [SpecialName] string ICSharpBinder.get_Name() { return base.Name; } } internal sealed class CSharpIsEventBinder : DynamicMetaObjectBinder, ICSharpBinder { private readonly RuntimeBinder _binder; private readonly Type _callingContext; public BindingFlag BindingFlags => (BindingFlag)0; public bool IsBinderThatCanHaveRefReceiver => false; public string Name { get; } public override Type ReturnType => typeof(bool); public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return runtimeBinder.BindIsEvent(this, arguments, locals); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { SymbolTable.PopulateSymbolTableWithName(Name, null, arguments[0].Info.IsStaticType ? (arguments[0].Value as Type) : arguments[0].Type); } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return CSharpArgumentInfo.None; } public CSharpIsEventBinder(string name, Type callingContext) { Name = name; _callingContext = callingContext; _binder = new RuntimeBinder(callingContext); } public int GetGetBinderEquivalenceHash() { int h = _callingContext?.GetHashCode() ?? 0; return HashHelpers.Combine(h, Name.GetHashCode()); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpIsEventBinder cSharpIsEventBinder)) { return false; } if (_callingContext != cSharpIsEventBinder._callingContext || Name != cSharpIsEventBinder.Name) { return false; } return true; } public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { BinderHelper.ValidateBindArgument(target, "target"); return BinderHelper.Bind(this, _binder, new DynamicMetaObject[1] { target }, null, null); } } internal sealed class CSharpSetIndexBinder : SetIndexBinder, ICSharpBinder { private readonly CSharpArgumentInfo[] _argumentInfo; private readonly RuntimeBinder _binder; private readonly Type _callingContext; public string Name => "$Item$"; public BindingFlag BindingFlags => (BindingFlag)0; public bool IsBinderThatCanHaveRefReceiver => true; internal bool IsCompoundAssignment { get; } private bool IsChecked => _binder.IsChecked; public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return runtimeBinder.BindAssignment(this, arguments, locals); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { SymbolTable.PopulateSymbolTableWithName("$Item$", null, arguments[0].Type); } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return _argumentInfo[index]; } public CSharpSetIndexBinder(bool isCompoundAssignment, bool isChecked, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(BinderHelper.CreateCallInfo(ref argumentInfo, 2)) { IsCompoundAssignment = isCompoundAssignment; _argumentInfo = argumentInfo as CSharpArgumentInfo[]; _callingContext = callingContext; _binder = new RuntimeBinder(callingContext, isChecked); } public int GetGetBinderEquivalenceHash() { int num = _callingContext?.GetHashCode() ?? 0; if (IsChecked) { num = HashHelpers.Combine(num, 1); } if (IsCompoundAssignment) { num = HashHelpers.Combine(num, 1); } return BinderHelper.AddArgHashes(num, _argumentInfo); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpSetIndexBinder cSharpSetIndexBinder)) { return false; } if (_callingContext != cSharpSetIndexBinder._callingContext || IsChecked != cSharpSetIndexBinder.IsChecked || IsCompoundAssignment != cSharpSetIndexBinder.IsCompoundAssignment || _argumentInfo.Length != cSharpSetIndexBinder._argumentInfo.Length) { return false; } return BinderHelper.CompareArgInfos(_argumentInfo, cSharpSetIndexBinder._argumentInfo); } public override DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion) { BinderHelper.ValidateBindArgument(target, "target"); BinderHelper.ValidateBindArgument(indexes, "indexes"); BinderHelper.ValidateBindArgument(value, "value"); return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, indexes, value), _argumentInfo, errorSuggestion); } } internal sealed class CSharpSetMemberBinder : SetMemberBinder, ICSharpBinder { private readonly CSharpArgumentInfo[] _argumentInfo; private readonly RuntimeBinder _binder; private readonly Type _callingContext; public BindingFlag BindingFlags => (BindingFlag)0; public bool IsBinderThatCanHaveRefReceiver => false; internal bool IsCompoundAssignment { get; } private bool IsChecked => _binder.IsChecked; public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return runtimeBinder.BindAssignment(this, arguments, locals); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { SymbolTable.PopulateSymbolTableWithName(base.Name, null, arguments[0].Type); } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return _argumentInfo[index]; } public CSharpSetMemberBinder(string name, bool isCompoundAssignment, bool isChecked, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(name, ignoreCase: false) { IsCompoundAssignment = isCompoundAssignment; _argumentInfo = BinderHelper.ToArray(argumentInfo); _callingContext = callingContext; _binder = new RuntimeBinder(callingContext, isChecked); } public int GetGetBinderEquivalenceHash() { int h = _callingContext?.GetHashCode() ?? 0; if (IsChecked) { h = HashHelpers.Combine(h, 1); } if (IsCompoundAssignment) { h = HashHelpers.Combine(h, 1); } h = HashHelpers.Combine(h, base.Name.GetHashCode()); return BinderHelper.AddArgHashes(h, _argumentInfo); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpSetMemberBinder cSharpSetMemberBinder)) { return false; } if (base.Name != cSharpSetMemberBinder.Name || _callingContext != cSharpSetMemberBinder._callingContext || IsChecked != cSharpSetMemberBinder.IsChecked || IsCompoundAssignment != cSharpSetMemberBinder.IsCompoundAssignment || _argumentInfo.Length != cSharpSetMemberBinder._argumentInfo.Length) { return false; } return BinderHelper.CompareArgInfos(_argumentInfo, cSharpSetMemberBinder._argumentInfo); } public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion) { BinderHelper.ValidateBindArgument(target, "target"); BinderHelper.ValidateBindArgument(value, "value"); return BinderHelper.Bind(this, _binder, new DynamicMetaObject[2] { target, value }, _argumentInfo, errorSuggestion); } [SpecialName] string ICSharpBinder.get_Name() { return base.Name; } } internal sealed class CSharpUnaryOperationBinder : UnaryOperationBinder, ICSharpBinder { private readonly CSharpArgumentInfo[] _argumentInfo; private readonly RuntimeBinder _binder; private readonly Type _callingContext; [ExcludeFromCodeCoverage] public string Name => null; public BindingFlag BindingFlags => (BindingFlag)0; public bool IsBinderThatCanHaveRefReceiver => false; private bool IsChecked => _binder.IsChecked; public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return runtimeBinder.BindUnaryOperation(this, arguments, locals); } public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) { SymbolTable.PopulateSymbolTableWithName(base.Operation.GetCLROperatorName(), null, arguments[0].Type); } CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) { return _argumentInfo[index]; } public CSharpUnaryOperationBinder(ExpressionType operation, bool isChecked, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(operation) { _argumentInfo = BinderHelper.ToArray(argumentInfo); _callingContext = callingContext; _binder = new RuntimeBinder(callingContext, isChecked); } public int GetGetBinderEquivalenceHash() { int h = _callingContext?.GetHashCode() ?? 0; h = HashHelpers.Combine(h, (int)base.Operation); if (IsChecked) { h = HashHelpers.Combine(h, 1); } return BinderHelper.AddArgHashes(h, _argumentInfo); } public bool IsEquivalentTo(ICSharpBinder other) { if (!(other is CSharpUnaryOperationBinder cSharpUnaryOperationBinder)) { return false; } if (base.Operation != cSharpUnaryOperationBinder.Operation || IsChecked != cSharpUnaryOperationBinder.IsChecked || _callingContext != cSharpUnaryOperationBinder._callingContext) { return false; } return BinderHelper.CompareArgInfos(_argumentInfo, cSharpUnaryOperationBinder._argumentInfo); } public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { BinderHelper.ValidateBindArgument(target, "target"); return BinderHelper.Bind(this, _binder, new DynamicMetaObject[1] { target }, _argumentInfo, errorSuggestion); } } [Serializable] [EditorBrowsable(EditorBrowsableState.Never)] internal sealed class DynamicBindingFailedException : Exception { public DynamicBindingFailedException() { } private DynamicBindingFailedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal sealed class GetMemberValueBinder : GetMemberBinder { public GetMemberValueBinder(string name, bool ignoreCase) : base(name, ignoreCase) { } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject self, DynamicMetaObject onBindingError) { if (onBindingError == null) { List<DynamicMetaObject> contributingObjects = new List<DynamicMetaObject> { self }; return new DynamicMetaObject(Expression.Throw(Expression.Constant(new DynamicBindingFailedException(), typeof(Exception)), typeof(object)), BindingRestrictions.Combine(contributingObjects)); } return onBindingError; } } internal sealed class DynamicMetaObjectProviderDebugView { [DebuggerDisplay("{value}", Name = "{name, nq}", Type = "{type, nq}")] internal class DynamicProperty { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly string name; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly object value; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly string type; public DynamicProperty(string name, object value) { this.name = name; this.value = value; type = ((value == null) ? "<null>" : value.GetType().ToString()); } } [Serializable] internal class DynamicDebugViewEmptyException : Exception { public string Empty => System.SR.EmptyDynamicView; public DynamicDebugViewEmptyException() { } protected DynamicDebugViewEmptyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private IList<KeyValuePair<string, object>> results; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private object obj; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static readonly ParameterExpression parameter = Expression.Parameter(typeof(object), "debug"); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal DynamicProperty[] Items { get { if (results == null || results.Count == 0) { results = QueryDynamicObject(obj); if (results == null || results.Count == 0) { throw new DynamicDebugViewEmptyException(); } } DynamicProperty[] array = new DynamicProperty[results.Count]; for (int i = 0; i < results.Count; i++) { array[i] = new DynamicProperty(results[i].Key, results[i].Value); } return array; } } public DynamicMetaObjectProviderDebugView(object arg) { obj = arg; } public static object TryEvalBinaryOperators<T1, T2>(T1 arg1, T2 arg2, CSharpArgumentInfoFlags arg1Flags, CSharpArgumentInfoFlags arg2Flags, ExpressionType opKind, Type accessibilityContext) { CSharpArgumentInfo cSharpArgumentInfo = CSharpArgumentInfo.Create(arg1Flags, null); CSharpArgumentInfo cSharpArgumentInfo2 = CSharpArgumentInfo.Create(arg2Flags, null); CSharpBinaryOperationBinder binder = new CSharpBinaryOperationBinder(opKind, isChecked: false, CSharpBinaryOperationFlags.None, accessibilityContext, new CSharpArgumentInfo[2] { cSharpArgumentInfo, cSharpArgumentInfo2 }); CallSite<Func<CallSite, T1, T2, object>> callSite = CallSite<Func<CallSite, T1, T2, object>>.Create(binder); return callSite.Target(callSite, arg1, arg2); } public static object TryEvalUnaryOperators<T>(T obj, ExpressionType oper, Type accessibilityContext) { if (oper == ExpressionType.IsTrue || oper == ExpressionType.IsFalse) { CallSite<Func<CallSite, T, bool>> callSite = CallSite<Func<CallSite, T, bool>>.Create(new CSharpUnaryOperationBinder(oper, isChecked: false, accessibilityContext, new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); return callSite.Target(callSite, obj); } CallSite<Func<CallSite, T, object>> callSite2 = CallSite<Func<CallSite, T, object>>.Create(new CSharpUnaryOperationBinder(oper, isChecked: false, accessibilityContext, new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); return callSite2.Target(callSite2, obj); } public static K TryEvalCast<T, K>(T obj, Type type, CSharpBinderFlags kind, Type accessibilityContext) { CallSite<Func<CallSite, T, K>> callSite = CallSite<Func<CallSite, T, K>>.Create(Binder.Convert(kind, type, accessibilityContext)); return callSite.Target(callSite, obj); } private static void CreateDelegateSignatureAndArgumentInfos(object[] args, Type[] argTypes, CSharpArgumentInfoFlags[] argFlags, out Type[] delegateSignatureTypes, out CSharpArgumentInfo[] argInfos) { int num = args.Length; delegateSignatureTypes = new Type[num + 2]; delegateSignatureTypes[0] = typeof(CallSite); argInfos = new CSharpArgumentInfo[num]; for (int i = 0; i < num; i++) { if (argTypes[i] != null) { delegateSignatureTypes[i + 1] = argTypes[i]; } else if (args[i] != null) { delegateSignatureTypes[i + 1] = args[i].GetType(); } else { delegateSignatureTypes[i + 1] = typeof(object); } argInfos[i] = CSharpArgumentInfo.Create(argFlags[i], null); } delegateSignatureTypes[num + 1] = typeof(object); } private static object CreateDelegateAndInvoke(Type[] delegateSignatureTypes, CallSiteBinder binder, object[] args) { Type delegateType = Expression.GetDelegateType(delegateSignatureTypes); CallSite callSite = CallSite.Create(delegateType, binder); Delegate @delegate = (Delegate)callSite.GetType().GetField("Target").GetValue(callSite); object[] array = new object[args.Length + 1]; array[0] = callSite; args.CopyTo(array, 1); return @delegate.DynamicInvoke(array); } public static object TryEvalMethodVarArgs(object[] methodArgs, Type[] argTypes, CSharpArgumentInfoFlags[] argFlags, string methodName, Type accessibilityContext, Type[] typeArguments) { Type[] delegateSignatureTypes = null; CSharpArgumentInfo[] argInfos = null; CreateDelegateSignatureAndArgumentInfos(methodArgs, argTypes, argFlags, out delegateSignatureTypes, out argInfos); return CreateDelegateAndInvoke(binder: (!string.IsNullOrEmpty(methodName)) ? ((CallSiteBinder)new CSharpInvokeMemberBinder(CSharpCallFlags.ResultDiscarded, methodName, accessibilityContext, typeArguments, argInfos)) : ((CallSiteBinder)new CSharpInvokeBinder(CSharpCallFlags.ResultDiscarded, accessibilityContext, argInfos)), delegateSignatureTypes: delegateSignatureTypes, args: methodArgs); } public static object TryGetMemberValue<T>(T obj, string propName, Type accessibilityContext, bool isResultIndexed) { CSharpGetMemberBinder binder = new CSharpGetMemberBinder(propName, isResultIndexed, accessibilityContext, new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); CallSite<Func<CallSite, T, object>> callSite = CallSite<Func<CallSite, T, object>>.Create(binder); return callSite.Target(callSite, obj); } public static object TryGetMemberValueVarArgs(object[] propArgs, Type[] argTypes, CSharpArgumentInfoFlags[] argFlags, Type accessibilityContext) { Type[] delegateSignatureTypes = null; CSharpArgumentInfo[] argInfos = null; CreateDelegateSignatureAndArgumentInfos(propArgs, argTypes, argFlags, out delegateSignatureTypes, out argInfos); CallSiteBinder binder = new CSharpGetIndexBinder(accessibilityContext, argInfos); return CreateDelegateAndInvoke(delegateSignatureTypes, binder, propArgs); } public static object TrySetMemberValue<TObject, TValue>(TObject obj, string propName, TValue value, CSharpArgumentInfoFlags valueFlags, Type accessibilityContext) { CSharpArgumentInfo cSharpArgumentInfo = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null); CSharpArgumentInfo cSharpArgumentInfo2 = CSharpArgumentInfo.Create(valueFlags, null); CSharpSetMemberBinder binder = new CSharpSetMemberBinder(propName, isCompoundAssignment: false, isChecked: false, accessibilityContext, new CSharpArgumentInfo[2] { cSharpArgumentInfo, cSharpArgumentInfo2 }); CallSite<Func<CallSite, TObject, TValue, object>> callSite = CallSite<Func<CallSite, TObject, TValue, object>>.Create(binder); return callSite.Target(callSite, obj, value); } public static object TrySetMemberValueVarArgs(object[] propArgs, Type[] argTypes, CSharpArgumentInfoFlags[] argFlags, Type accessibilityContext) { Type[] delegateSignatureTypes = null; CSharpArgumentInfo[] argInfos = null; CreateDelegateSignatureAndArgumentInfos(propArgs, argTypes, argFlags, out delegateSignatureTypes, out argInfos); CallSiteBinder binder = new CSharpSetIndexBinder(isCompoundAssignment: false, isChecked: false, accessibilityContext, argInfos); return CreateDelegateAndInvoke(delegateSignatureTypes, binder, propArgs); } internal static object TryGetMemberValue(object obj, string name, bool ignoreException) { bool ignoreCase = false; object obj2 = null; CallSite<Func<CallSite, object, object>> callSite = CallSite<Func<CallSite, object, object>>.Create(new GetMemberValueBinder(name, ignoreCase)); try { return callSite.Target(callSite, obj); } catch (DynamicBindingFailedException ex) { if (ignoreException) { return null; } throw ex; } catch (MissingMemberException ex2) { if (ignoreException) { return System.SR.GetValueonWriteOnlyProperty; } throw ex2; } } private static IList<KeyValuePair<string, object>> QueryDynamicObject(object obj) { if (obj is IDynamicMetaObjectProvider dynamicMetaObjectProvider) { DynamicMetaObject metaObject = dynamicMetaObjectProvider.GetMetaObject(parameter); List<string> list = new List<string>(metaObject.GetDynamicMemberNames()); list.Sort(); if (list != null) { List<KeyValuePair<string, object>> list2 = new List<KeyValuePair<string, object>>(); { foreach (string item in list) { object value; if ((value = TryGetMemberValue(obj, item, ignoreException: true)) != null) { list2.Add(new KeyValuePair<string, object>(item, value)); } } return list2; } } } return new KeyValuePair<string, object>[0]; } } internal static class Error { internal static Exception InternalCompilerError() { return new RuntimeBinderInternalCompilerException(System.SR.InternalCompilerError); } internal static Exception BindPropertyFailedMethodGroup(object p0) { return new RuntimeBinderException(System.SR.Format(System.SR.BindPropertyFailedMethodGroup, p0)); } internal static Exception BindPropertyFailedEvent(object p0) { return new RuntimeBinderException(System.SR.Format(System.SR.BindPropertyFailedEvent, p0)); } internal static Exception BindInvokeFailedNonDelegate() { return new RuntimeBinderException(System.SR.BindInvokeFailedNonDelegate); } internal static Exception BindStaticRequiresType(string paramName) { return new ArgumentException(System.SR.TypeArgumentRequiredForStaticCall, paramName); } internal static Exception NullReferenceOnMemberException() { return new RuntimeBinderException(System.SR.NullReferenceOnMemberException); } internal static Exception BindCallToConditionalMethod(object p0) { return new RuntimeBinderException(System.SR.Format(System.SR.BindCallToConditionalMethod, p0)); } internal static Exception BindToVoidMethodButExpectResult() { return new RuntimeBinderException(System.SR.BindToVoidMethodButExpectResult); } internal static Exception ArgumentNull(string paramName) { return new ArgumentNullException(paramName); } internal static Exception DynamicArgumentNeedsValue(string paramName) { return new ArgumentException(System.SR.DynamicArgumentNeedsValue, paramName); } } internal sealed class ExpressionTreeCallRewriter : ExprVisitorBase { private sealed class ExpressionExpr : Expr { public readonly Expression Expression; public ExpressionExpr(Expression e) : base(ExpressionKind.NoOp) { Expression = e; } } private readonly Dictionary<ExprCall, Expression> _DictionaryOfParameters; private readonly Expression[] _ListOfParameters; private int _currentParameterIndex; private ExpressionTreeCallRewriter(Expression[] listOfParameters) { _DictionaryOfParameters = new Dictionary<ExprCall, Expression>(); _ListOfParameters = listOfParameters; } public static Expression Rewrite(ExprBinOp binOp, Expression[] listOfParameters) { ExpressionTreeCallRewriter expressionTreeCallRewriter = new ExpressionTreeCallRewriter(listOfParameters); expressionTreeCallRewriter.Visit(binOp.OptionalLeftChild); ExprCall pExpr = (ExprCall)binOp.OptionalRightChild; ExpressionExpr expressionExpr = expressionTreeCallRewriter.Visit(pExpr) as ExpressionExpr; return expressionExpr.Expression; } protected override Expr VisitSAVE(ExprBinOp pExpr) { ExprCall key = (ExprCall)pExpr.OptionalLeftChild; Expression value = _ListOfParameters[_currentParameterIndex++]; _DictionaryOfParameters.Add(key, value); return null; } protected override Expr VisitCALL(ExprCall pExpr) { if (pExpr.PredefinedMethod == PREDEFMETH.PM_COUNT) { return pExpr; } Expression e; switch (pExpr.PredefinedMethod) { case PREDEFMETH.PM_EXPRESSION_LAMBDA: return GenerateLambda(pExpr); case PREDEFMETH.PM_EXPRESSION_CALL: e = GenerateCall(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX: case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2: e = GenerateArrayIndex(pExpr); break; case PREDEFMETH.PM_EXPRESSION_CONVERT: case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED: e = GenerateConvert(pExpr); break; case PREDEFMETH.PM_EXPRESSION_PROPERTY: e = GenerateProperty(pExpr); break; case PREDEFMETH.PM_EXPRESSION_FIELD: e = GenerateField(pExpr); break; case PREDEFMETH.PM_EXPRESSION_INVOKE: e = GenerateInvoke(pExpr); break; case PREDEFMETH.PM_EXPRESSION_NEW: e = GenerateNew(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ADD: case PREDEFMETH.PM_EXPRESSION_ADDCHECKED: case PREDEFMETH.PM_EXPRESSION_AND: case PREDEFMETH.PM_EXPRESSION_ANDALSO: case PREDEFMETH.PM_EXPRESSION_DIVIDE: case PREDEFMETH.PM_EXPRESSION_EQUAL: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT: case PREDEFMETH.PM_EXPRESSION_LESSTHAN: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_MODULO: case PREDEFMETH.PM_EXPRESSION_MULTIPLY: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL: case PREDEFMETH.PM_EXPRESSION_OR: case PREDEFMETH.PM_EXPRESSION_ORELSE: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT: case PREDEFMETH.PM_EXPRESSION_SUBTRACT: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED: e = GenerateBinaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED: e = GenerateUserDefinedBinaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_NEGATE: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED: case PREDEFMETH.PM_EXPRESSION_NOT: e = GenerateUnaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED: e = GenerateUserDefinedUnaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE: e = GenerateConstantType(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ASSIGN: e = GenerateAssignment(pExpr); break; default: throw Error.InternalCompilerError(); } return new ExpressionExpr(e); } protected override Expr VisitWRAP(ExprWrap pExpr) { return new ExpressionExpr(GetExpression(pExpr)); } private Expr GenerateLambda(ExprCall pExpr) { return Visit(((ExprList)pExpr.OptionalArguments).OptionalElement); } private Expression GenerateCall(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; ExprMethodInfo exprMethodInfo; ExprArrayInit arrinit; if (exprList.OptionalNextListNode is ExprList exprList2) { exprMethodInfo = (ExprMethodInfo)exprList2.OptionalElement; arrinit = (ExprArrayInit)exprList2.OptionalNextListNode; } else { exprMethodInfo = (ExprMethodInfo)exprList.OptionalNextListNode; arrinit = null; } Expression instance = null; MethodInfo methodInfo = exprMethodInfo.MethodInfo; Expression[] argumentsFromArrayInit = GetArgumentsFromArrayInit(arrinit); if (methodInfo == null) { throw Error.InternalCompilerError(); } if (!methodInfo.IsStatic) { instance = GetExpression(((ExprList)pExpr.OptionalArguments).OptionalElement); } return Expression.Call(instance, methodInfo, argumentsFromArrayInit); } private Expression GenerateArrayIndex(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; Expression expression = GetExpression(exprList.OptionalElement); Expression[] indexes = ((pExpr.PredefinedMethod != PREDEFMETH.PM_EXPRESSION_ARRAYINDEX) ? GetArgumentsFromArrayInit((ExprArrayInit)exprList.OptionalNextListNode) : new Expression[1] { GetExpression(exprList.OptionalNextListNode) }); return Expression.ArrayAccess(expression, indexes); } private Expression GenerateConvert(ExprCall pExpr) { PREDEFMETH predefinedMethod = pExpr.PredefinedMethod; Expression expression; Type associatedSystemType; if (predefinedMethod == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED || predefinedMethod == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED) { ExprList exprList = (ExprList)pExpr.OptionalArguments; ExprList exprList2 = (ExprList)exprList.OptionalNextListNode; expression = GetExpression(exprList.OptionalElement); associatedSystemType = ((ExprTypeOf)exprList2.OptionalElement).SourceType.AssociatedSystemType; if (expression.Type.MakeByRefType() == associatedSystemType) { return expression; } MethodInfo methodInfo = ((ExprMethodInfo)exprList2.OptionalNextListNode).MethodInfo; if (predefinedMethod == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED) { return Expression.Convert(expression, associatedSystemType, methodInfo); } return Expression.ConvertChecked(expression, associatedSystemType, methodInfo); } ExprList exprList3 = (ExprList)pExpr.OptionalArguments; expression = GetExpression(exprList3.OptionalElement); associatedSystemType = ((ExprTypeOf)exprList3.OptionalNextListNode).SourceType.AssociatedSystemType; if (expression.Type.MakeByRefType() == associatedSystemType) { return expression; } if ((pExpr.Flags & EXPRFLAG.EXF_USERCALLABLE) != 0) { return Expression.Unbox(expression, associatedSystemType); } if (predefinedMethod == PREDEFMETH.PM_EXPRESSION_CONVERT) { return Expression.Convert(expression, associatedSystemType); } return Expression.ConvertChecked(expression, associatedSystemType); } private Expression GenerateProperty(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; Expr optionalElement = exprList.OptionalElement; Expr optionalNextListNode = exprList.OptionalNextListNode; ExprPropertyInfo exprPropertyInfo; ExprArrayInit exprArrayInit; if (optionalNextListNode is ExprList exprList2) { exprPropertyInfo = exprList2.OptionalElement as ExprPropertyInfo; exprArrayInit = exprList2.OptionalNextListNode as ExprArrayInit; } else { exprPropertyInfo = optionalNextListNode as ExprPropertyInfo; exprArrayInit = null; } PropertyInfo propertyInfo = exprPropertyInfo.PropertyInfo; if (propertyInfo == null) { throw Error.InternalCompilerError(); } if (exprArrayInit == null) { return Expression.Property(GetExpression(optionalElement), propertyInfo); } return Expression.Property(GetExpression(optionalElement), propertyInfo, GetArgumentsFromArrayInit(exprArrayInit)); } private Expression GenerateField(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; ExprFieldInfo exprFieldInfo = (ExprFieldInfo)exprList.OptionalNextListNode; Type type = exprFieldInfo.FieldType.AssociatedSystemType; FieldInfo fieldInfo = exprFieldInfo.Field.AssociatedFieldInfo; if (!type.IsGenericType && !type.IsNested) { type = fieldInfo.DeclaringType; } if (type.IsGenericType) { fieldInfo = type.GetField(fieldInfo.Name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return Expression.Field(GetExpression(exprList.OptionalElement), fieldInfo); } private Expression GenerateInvoke(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; return Expression.Invoke(GetExpression(exprList.OptionalElement), GetArgumentsFromArrayInit(exprList.OptionalNextListNode as ExprArrayInit)); } private Expression GenerateNew(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; ConstructorInfo constructorInfo = ((ExprMethodInfo)exprList.OptionalElement).ConstructorInfo; Expression[] argumentsFromArrayInit = GetArgumentsFromArrayInit(exprList.OptionalNextListNode as ExprArrayInit); return Expression.New(constructorInfo, argumentsFromArrayInit); } private static Expression GenerateConstantType(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; return Expression.Constant(exprList.OptionalElement.Object, ((ExprTypeOf)exprList.OptionalNextListNode).SourceType.AssociatedSystemType); } private Expression GenerateAssignment(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; return Expression.Assign(GetExpression(exprList.OptionalElement), GetExpression(exprList.OptionalNextListNode)); } private Expression GenerateBinaryOperator(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; Expression expression = GetExpression(exprList.OptionalElement); Expression expression2 = GetExpression(exprList.OptionalNextListNode); return pExpr.PredefinedMethod switch { PREDEFMETH.PM_EXPRESSION_ADD => Expression.Add(expression, expression2), PREDEFMETH.PM_EXPRESSION_AND => Expression.And(expression, expression2), PREDEFMETH.PM_EXPRESSION_DIVIDE => Expression.Divide(expression, expression2), PREDEFMETH.PM_EXPRESSION_EQUAL => Expression.Equal(expression, expression2), PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR => Expression.ExclusiveOr(expression, expression2), PREDEFMETH.PM_EXPRESSION_GREATERTHAN => Expression.GreaterThan(expression, expression2), PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL => Expression.GreaterThanOrEqual(expression, expression2), PREDEFMETH.PM_EXPRESSION_LEFTSHIFT => Expression.LeftShift(expression, expression2), PREDEFMETH.PM_EXPRESSION_LESSTHAN => Expression.LessThan(expression, expression2), PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL => Expression.LessThanOrEqual(expression, expression2), PREDEFMETH.PM_EXPRESSION_MODULO => Expression.Modulo(expression, expression2), PREDEFMETH.PM_EXPRESSION_MULTIPLY => Expression.Multiply(expression, expression2), PREDEFMETH.PM_EXPRESSION_NOTEQUAL => Expression.NotEqual(expression, expression2), PREDEFMETH.PM_EXPRESSION_OR => Expression.Or(expression, expression2), PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT => Expression.RightShift(expression, expression2), PREDEFMETH.PM_EXPRESSION_SUBTRACT => Expression.Subtract(expression, expression2), PREDEFMETH.PM_EXPRESSION_ORELSE => Expression.OrElse(expression, expression2), PREDEFMETH.PM_EXPRESSION_ANDALSO => Expression.AndAlso(expression, expression2), PREDEFMETH.PM_EXPRESSION_ADDCHECKED => Expression.AddChecked(expression, expression2), PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED => Expression.MultiplyChecked(expression, expression2), PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED => Expression.SubtractChecked(expression, expression2), _ => throw Error.InternalCompilerError(), }; } private Expression GenerateUserDefinedBinaryOperator(ExprCall pExpr) { ExprList exprList = (ExprList)pExpr.OptionalArguments; Expression expression = GetExpression(exprList.OptionalElement); Expression expression2 = GetExpression(((ExprList)exprList.OptionalNextListNode).OptionalElement); exprList = (ExprList)exprList.OptionalNextListNode; bool liftToNull = false; MethodInfo methodInfo; if (exprList.OptionalNextListNode is ExprList exprList2) { ExprConstant exprConstant = (ExprConstant)exprList2.OptionalElement; liftToNull = exprConstant.Val.Int32Val == 1; methodInfo = ((ExprMethodInfo)exprList2.OptionalNextListNode).MethodInfo; } else { methodInfo = ((ExprMethodInfo)exprList.OptionalNextListNode).MethodInfo; } return pExpr.PredefinedMethod switch { PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED => Expression.Add(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED => Expression.And(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED => Expression.Divide(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED => Expression.Equal(expression, expression2, liftToNull, methodInfo), PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED => Expression.ExclusiveOr(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED => Expression.GreaterThan(expression, expression2, liftToNull, methodInfo), PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED => Expression.GreaterThanOrEqual(expression, expression2, liftToNull, methodInfo), PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED => Expression.LeftShift(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED => Expression.LessThan(expression, expression2, liftToNull, methodInfo), PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED => Expression.LessThanOrEqual(expression, expression2, liftToNull, methodInfo), PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED => Expression.Modulo(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED => Expression.Multiply(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED => Expression.NotEqual(expression, expression2, liftToNull, methodInfo), PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED => Expression.Or(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED => Expression.RightShift(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED => Expression.Subtract(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED => Expression.OrElse(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED => Expression.AndAlso(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED => Expression.AddChecked(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED => Expression.MultiplyChecked(expression, expression2, methodInfo), PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED => Expression.SubtractChecked(expression, expression2, methodInfo), _ => throw Error.InternalCompilerError(), }; } private Expression GenerateUnaryOperator(ExprCall pExpr) { PREDEFMETH predefinedMethod = pExpr.PredefinedMethod; Expression expression = GetExpression(pExpr.OptionalArguments); return predefinedMethod switch { PREDEFMETH.PM_EXPRESSION_NOT => Expression.Not(expression), PREDEFMETH.PM_EXPRESSION_NEGATE => Expression.Negate(expression), PREDEFMETH.PM_EXPRESSION_NEGATECHECKED => Expression.NegateChecked(expression), _ => throw Error.InternalCompilerError(), }; } private Expression GenerateUserDefinedUnaryOperator(ExprCall pExpr) { PREDEFMETH predefinedMethod = pExpr.PredefinedMethod; ExprList exprList = (ExprList)pExpr.OptionalArguments; Expression expression = GetExpression(exprList.OptionalElement); MethodInfo methodInfo = ((ExprMethodInfo)exprList.OptionalNextListNode).MethodInfo; return predefinedMethod switch { PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED => Expression.Not(expression, methodInfo), PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED => Expression.Negate(expression, methodInfo), PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED => Expression.UnaryPlus(expression, methodInfo), PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED => Expression.NegateChecked(expression, methodInfo), _ => throw Error.InternalCompilerError(), }; } private Expression GetExpression(Expr pExpr) { if (pExpr is ExprWrap exprWrap) { return _DictionaryOfParameters[(ExprCall)exprWrap.OptionalExpression]; } if (pExpr is ExprConstant) { return null; } ExprCall exprCall = (ExprCall)pExpr; switch (exprCall.PredefinedMethod) { case PREDEFMETH.PM_EXPRESSION_CALL: return GenerateCall(exprCall); case PREDEFMETH.PM_EXPRESSION_CONVERT: case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED: return GenerateConvert(exprCall); case PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT: { ExprList exprList = (ExprList)exprCall.OptionalArguments; return Expression.NewArrayInit(((ExprTypeOf)exprList.OptionalElement).SourceType.AssociatedSystemType, GetArgumentsFromArrayInit((ExprArrayInit)exprList.OptionalNextListNode)); } case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX: case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2: return GenerateArrayIndex(exprCall); case PREDEFMETH.PM_EXPRESSION_NEW: return GenerateNew(exprCall); case PREDEFMETH.PM_EXPRESSION_PROPERTY: return GenerateProperty(exprCall); case PREDEFMETH.PM_EXPRESSION_FIELD: return GenerateField(exprCall); case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE: return GenerateConstantType(exprCall); case PREDEFMETH.PM_EXPRESSION_ASSIGN: return GenerateAssignment(exprCall); case PREDEFMETH.PM_EXPRESSION_ADD: case PREDEFMETH.PM_EXPRESSION_ADDCHECKED: case PREDEFMETH.PM_EXPRESSION_AND: case PREDEFMETH.PM_EXPRESSION_ANDALSO: case PREDEFMETH.PM_EXPRESSION_DIVIDE: case PREDEFMETH.PM_EXPRESSION_EQUAL: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT: case PREDEFMETH.PM_EXPRESSION_LESSTHAN: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_MODULO: case PREDEFMETH.PM_EXPRESSION_MULTIPLY: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL: case PREDEFMETH.PM_EXPRESSION_OR: case PREDEFMETH.PM_EXPRESSION_ORELSE: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT: case PREDEFMETH.PM_EXPRESSION_SUBTRACT: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED: return GenerateBinaryOperator(exprCall); case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED: return GenerateUserDefinedBinaryOperator(exprCall); case PREDEFMETH.PM_EXPRESSION_NEGATE: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED: case PREDEFMETH.PM_EXPRESSION_NOT: return GenerateUnaryOperator(exprCall); case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED: return GenerateUserDefinedUnaryOperator(exprCall); default: throw Error.InternalCompilerError(); } } private Expression[] GetArgumentsFromArrayInit(ExprArrayInit arrinit) { List<Expression> list = new List<Expression>(); if (arrinit != null) { Expr expr = arrinit.OptionalArguments; while (expr != null) { Expr pExpr; if (expr is ExprList exprList) { pExpr = exprList.OptionalElement; expr = exprList.OptionalNextListNode; } else { pExpr = expr; expr = null; } list.Add(GetExpression(pExpr)); } } return list.ToArray(); } } internal interface ICSharpBinder { bool IsBinderThatCanHaveRefReceiver { get; } BindingFlag BindingFlags { get; } string Name { get; } Type ReturnType { get; } CSharpArgumentInfo GetArgumentInfo(int index); void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments); Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals); int GetGetBinderEquivalenceHash(); bool IsEquivalentTo(ICSharpBinder other); } internal interface ICSharpInvokeOrInvokeMemberBinder : ICSharpBinder { bool StaticCall { get; } bool ResultDiscarded { get; } CSharpCallFlags Flags { get; } Type[] TypeArguments { get; } } internal readonly struct RuntimeBinder { private static readonly object s_bindLock = new object(); private readonly ExpressionBinder _binder; internal bool IsChecked => _binder.Context.Checked; public RuntimeBinder(Type contextType, bool isChecked = false) { AggregateSymbol context; if (contextType != null) { lock (s_bindLock) { context = ((AggregateType)SymbolTable.GetCTypeFromType(contextType)).OwningAggregate; } } else { context = null; } _binder = new ExpressionBinder(new BindingContext(context, isChecked)); } public Expression Bind(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, out DynamicMetaObject deferredBinding) { lock (s_bindLock) { return BindCore(payload, parameters, args, out deferredBinding); } } private Expression BindCore(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, out DynamicMetaObject deferredBinding) { ArgumentObject[] array = CreateArgumentArray(payload, parameters, args); payload.PopulateSymbolTableWithName(array[0].Type, array); AddConversionsForArguments(array); Scope pScope = SymFactory.CreateScope(); LocalVariableSymbol[] locals = PopulateLocalScope(payload, pScope, array, parameters); if (DeferBinding(payload, array, args, locals, out deferredBinding)) { return null; } Expr pResult = payload.DispatchPayload(this, array, locals); return CreateExpressionTreeFromResult(parameters, pScope, pResult); } private bool DeferBinding(ICSharpBinder payload, ArgumentObject[] arguments, DynamicMetaObject[] args, LocalVariableSymbol[] locals, out DynamicMetaObject deferredBinding) { if (payload is CSharpInvokeMemberBinder cSharpInvokeMemberBinder) { Type[] typeArguments = cSharpInvokeMemberBinder.TypeArguments; int arity = ((typeArguments != null) ? typeArguments.Length : 0); MemberLookup mem = new MemberLookup(); Expr callingObject = CreateCallingObjectForCall(cSharpInvokeMemberBinder, arguments, locals); SymWithType symWithType = SymbolTable.LookupMember(cSharpInvokeMemberBinder.Name, callingObject, _binder.Context.ContextForMemberLookup, arity, mem, (cSharpInvokeMemberBinder.Flags & CSharpCallFlags.EventHookup) != 0, requireInvocable: true); if (symWithType != null && symWithType.Sym.getKind() != SYMKIND.SK_MethodSymbol) { CSharpGetMemberBinder cSharpGetMemberBinder = new CSharpGetMemberBinder(cSharpInvokeMemberBinder.Name, resultIndexed: false, cSharpInvokeMemberBinder.CallingContext, new CSharpArgumentInfo[1] { cSharpInvokeMemberBinder.GetArgumentInfo(0) }).TryGetExisting(); CSharpArgumentInfo[] array = cSharpInvokeMemberBinder.ArgumentInfoArray(); array[0] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null); CSharpInvokeBinder cSharpInvokeBinder = new CSharpInvokeBinder(cSharpInvokeMemberBinder.Flags, cSharpInvokeMemberBinder.CallingContext, array).TryGetExisting(); DynamicMetaObject[] array2 = new DynamicMetaObject[args.Length - 1]; Array.Copy(args, 1, array2, 0, args.Length - 1); deferredBinding = cSharpInvokeBinder.Defer(cSharpGetMemberBinder.Defer(args[0]), array2); return true; } } deferredBinding = null; return false; } private static Expression CreateExpressionTreeFromResult(Expression[] parameters, Scope pScope, Expr pResult) { ExprBoundLambda expr = GenerateBoundLambda(pScope, pResult); ExprBinOp binOp = ExpressionTreeRewriter.Rewrite(expr); return ExpressionTreeCallRewriter.Rewrite(binOp, parameters); } private Type GetArgumentType(ICSharpBinder p, CSharpArgumentInfo argInfo, Expression param, DynamicMetaObject arg, int index) { Type type = (argInfo.UseCompileTimeType ? param.Type : arg.LimitType); if (argInfo.IsByRefOrOut) { if (index != 0 || !p.IsBinderThatCanHaveRefReceiver) { type = type.MakeByRefType(); } } else if (!argInfo.UseCompileTimeType) { CType cTypeFromType = SymbolTable.GetCTypeFromType(type); CType bestAccessibleType = TypeManager.GetBestAccessibleType(_binder.Context.ContextForMemberLookup, cTypeFromType); type = bestAccessibleType.AssociatedSystemType; } return type; } private ArgumentObject[] CreateArgumentArray(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args) { ArgumentObject[] array = new ArgumentObject[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { CSharpArgumentInfo argumentInfo = payload.GetArgumentInfo(i); array[i] = new ArgumentObject(args[i].Value, argumentInfo, GetArgumentType(payload, argumentInfo, parameters[i], args[i], i)); } return array; } internal static void PopulateSymbolTableWithPayloadInformation(ICSharpInvokeOrInvokeMemberBinder callOrInvoke, Type callingType, ArgumentObject[] arguments) { Type type; if (callOrInvoke.StaticCall) { type = arguments[0].Value as Type; if (type == null) { throw Error.BindStaticRequiresType(arguments[0].Info.Name); } } else { type = callingType; } SymbolTable.PopulateSymbolTableWithName(callOrInvoke.Name, callOrInvoke.TypeArguments, type); if (callOrInvoke.Name.StartsWith("set_", StringComparison.Ordinal) || callOrInvoke.Name.StartsWith("get_", StringComparison.Ordinal)) { SymbolTable.PopulateSymbolTableWithName(callOrInvoke.Name.Substring(4), callOrInvoke.TypeArguments, type); } } private static void AddConversionsForArguments(ArgumentObject[] arguments) { for (int i = 0; i < arguments.Length; i++) { ArgumentObject argumentObject = arguments[i]; SymbolTable.AddConversionsForType(argumentObject.Type); } } internal ExprWithArgs DispatchPayload(ICSharpInvokeOrInvokeMemberBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { return BindCall(payload, CreateCallingObjectForCall(payload, arguments, locals), arguments, locals); } private static LocalVariableSymbol[] PopulateLocalScope(ICSharpBinder payload, Scope pScope, ArgumentObject[] arguments, Expression[] parameterExpressions) { LocalVariableSymbol[] array = new LocalVariableSymbol[parameterExpressions.Length]; for (int i = 0; i < parameterExpressions.Length; i++) { Expression expression = parameterExpressions[i]; CType cType = SymbolTable.GetCTypeFromType(expression.Type); if ((i != 0 || !payload.IsBinderThatCanHaveRefReceiver) && expression is ParameterExpression parameterExpression && parameterExpression.IsByRef) { CSharpArgumentInfo info = arguments[i].Info; if (info.IsByRefOrOut) { cType = TypeManager.GetParameterModifier(cType, info.IsOut); } } LocalVariableSymbol localVariableSymbol = SymFactory.CreateLocalVar(NameManager.Add("p" + i), pScope, cType); array[i] = localVariableSymbol; } return array; } private static ExprBoundLambda GenerateBoundLambda(Scope pScope, Expr call) { AggregateType predefindType = SymbolLoader.GetPredefindType(PredefinedType.PT_FUNC); return ExprFactory.CreateAnonymousMethod(predefindType, pScope, call); } private Expr CreateLocal(Type type, bool isOut, LocalVariableSymbol local) { CType dest = ((!isOut) ? SymbolTable.GetCTypeFromType(type) : TypeManager.GetParameterModifier(SymbolTable.GetCTypeFromType(type.GetElementType()), isOut: true)); ExprLocal expr = ExprFactory.CreateLocal(local); Expr expr2 = _binder.tryConvert(expr, dest) ?? _binder.mustCast(expr, dest); expr2.Flags |= EXPRFLAG.EXF_LVALUE; return expr2; } internal Expr CreateArgumentListEXPR(ArgumentObject[] arguments, LocalVariableSymbol[] locals, int startIndex, int endIndex) { Expr first = null; Expr last = null; if (arguments != null) { for (int i = startIndex; i < endIndex; i++) { ArgumentObject argument = arguments[i]; Expr expr = CreateArgumentEXPR(argument, locals[i]); if (first == null) { first = expr; last = first; } else { ExprFactory.AppendItemToList(expr, ref first, ref last); } } } return first; } private Expr CreateArgumentEXPR(ArgumentObject argument, LocalVariableSymbol local) { Expr expr = (argument.Info.LiteralConstant ? ((argument.Value != null) ? ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), ConstVal.Get(argument.Value)) : ((!argument.Info.UseCompileTimeType) ? ExprFactory.CreateNull() : ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), default(ConstVal)))) : ((argument.Info.UseCompileTimeType || argument.Value != null) ? CreateLocal(argument.Type, argument.Info.IsOut, local) : ExprFactory.CreateNull())); if (argument.Info.NamedArgument) { expr = ExprFactory.CreateNamedArgumentSpecification(NameManager.Add(argument.Info.Name), expr); } if (!argument.Info.UseCompileTimeType && argument.Value != null) { expr.RuntimeObject = argument.Value;
plugins/RiskOfRumble.dll
Decompiled 2 years agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Buttplug.Client; using Buttplug.Client.Connectors.WebsocketConnector; using Buttplug.Core; using RoR2; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("RiskOfRumble")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+80235b52c4ade6ffd8e05428c33224965c90f4ed")] [assembly: AssemblyProduct("RiskOfRumble")] [assembly: AssemblyTitle("RiskOfRumble")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] internal sealed class ConfigurationManagerAttributes { public bool? ShowRangeAsPercent; public Action<ConfigEntryBase> CustomDrawer; public bool? Browsable; public string Category; public object DefaultValue; public bool? HideDefaultButton; public bool? HideSettingName; public string Description; public string DispName; public int? Order; public bool? ReadOnly; public bool? IsAdvanced; public Func<object, string> ObjToStr; public Func<string, object> StrToObj; } namespace RiskOfRumble; [BepInPlugin("com.exp111.RiskOfRumble", "RiskOfRumble", "1.0")] public class RiskOfRumble : BaseUnityPlugin { public class Vibration { public float Intensity; public Vibration(float intensity) { Intensity = intensity; } } public const string ID = "com.exp111.RiskOfRumble"; public const string NAME = "RiskOfRumble"; public const string VERSION = "1.0"; public static ManualLogSource Log; private static ButtplugClient ButtplugClient; public static ConfigEntry<string> ServerURL; public static ConfigEntry<bool> Rewarding; public static ConfigEntry<bool> Punishing; public static ConfigEntry<bool> RoundRobin; public static ConfigEntry<float> RewardFactor; public static ConfigEntry<float> PunishmentFactor; public static List<Vibration> Vibrations = new List<Vibration>(); public void Awake() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown try { Log = ((BaseUnityPlugin)this).Logger; Log.LogMessage((object)"Awake"); SetupConfig(); ButtplugClient = new ButtplugClient("RiskOfRumble"); ButtplugClient.DeviceAdded += ButtplugClient_DeviceAdded; ButtplugClient.PingTimeout += ButtplugClient_PingTimeout; ButtplugClient.ErrorReceived += ButtplugClient_ErrorReceived; Connect(); GlobalEventManager.onClientDamageNotified += GlobalEventManager_onClientDamageNotified; } catch (Exception arg) { Log.LogMessage((object)$"Exception during RiskOfRumble.Awake: {arg}"); } } private void ButtplugClient_DeviceAdded(object sender, DeviceAddedEventArgs e) { } private void ButtplugClient_PingTimeout(object sender, EventArgs e) { Log.LogMessage((object)$"Ping Timeout from RiskOfRumble.ButtplugClient: {e}"); } private void ButtplugClient_ErrorReceived(object sender, ButtplugExceptionEventArgs e) { Log.LogMessage((object)$"Error received from RiskOfRumble.ButtplugClient: {e}"); } private void SetupConfig() { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown ServerURL = ((BaseUnityPlugin)this).Config.Bind<string>("Connection", "URL", "ws://localhost:12345", "The server url which to join"); ((BaseUnityPlugin)this).Config.Bind<bool>("Connection", "Connect", false, new ConfigDescription("Scan/reconnect", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { CustomDrawer = ConnectDrawer, HideDefaultButton = true } })); Rewarding = ((BaseUnityPlugin)this).Config.Bind<bool>("Gameplay", "Rewarding", true, "If rewarding actions (hitting things) should trigger vibrations"); Punishing = ((BaseUnityPlugin)this).Config.Bind<bool>("Gameplay", "Punishing", false, "If punishing actions (getting hit) should trigger vibrations"); RoundRobin = ((BaseUnityPlugin)this).Config.Bind<bool>("Gameplay", "Round Robin", false, "If you should receive rewards/punishments from another players actions"); RewardFactor = ((BaseUnityPlugin)this).Config.Bind<float>("Gameplay", "Reward Factor", 0.5f, "The reward multiplier"); PunishmentFactor = ((BaseUnityPlugin)this).Config.Bind<float>("Gameplay", "Punishment Factor", 2f, "The punishment multiplier"); } private void Connect() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown try { ButtplugWebsocketConnector val = new ButtplugWebsocketConnector(new Uri(ServerURL.Value)); ButtplugClient.ConnectAsync((IButtplugClientConnector)(object)val, default(CancellationToken)).Wait(); } catch (Exception arg) { Log.LogMessage((object)$"Exception during RiskOfRumble.Connect: {arg}"); } } private void Disconnect() { try { ButtplugClient.DisconnectAsync().Wait(); } catch (Exception arg) { Log.LogMessage((object)$"Exception during RiskOfRumble.Disconnect: {arg}"); } } public void ConnectDrawer(ConfigEntryBase entry) { try { GUILayout.TextArea("Status: " + (ButtplugClient.Connected ? "Connected" : "Disconnected"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); GUILayout.TextArea($"#Devices: {ButtplugClient.Devices.Length}", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); if (GUILayout.Button("Connect", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) })) { Connect(); } if (GUILayout.Button("Scan", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) })) { ButtplugClient.StartScanningAsync(default(CancellationToken)).Wait(); } if (GUILayout.Button("Disconnect", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) })) { Disconnect(); } } catch (Exception arg) { Log.LogMessage((object)$"Exception during RiskOfRumble.CustomDrawer: {arg}"); } } public static void Vibrate(float strength) { float num = Math.Max(0f, Math.Min(1f, strength)); Vibrations.Add(new Vibration(num)); SendVibrate(num); } public void Update() { try { float deltaTime = Time.deltaTime; if (Vibrations.Count == 0) { return; } foreach (Vibration vibration in Vibrations) { vibration.Intensity = Mathf.Lerp(vibration.Intensity, -0.01f, 0.5f * deltaTime); } Vibrations.RemoveAll((Vibration p) => p.Intensity <= 0f); SendVibrate(Vibrations.Sum((Vibration item) => item.Intensity)); } catch (Exception arg) { Log.LogMessage((object)$"Exception during RiskOfRumble.Update: {arg}"); } } public static void SendVibrate(float strength) { ButtplugClientDevice[] devices = ButtplugClient.Devices; for (int i = 0; i < devices.Length; i++) { devices[i].VibrateAsync((double)strength); } } [Conditional("DEBUG")] public static void DebugLog(string message) { Log.LogMessage((object)message); } [Conditional("TRACE")] public static void DebugTrace(string message) { Log.LogMessage((object)message); } private void GlobalEventManager_onClientDamageNotified(DamageDealtMessage message) { try { if (Object.op_Implicit((Object)(object)message.victim)) { if (Rewarding.Value) { Reward(message); } if (Punishing.Value) { Punish(message); } } } catch (Exception arg) { Log.LogMessage((object)$"Exception during GlobalEventManager.onClientDamageNotified hook: {arg}"); } } private CharacterMaster GetCharacterMaster() { CharacterMaster master = LocalUserManager.GetFirstLocalUser().currentNetworkUser.master; if (RoundRobin.Value) { int num = 0; using (IEnumerator<PlayerCharacterMasterController> enumerator = PlayerCharacterMasterController.instances.GetEnumerator()) { while (enumerator.MoveNext() && !((Object)(object)enumerator.Current.master == (Object)(object)master)) { num++; } } master = PlayerCharacterMasterController.instances[(num + 1) % PlayerCharacterMasterController.instances.Count].master; } return master; } private void Punish(DamageDealtMessage obj) { CharacterMaster characterMaster = GetCharacterMaster(); if (!Object.op_Implicit((Object)(object)characterMaster)) { return; } CharacterBody body = characterMaster.GetBody(); if (Object.op_Implicit((Object)(object)body)) { GameObject victim = obj.victim; if (!((Object)(object)victim != (Object)(object)((Component)body).gameObject)) { HealthComponent component = victim.GetComponent<HealthComponent>(); Vibrate(PunishmentFactor.Value * (obj.damage / component.fullCombinedHealth)); } } } private void Reward(DamageDealtMessage obj) { CharacterMaster characterMaster = GetCharacterMaster(); if (!Object.op_Implicit((Object)(object)characterMaster)) { return; } CharacterBody body = characterMaster.GetBody(); if (Object.op_Implicit((Object)(object)body) && !((Object)(object)obj.attacker != (Object)(object)((Component)body).gameObject)) { GameObject victim = obj.victim; if (Object.op_Implicit((Object)(object)victim)) { HealthComponent component = victim.GetComponent<HealthComponent>(); Vibrate(RewardFactor.Value * (obj.damage / component.fullCombinedHealth)); } } } }
plugins/System.Buffers.dll
Decompiled 2 years agousing System; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Buffers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Buffers")] [assembly: AssemblyDescription("System.Buffers")] [assembly: AssemblyDefaultAlias("System.Buffers")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.28619.01")] [assembly: AssemblyInformationalVersion("4.6.28619.01 @BuiltBy: dlab14-DDVSOWINAGE069 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/7601f4f6225089ffb291dc7d58293c7bbf5c5d4f")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.3.0")] [module: UnverifiableCode] namespace FxResources.System.Buffers { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static Type ResourceType { get; } = typeof(SR); internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool", null); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } namespace System.Buffers { public abstract class ArrayPool<T> { private static ArrayPool<T> s_sharedInstance; public static ArrayPool<T> Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static ArrayPool<T> EnsureSharedCreated() { Interlocked.CompareExchange(ref s_sharedInstance, Create(), null); return s_sharedInstance; } public static ArrayPool<T> Create() { return new DefaultArrayPool<T>(); } public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket) { return new DefaultArrayPool<T>(maxArrayLength, maxArraysPerBucket); } public abstract T[] Rent(int minimumLength); public abstract void Return(T[] array, bool clearArray = false); } [EventSource(Name = "System.Buffers.ArrayPoolEventSource")] internal sealed class ArrayPoolEventSource : EventSource { internal enum BufferAllocatedReason { Pooled, OverMaximumSize, PoolExhausted } internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource(); [Event(1, Level = EventLevel.Verbose)] internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId) { EventData* ptr = stackalloc EventData[4]; *ptr = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, DataPointer = (IntPtr)(&bucketId) }; WriteEventCore(1, 4, ptr); } [Event(2, Level = EventLevel.Informational)] internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason) { EventData* ptr = stackalloc EventData[5]; *ptr = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, DataPointer = (IntPtr)(&bucketId) }; ptr[4] = new EventData { Size = 4, DataPointer = (IntPtr)(&reason) }; WriteEventCore(2, 5, ptr); } [Event(3, Level = EventLevel.Verbose)] internal void BufferReturned(int bufferId, int bufferSize, int poolId) { WriteEvent(3, bufferId, bufferSize, poolId); } } internal sealed class DefaultArrayPool<T> : ArrayPool<T> { private sealed class Bucket { internal readonly int _bufferLength; private readonly T[][] _buffers; private readonly int _poolId; private SpinLock _lock; private int _index; internal int Id => GetHashCode(); internal Bucket(int bufferLength, int numberOfBuffers, int poolId) { _lock = new SpinLock(Debugger.IsAttached); _buffers = new T[numberOfBuffers][]; _bufferLength = bufferLength; _poolId = poolId; } internal T[] Rent() { T[][] buffers = _buffers; T[] array = null; bool lockTaken = false; bool flag = false; try { _lock.Enter(ref lockTaken); if (_index < buffers.Length) { array = buffers[_index]; buffers[_index++] = null; flag = array == null; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } if (flag) { array = new T[_bufferLength]; System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled); } } return array; } internal void Return(T[] array) { if (array.Length != _bufferLength) { throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array"); } bool lockTaken = false; try { _lock.Enter(ref lockTaken); if (_index != 0) { _buffers[--_index] = array; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } } } private const int DefaultMaxArrayLength = 1048576; private const int DefaultMaxNumberOfArraysPerBucket = 50; private static T[] s_emptyArray; private readonly Bucket[] _buckets; private int Id => GetHashCode(); internal DefaultArrayPool() : this(1048576, 50) { } internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket) { if (maxArrayLength <= 0) { throw new ArgumentOutOfRangeException("maxArrayLength"); } if (maxArraysPerBucket <= 0) { throw new ArgumentOutOfRangeException("maxArraysPerBucket"); } if (maxArrayLength > 1073741824) { maxArrayLength = 1073741824; } else if (maxArrayLength < 16) { maxArrayLength = 16; } int id = Id; int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength); Bucket[] array = new Bucket[num + 1]; for (int i = 0; i < array.Length; i++) { array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id); } _buckets = array; } public override T[] Rent(int minimumLength) { if (minimumLength < 0) { throw new ArgumentOutOfRangeException("minimumLength"); } if (minimumLength == 0) { return s_emptyArray ?? (s_emptyArray = new T[0]); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; T[] array = null; int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength); if (num < _buckets.Length) { int num2 = num; do { array = _buckets[num2].Rent(); if (array != null) { if (log.IsEnabled()) { log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id); } return array; } } while (++num2 < _buckets.Length && num2 != num + 2); array = new T[_buckets[num]._bufferLength]; } else { array = new T[minimumLength]; } if (log.IsEnabled()) { int hashCode = array.GetHashCode(); int bucketId = -1; log.BufferRented(hashCode, array.Length, Id, bucketId); log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted); } return array; } public override void Return(T[] array, bool clearArray = false) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Length == 0) { return; } int num = System.Buffers.Utilities.SelectBucketIndex(array.Length); if (num < _buckets.Length) { if (clearArray) { Array.Clear(array, 0, array.Length); } _buckets[num].Return(array); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferReturned(array.GetHashCode(), array.Length, Id); } } } internal static class Utilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int SelectBucketIndex(int bufferSize) { uint num = (uint)(bufferSize - 1) >> 4; int num2 = 0; if (num > 65535) { num >>= 16; num2 = 16; } if (num > 255) { num >>= 8; num2 += 8; } if (num > 15) { num >>= 4; num2 += 4; } if (num > 3) { num >>= 2; num2 += 2; } if (num > 1) { num >>= 1; num2++; } return num2 + (int)num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetMaxSizeForBucket(int binIndex) { return 16 << binIndex; } } }
plugins/System.Runtime.CompilerServices.Unsafe.dll
Decompiled 2 years 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.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0")] [assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyVersion("6.0.0.0")] namespace System.Runtime.CompilerServices { public static class Unsafe { [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T Read<T>(void* source) { return Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T ReadUnaligned<T>(void* source) { return Unsafe.ReadUnaligned<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T ReadUnaligned<T>(ref byte source) { return Unsafe.ReadUnaligned<T>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Write<T>(void* destination, T value) { Unsafe.Write(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void WriteUnaligned<T>(void* destination, T value) { Unsafe.WriteUnaligned(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void WriteUnaligned<T>(ref byte destination, T value) { Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(void* destination, ref T source) { Unsafe.Write(destination, source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(ref T destination, void* source) { destination = Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* AsPointer<T>(ref T value) { return Unsafe.AsPointer(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void SkipInit<T>(out T value) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static int SizeOf<T>() { return Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T As<T>(object o) where T : class { return (T)o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T AsRef<T>(void* source) { return ref *(T*)source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AsRef<T>(in T source) { return ref source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref TTo As<TFrom, TTo>(ref TFrom source) { return ref Unsafe.As<TFrom, TTo>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Unbox<T>(object box) where T : struct { return ref (T)box; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, int elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Add<T>(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, int elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Subtract<T>(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static IntPtr ByteOffset<T>(ref T origin, ref T target) { return Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool AreSame<T>(ref T left, ref T right) { return Unsafe.AreSame(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressGreaterThan<T>(ref T left, ref T right) { return Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressLessThan<T>(ref T left, ref T right) { return Unsafe.IsAddressLessThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsNullRef<T>(ref T source) { return Unsafe.AsPointer(ref source) == null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T NullRef<T>() { return ref *(T*)null; } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { internal sealed class IsReadOnlyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] A_0) { TransformFlags = A_0; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } }
plugins/System.Text.Encodings.Web.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.Encodings.Web; using System.Text.Unicode; using System.Threading; using FxResources.System.Text.Encodings.Web; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Text.Encodings.Web")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides types for encoding and escaping strings for use in JavaScript, HyperText Markup Language (HTML), and uniform resource locators (URL).\r\n\r\nCommonly Used Types:\r\nSystem.Text.Encodings.Web.HtmlEncoder\r\nSystem.Text.Encodings.Web.UrlEncoder\r\nSystem.Text.Encodings.Web.JavaScriptEncoder")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Text.Encodings.Web")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("7.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Text.Encodings.Web { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { 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; if ((long)(num2 & num3) >= 0L) { return false; } return true; } 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 TextEncoderDoesNotImplementMaxOutputCharsPerInputChar => GetResourceString("TextEncoderDoesNotImplementMaxOutputCharsPerInputChar"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Numerics { internal static class BitOperations { private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32] { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Log2(uint value) { return Log2SoftwareFallback(value | 1u); } private static int Log2SoftwareFallback(uint value) { value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (nint)(value * 130329821 >> 27)); } } } namespace System.Text { internal static class UnicodeDebug { [Conditional("DEBUG")] internal static void AssertIsBmpCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsBmpCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsHighSurrogateCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsHighSurrogateCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsLowSurrogateCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsLowSurrogateCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsValidCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsValidCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsValidScalar(uint scalarValue) { System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue); } [Conditional("DEBUG")] internal static void AssertIsValidSupplementaryPlaneScalar(uint scalarValue) { if (System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue)) { System.Text.UnicodeUtility.IsBmpCodePoint(scalarValue); } } private static string ToHexString(uint codePoint) { return FormattableString.Invariant($"U+{codePoint:X4}"); } } internal static class UnicodeUtility { public const uint ReplacementChar = 65533u; public static int GetPlane(uint codePoint) { return (int)(codePoint >> 16); } public static uint GetScalarFromUtf16SurrogatePair(uint highSurrogateCodePoint, uint lowSurrogateCodePoint) { return (highSurrogateCodePoint << 10) + lowSurrogateCodePoint - 56613888; } public static int GetUtf16SequenceLength(uint value) { value -= 65536; value += 33554432; value >>= 24; return (int)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void GetUtf16SurrogatesFromSupplementaryPlaneScalar(uint value, out char highSurrogateCodePoint, out char lowSurrogateCodePoint) { highSurrogateCodePoint = (char)(value + 56557568 >> 10); lowSurrogateCodePoint = (char)((value & 0x3FF) + 56320); } public static int GetUtf8SequenceLength(uint value) { int num = (int)(value - 2048) >> 31; value ^= 0xF800u; value -= 63616; value += 67108864; value >>= 24; return (int)value + num * 2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAsciiCodePoint(uint value) { return value <= 127; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsBmpCodePoint(uint value) { return value <= 65535; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHighSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 55296u, 56319u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound) { return value - lowerBound <= upperBound - lowerBound; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLowSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 56320u, 57343u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 55296u, 57343u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidCodePoint(uint codePoint) { return codePoint <= 1114111; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidUnicodeScalar(uint value) { return ((value - 1114112) ^ 0xD800) >= 4293855232u; } } internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => ref _chars[index]; public Span<char> RawChars => _chars; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public void EnsureCapacity(int capacity) { if ((uint)capacity > (uint)_chars.Length) { Grow(capacity - _pos); } } public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public override string ToString() { string result = _chars.Slice(0, _pos).ToString(); Dispose(); return result; } public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } charsWritten = 0; Dispose(); return false; } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int length = _pos - index; _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string s) { if (s != null) { int length = s.Length; if (_pos > _chars.Length - length) { Grow(length); } int length2 = _pos - index; _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); s.AsSpan().CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; 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); } } } internal readonly struct Rune : IEquatable<Rune> { private const int MaxUtf16CharsPerRune = 2; private const char HighSurrogateStart = '\ud800'; private const char LowSurrogateStart = '\udc00'; private const int HighSurrogateRange = 1023; private readonly uint _value; public bool IsAscii => System.Text.UnicodeUtility.IsAsciiCodePoint(_value); public bool IsBmp => System.Text.UnicodeUtility.IsBmpCodePoint(_value); public static Rune ReplacementChar => UnsafeCreate(65533u); public int Utf16SequenceLength => System.Text.UnicodeUtility.GetUtf16SequenceLength(_value); public int Value => (int)_value; public Rune(uint value) { if (!System.Text.UnicodeUtility.IsValidUnicodeScalar(value)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } _value = value; } public Rune(int value) : this((uint)value) { } private Rune(uint scalarValue, bool unused) { _value = scalarValue; } public static bool operator ==(Rune left, Rune right) { return left._value == right._value; } public static bool operator !=(Rune left, Rune right) { return left._value != right._value; } public static bool IsControl(Rune value) { return ((value._value + 1) & 0xFFFFFF7Fu) <= 32; } public static OperationStatus DecodeFromUtf16(ReadOnlySpan<char> source, out Rune result, out int charsConsumed) { if (!source.IsEmpty) { char c = source[0]; if (TryCreate(c, out result)) { charsConsumed = 1; return OperationStatus.Done; } if (1u < (uint)source.Length) { char lowSurrogate = source[1]; if (TryCreate(c, lowSurrogate, out result)) { charsConsumed = 2; return OperationStatus.Done; } } else if (char.IsHighSurrogate(c)) { goto IL_004c; } charsConsumed = 1; result = ReplacementChar; return OperationStatus.InvalidData; } goto IL_004c; IL_004c: charsConsumed = source.Length; result = ReplacementChar; return OperationStatus.NeedMoreData; } public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> source, out Rune result, out int bytesConsumed) { int num = 0; uint num2; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Text.UnicodeUtility.IsAsciiCodePoint(num2)) { goto IL_0021; } if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 194u, 244u)) { num2 = num2 - 194 << 6; num++; if ((uint)num >= (uint)source.Length) { goto IL_0163; } int num3 = (sbyte)source[num]; if (num3 < -64) { num2 += (uint)num3; num2 += 128; num2 += 128; if (num2 < 2048) { goto IL_0021; } if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2080u, 3343u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2912u, 2943u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 3072u, 3087u)) { num++; if ((uint)num >= (uint)source.Length) { goto IL_0163; } num3 = (sbyte)source[num]; if (num3 < -64) { num2 <<= 6; num2 += (uint)num3; num2 += 128; num2 -= 131072; if (num2 > 65535) { num++; if ((uint)num >= (uint)source.Length) { goto IL_0163; } num3 = (sbyte)source[num]; if (num3 >= -64) { goto IL_0153; } num2 <<= 6; num2 += (uint)num3; num2 += 128; num2 -= 4194304; } goto IL_0021; } } } } else { num = 1; } goto IL_0153; } goto IL_0163; IL_0021: bytesConsumed = num + 1; result = UnsafeCreate(num2); return OperationStatus.Done; IL_0153: bytesConsumed = num; result = ReplacementChar; return OperationStatus.InvalidData; IL_0163: bytesConsumed = num; result = ReplacementChar; return OperationStatus.NeedMoreData; } public override bool Equals([NotNullWhen(true)] object obj) { if (obj is Rune other) { return Equals(other); } return false; } public bool Equals(Rune other) { return this == other; } public override int GetHashCode() { return Value; } public static bool TryCreate(char ch, out Rune result) { if (!System.Text.UnicodeUtility.IsSurrogateCodePoint(ch)) { result = UnsafeCreate(ch); return true; } result = default(Rune); return false; } public static bool TryCreate(char highSurrogate, char lowSurrogate, out Rune result) { uint num = (uint)(highSurrogate - 55296); uint num2 = (uint)(lowSurrogate - 56320); if ((num | num2) <= 1023) { result = UnsafeCreate((uint)((int)(num << 10) + (lowSurrogate - 56320) + 65536)); return true; } result = default(Rune); return false; } public bool TryEncodeToUtf16(Span<char> destination, out int charsWritten) { if (destination.Length >= 1) { if (IsBmp) { destination[0] = (char)_value; charsWritten = 1; return true; } if (destination.Length >= 2) { System.Text.UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out destination[0], out destination[1]); charsWritten = 2; return true; } } charsWritten = 0; return false; } public bool TryEncodeToUtf8(Span<byte> destination, out int bytesWritten) { if (destination.Length >= 1) { if (IsAscii) { destination[0] = (byte)_value; bytesWritten = 1; return true; } if (destination.Length >= 2) { if (_value <= 2047) { destination[0] = (byte)(_value + 12288 >> 6); destination[1] = (byte)((_value & 0x3F) + 128); bytesWritten = 2; return true; } if (destination.Length >= 3) { if (_value <= 65535) { destination[0] = (byte)(_value + 917504 >> 12); destination[1] = (byte)(((_value & 0xFC0) >> 6) + 128); destination[2] = (byte)((_value & 0x3F) + 128); bytesWritten = 3; return true; } if (destination.Length >= 4) { destination[0] = (byte)(_value + 62914560 >> 18); destination[1] = (byte)(((_value & 0x3F000) >> 12) + 128); destination[2] = (byte)(((_value & 0xFC0) >> 6) + 128); destination[3] = (byte)((_value & 0x3F) + 128); bytesWritten = 4; return true; } } } } bytesWritten = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Rune UnsafeCreate(uint scalarValue) { return new Rune(scalarValue, unused: false); } } } namespace System.Text.Unicode { internal static class UnicodeHelpers { internal const int UNICODE_LAST_CODEPOINT = 1114111; private static ReadOnlySpan<byte> DefinedCharsBitmapSpan => new byte[8192] { 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, 0, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 240, 215, 255, 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 127, 254, 255, 255, 255, 255, 255, 231, 254, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 135, 31, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 255, 255, 63, 255, 127, 255, 255, 255, 79, 255, 7, 255, 255, 255, 127, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 239, 159, 249, 255, 255, 253, 197, 243, 159, 121, 128, 176, 207, 255, 255, 127, 238, 135, 249, 255, 255, 253, 109, 211, 135, 57, 2, 94, 192, 255, 127, 0, 238, 191, 251, 255, 255, 253, 237, 243, 191, 59, 1, 0, 207, 255, 3, 254, 238, 159, 249, 255, 255, 253, 237, 243, 159, 57, 224, 176, 207, 255, 255, 0, 236, 199, 61, 214, 24, 199, 255, 195, 199, 61, 129, 0, 192, 255, 255, 7, 255, 223, 253, 255, 255, 253, 255, 243, 223, 61, 96, 39, 207, 255, 128, 255, 255, 223, 253, 255, 255, 253, 239, 243, 223, 61, 96, 96, 207, 255, 6, 0, 255, 223, 253, 255, 255, 255, 255, 255, 223, 253, 240, 255, 207, 255, 255, 255, 238, 255, 127, 252, 255, 255, 251, 47, 127, 132, 95, 255, 192, 255, 28, 0, 254, 255, 255, 255, 255, 255, 255, 135, 255, 255, 255, 15, 0, 0, 0, 0, 214, 247, 255, 255, 175, 255, 255, 63, 95, 63, 255, 243, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 31, 254, 255, 255, 255, 255, 254, 255, 255, 255, 223, 255, 223, 255, 7, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 32, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 61, 127, 61, 255, 255, 255, 255, 255, 61, 255, 255, 255, 255, 61, 127, 61, 255, 127, 255, 255, 255, 255, 255, 255, 255, 61, 255, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 31, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 63, 128, 255, 255, 127, 0, 255, 255, 15, 0, 255, 223, 13, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 3, 255, 3, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 255, 255, 7, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 255, 255, 255, 127, 255, 15, 255, 15, 241, 255, 255, 255, 255, 63, 31, 0, 255, 255, 255, 255, 255, 15, 255, 255, 255, 3, 255, 199, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 255, 255, 255, 255, 127, 255, 255, 255, 159, 255, 3, 255, 3, 255, 63, 255, 255, 255, 127, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 240, 255, 255, 255, 255, 255, 255, 255, 248, 255, 227, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 255, 255, 231, 255, 0, 255, 255, 255, 255, 255, 7, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 63, 255, 255, 255, 255, 63, 63, 255, 170, 255, 255, 255, 63, 255, 255, 255, 255, 255, 255, 223, 255, 223, 255, 207, 239, 255, 255, 220, 127, 0, 248, 255, 255, 255, 124, 255, 255, 255, 255, 255, 127, 223, 255, 243, 255, 255, 127, 255, 31, 255, 255, 255, 255, 1, 0, 255, 255, 255, 255, 1, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, 255, 7, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 254, 255, 255, 255, 255, 191, 32, 255, 255, 255, 255, 255, 255, 255, 128, 1, 128, 255, 255, 127, 0, 127, 127, 127, 127, 127, 127, 127, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 0, 0, 0, 255, 255, 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 0, 0, 255, 15, 254, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 224, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 127, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 235, 3, 0, 0, 252, 255, 255, 255, 255, 255, 255, 31, 255, 3, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, 63, 192, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 128, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 195, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 127, 0, 255, 63, 255, 243, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 0, 0, 248, 255, 255, 127, 0, 126, 126, 126, 0, 127, 127, 255, 255, 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 127, 248, 255, 255, 255, 255, 255, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 0, 0, 0, 127, 0, 248, 224, 255, 255, 127, 95, 219, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 0, 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 128, 0, 0, 0, 0, 255, 255, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 247, 255, 127, 15, 223, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 252, 252, 252, 28, 127, 127, 0, 62 }; internal static ReadOnlySpan<byte> GetDefinedBmpCodePointsBitmapLittleEndian() { return DefinedCharsBitmapSpan; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void GetUtf16SurrogatePairFromAstralScalarValue(uint scalar, out char highSurrogate, out char lowSurrogate) { highSurrogate = (char)(scalar + 56557568 >> 10); lowSurrogate = (char)((scalar & 0x3FF) + 56320); } internal static int GetUtf8RepresentationForScalarValue(uint scalar) { if (scalar <= 127) { return (byte)scalar; } if (scalar <= 2047) { byte b = (byte)(0xC0u | (scalar >> 6)); byte b2 = (byte)(0x80u | (scalar & 0x3Fu)); return (b2 << 8) | b; } if (scalar <= 65535) { byte b3 = (byte)(0xE0u | (scalar >> 12)); byte b4 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu)); byte b5 = (byte)(0x80u | (scalar & 0x3Fu)); return (((b5 << 8) | b4) << 8) | b3; } byte b6 = (byte)(0xF0u | (scalar >> 18)); byte b7 = (byte)(0x80u | ((scalar >> 12) & 0x3Fu)); byte b8 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu)); byte b9 = (byte)(0x80u | (scalar & 0x3Fu)); return (((((b9 << 8) | b8) << 8) | b7) << 8) | b6; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsSupplementaryCodePoint(int scalar) { return (scalar & -65536) != 0; } } public sealed class UnicodeRange { public int FirstCodePoint { get; private set; } public int Length { get; private set; } public UnicodeRange(int firstCodePoint, int length) { if (firstCodePoint < 0 || firstCodePoint > 65535) { throw new ArgumentOutOfRangeException("firstCodePoint"); } if (length < 0 || (long)firstCodePoint + (long)length > 65536) { throw new ArgumentOutOfRangeException("length"); } FirstCodePoint = firstCodePoint; Length = length; } public static UnicodeRange Create(char firstCharacter, char lastCharacter) { if (lastCharacter < firstCharacter) { throw new ArgumentOutOfRangeException("lastCharacter"); } return new UnicodeRange(firstCharacter, 1 + (lastCharacter - firstCharacter)); } } public static class UnicodeRanges { private static UnicodeRange _none; private static UnicodeRange _all; private static UnicodeRange _u0000; private static UnicodeRange _u0080; private static UnicodeRange _u0100; private static UnicodeRange _u0180; private static UnicodeRange _u0250; private static UnicodeRange _u02B0; private static UnicodeRange _u0300; private static UnicodeRange _u0370; private static UnicodeRange _u0400; private static UnicodeRange _u0500; private static UnicodeRange _u0530; private static UnicodeRange _u0590; private static UnicodeRange _u0600; private static UnicodeRange _u0700; private static UnicodeRange _u0750; private static UnicodeRange _u0780; private static UnicodeRange _u07C0; private static UnicodeRange _u0800; private static UnicodeRange _u0840; private static UnicodeRange _u0860; private static UnicodeRange _u0870; private static UnicodeRange _u08A0; private static UnicodeRange _u0900; private static UnicodeRange _u0980; private static UnicodeRange _u0A00; private static UnicodeRange _u0A80; private static UnicodeRange _u0B00; private static UnicodeRange _u0B80; private static UnicodeRange _u0C00; private static UnicodeRange _u0C80; private static UnicodeRange _u0D00; private static UnicodeRange _u0D80; private static UnicodeRange _u0E00; private static UnicodeRange _u0E80; private static UnicodeRange _u0F00; private static UnicodeRange _u1000; private static UnicodeRange _u10A0; private static UnicodeRange _u1100; private static UnicodeRange _u1200; private static UnicodeRange _u1380; private static UnicodeRange _u13A0; private static UnicodeRange _u1400; private static UnicodeRange _u1680; private static UnicodeRange _u16A0; private static UnicodeRange _u1700; private static UnicodeRange _u1720; private static UnicodeRange _u1740; private static UnicodeRange _u1760; private static UnicodeRange _u1780; private static UnicodeRange _u1800; private static UnicodeRange _u18B0; private static UnicodeRange _u1900; private static UnicodeRange _u1950; private static UnicodeRange _u1980; private static UnicodeRange _u19E0; private static UnicodeRange _u1A00; private static UnicodeRange _u1A20; private static UnicodeRange _u1AB0; private static UnicodeRange _u1B00; private static UnicodeRange _u1B80; private static UnicodeRange _u1BC0; private static UnicodeRange _u1C00; private static UnicodeRange _u1C50; private static UnicodeRange _u1C80; private static UnicodeRange _u1C90; private static UnicodeRange _u1CC0; private static UnicodeRange _u1CD0; private static UnicodeRange _u1D00; private static UnicodeRange _u1D80; private static UnicodeRange _u1DC0; private static UnicodeRange _u1E00; private static UnicodeRange _u1F00; private static UnicodeRange _u2000; private static UnicodeRange _u2070; private static UnicodeRange _u20A0; private static UnicodeRange _u20D0; private static UnicodeRange _u2100; private static UnicodeRange _u2150; private static UnicodeRange _u2190; private static UnicodeRange _u2200; private static UnicodeRange _u2300; private static UnicodeRange _u2400; private static UnicodeRange _u2440; private static UnicodeRange _u2460; private static UnicodeRange _u2500; private static UnicodeRange _u2580; private static UnicodeRange _u25A0; private static UnicodeRange _u2600; private static UnicodeRange _u2700; private static UnicodeRange _u27C0; private static UnicodeRange _u27F0; private static UnicodeRange _u2800; private static UnicodeRange _u2900; private static UnicodeRange _u2980; private static UnicodeRange _u2A00; private static UnicodeRange _u2B00; private static UnicodeRange _u2C00; private static UnicodeRange _u2C60; private static UnicodeRange _u2C80; private static UnicodeRange _u2D00; private static UnicodeRange _u2D30; private static UnicodeRange _u2D80; private static UnicodeRange _u2DE0; private static UnicodeRange _u2E00; private static UnicodeRange _u2E80; private static UnicodeRange _u2F00; private static UnicodeRange _u2FF0; private static UnicodeRange _u3000; private static UnicodeRange _u3040; private static UnicodeRange _u30A0; private static UnicodeRange _u3100; private static UnicodeRange _u3130; private static UnicodeRange _u3190; private static UnicodeRange _u31A0; private static UnicodeRange _u31C0; private static UnicodeRange _u31F0; private static UnicodeRange _u3200; private static UnicodeRange _u3300; private static UnicodeRange _u3400; private static UnicodeRange _u4DC0; private static UnicodeRange _u4E00; private static UnicodeRange _uA000; private static UnicodeRange _uA490; private static UnicodeRange _uA4D0; private static UnicodeRange _uA500; private static UnicodeRange _uA640; private static UnicodeRange _uA6A0; private static UnicodeRange _uA700; private static UnicodeRange _uA720; private static UnicodeRange _uA800; private static UnicodeRange _uA830; private static UnicodeRange _uA840; private static UnicodeRange _uA880; private static UnicodeRange _uA8E0; private static UnicodeRange _uA900; private static UnicodeRange _uA930; private static UnicodeRange _uA960; private static UnicodeRange _uA980; private static UnicodeRange _uA9E0; private static UnicodeRange _uAA00; private static UnicodeRange _uAA60; private static UnicodeRange _uAA80; private static UnicodeRange _uAAE0; private static UnicodeRange _uAB00; private static UnicodeRange _uAB30; private static UnicodeRange _uAB70; private static UnicodeRange _uABC0; private static UnicodeRange _uAC00; private static UnicodeRange _uD7B0; private static UnicodeRange _uF900; private static UnicodeRange _uFB00; private static UnicodeRange _uFB50; private static UnicodeRange _uFE00; private static UnicodeRange _uFE10; private static UnicodeRange _uFE20; private static UnicodeRange _uFE30; private static UnicodeRange _uFE50; private static UnicodeRange _uFE70; private static UnicodeRange _uFF00; private static UnicodeRange _uFFF0; public static UnicodeRange None => _none ?? CreateEmptyRange(ref _none); public static UnicodeRange All => _all ?? CreateRange(ref _all, '\0', '\uffff'); public static UnicodeRange BasicLatin => _u0000 ?? CreateRange(ref _u0000, '\0', '\u007f'); public static UnicodeRange Latin1Supplement => _u0080 ?? CreateRange(ref _u0080, '\u0080', 'ÿ'); public static UnicodeRange LatinExtendedA => _u0100 ?? CreateRange(ref _u0100, 'Ā', 'ſ'); public static UnicodeRange LatinExtendedB => _u0180 ?? CreateRange(ref _u0180, 'ƀ', 'ɏ'); public static UnicodeRange IpaExtensions => _u0250 ?? CreateRange(ref _u0250, 'ɐ', 'ʯ'); public static UnicodeRange SpacingModifierLetters => _u02B0 ?? CreateRange(ref _u02B0, 'ʰ', '\u02ff'); public static UnicodeRange CombiningDiacriticalMarks => _u0300 ?? CreateRange(ref _u0300, '\u0300', '\u036f'); public static UnicodeRange GreekandCoptic => _u0370 ?? CreateRange(ref _u0370, 'Ͱ', 'Ͽ'); public static UnicodeRange Cyrillic => _u0400 ?? CreateRange(ref _u0400, 'Ѐ', 'ӿ'); public static UnicodeRange CyrillicSupplement => _u0500 ?? CreateRange(ref _u0500, 'Ԁ', 'ԯ'); public static UnicodeRange Armenian => _u0530 ?? CreateRange(ref _u0530, '\u0530', '֏'); public static UnicodeRange Hebrew => _u0590 ?? CreateRange(ref _u0590, '\u0590', '\u05ff'); public static UnicodeRange Arabic => _u0600 ?? CreateRange(ref _u0600, '\u0600', 'ۿ'); public static UnicodeRange Syriac => _u0700 ?? CreateRange(ref _u0700, '܀', 'ݏ'); public static UnicodeRange ArabicSupplement => _u0750 ?? CreateRange(ref _u0750, 'ݐ', 'ݿ'); public static UnicodeRange Thaana => _u0780 ?? CreateRange(ref _u0780, 'ހ', '\u07bf'); public static UnicodeRange NKo => _u07C0 ?? CreateRange(ref _u07C0, '߀', '߿'); public static UnicodeRange Samaritan => _u0800 ?? CreateRange(ref _u0800, 'ࠀ', '\u083f'); public static UnicodeRange Mandaic => _u0840 ?? CreateRange(ref _u0840, 'ࡀ', '\u085f'); public static UnicodeRange SyriacSupplement => _u0860 ?? CreateRange(ref _u0860, 'ࡠ', '\u086f'); public static UnicodeRange ArabicExtendedB => _u0870 ?? CreateRange(ref _u0870, '\u0870', '\u089f'); public static UnicodeRange ArabicExtendedA => _u08A0 ?? CreateRange(ref _u08A0, 'ࢠ', '\u08ff'); public static UnicodeRange Devanagari => _u0900 ?? CreateRange(ref _u0900, '\u0900', 'ॿ'); public static UnicodeRange Bengali => _u0980 ?? CreateRange(ref _u0980, 'ঀ', '\u09ff'); public static UnicodeRange Gurmukhi => _u0A00 ?? CreateRange(ref _u0A00, '\u0a00', '\u0a7f'); public static UnicodeRange Gujarati => _u0A80 ?? CreateRange(ref _u0A80, '\u0a80', '\u0aff'); public static UnicodeRange Oriya => _u0B00 ?? CreateRange(ref _u0B00, '\u0b00', '\u0b7f'); public static UnicodeRange Tamil => _u0B80 ?? CreateRange(ref _u0B80, '\u0b80', '\u0bff'); public static UnicodeRange Telugu => _u0C00 ?? CreateRange(ref _u0C00, '\u0c00', '౿'); public static UnicodeRange Kannada => _u0C80 ?? CreateRange(ref _u0C80, 'ಀ', '\u0cff'); public static UnicodeRange Malayalam => _u0D00 ?? CreateRange(ref _u0D00, '\u0d00', 'ൿ'); public static UnicodeRange Sinhala => _u0D80 ?? CreateRange(ref _u0D80, '\u0d80', '\u0dff'); public static UnicodeRange Thai => _u0E00 ?? CreateRange(ref _u0E00, '\u0e00', '\u0e7f'); public static UnicodeRange Lao => _u0E80 ?? CreateRange(ref _u0E80, '\u0e80', '\u0eff'); public static UnicodeRange Tibetan => _u0F00 ?? CreateRange(ref _u0F00, 'ༀ', '\u0fff'); public static UnicodeRange Myanmar => _u1000 ?? CreateRange(ref _u1000, 'က', '႟'); public static UnicodeRange Georgian => _u10A0 ?? CreateRange(ref _u10A0, 'Ⴀ', 'ჿ'); public static UnicodeRange HangulJamo => _u1100 ?? CreateRange(ref _u1100, 'ᄀ', 'ᇿ'); public static UnicodeRange Ethiopic => _u1200 ?? CreateRange(ref _u1200, 'ሀ', '\u137f'); public static UnicodeRange EthiopicSupplement => _u1380 ?? CreateRange(ref _u1380, 'ᎀ', '\u139f'); public static UnicodeRange Cherokee => _u13A0 ?? CreateRange(ref _u13A0, 'Ꭰ', '\u13ff'); public static UnicodeRange UnifiedCanadianAboriginalSyllabics => _u1400 ?? CreateRange(ref _u1400, '᐀', 'ᙿ'); public static UnicodeRange Ogham => _u1680 ?? CreateRange(ref _u1680, '\u1680', '\u169f'); public static UnicodeRange Runic => _u16A0 ?? CreateRange(ref _u16A0, 'ᚠ', '\u16ff'); public static UnicodeRange Tagalog => _u1700 ?? CreateRange(ref _u1700, 'ᜀ', '\u171f'); public static UnicodeRange Hanunoo => _u1720 ?? CreateRange(ref _u1720, 'ᜠ', '\u173f'); public static UnicodeRange Buhid => _u1740 ?? CreateRange(ref _u1740, 'ᝀ', '\u175f'); public static UnicodeRange Tagbanwa => _u1760 ?? CreateRange(ref _u1760, 'ᝠ', '\u177f'); public static UnicodeRange Khmer => _u1780 ?? CreateRange(ref _u1780, 'ក', '\u17ff'); public static UnicodeRange Mongolian => _u1800 ?? CreateRange(ref _u1800, '᠀', '\u18af'); public static UnicodeRange UnifiedCanadianAboriginalSyllabicsExtended => _u18B0 ?? CreateRange(ref _u18B0, 'ᢰ', '\u18ff'); public static UnicodeRange Limbu => _u1900 ?? CreateRange(ref _u1900, 'ᤀ', '᥏'); public static UnicodeRange TaiLe => _u1950 ?? CreateRange(ref _u1950, 'ᥐ', '\u197f'); public static UnicodeRange NewTaiLue => _u1980 ?? CreateRange(ref _u1980, 'ᦀ', '᧟'); public static UnicodeRange KhmerSymbols => _u19E0 ?? CreateRange(ref _u19E0, '᧠', '᧿'); public static UnicodeRange Buginese => _u1A00 ?? CreateRange(ref _u1A00, 'ᨀ', '᨟'); public static UnicodeRange TaiTham => _u1A20 ?? CreateRange(ref _u1A20, 'ᨠ', '\u1aaf'); public static UnicodeRange CombiningDiacriticalMarksExtended => _u1AB0 ?? CreateRange(ref _u1AB0, '\u1ab0', '\u1aff'); public static UnicodeRange Balinese => _u1B00 ?? CreateRange(ref _u1B00, '\u1b00', '\u1b7f'); public static UnicodeRange Sundanese => _u1B80 ?? CreateRange(ref _u1B80, '\u1b80', 'ᮿ'); public static UnicodeRange Batak => _u1BC0 ?? CreateRange(ref _u1BC0, 'ᯀ', '᯿'); public static UnicodeRange Lepcha => _u1C00 ?? CreateRange(ref _u1C00, 'ᰀ', 'ᱏ'); public static UnicodeRange OlChiki => _u1C50 ?? CreateRange(ref _u1C50, '᱐', '᱿'); public static UnicodeRange CyrillicExtendedC => _u1C80 ?? CreateRange(ref _u1C80, 'ᲀ', '\u1c8f'); public static UnicodeRange GeorgianExtended => _u1C90 ?? CreateRange(ref _u1C90, 'Ა', 'Ჿ'); public static UnicodeRange SundaneseSupplement => _u1CC0 ?? CreateRange(ref _u1CC0, '᳀', '\u1ccf'); public static UnicodeRange VedicExtensions => _u1CD0 ?? CreateRange(ref _u1CD0, '\u1cd0', '\u1cff'); public static UnicodeRange PhoneticExtensions => _u1D00 ?? CreateRange(ref _u1D00, 'ᴀ', 'ᵿ'); public static UnicodeRange PhoneticExtensionsSupplement => _u1D80 ?? CreateRange(ref _u1D80, 'ᶀ', 'ᶿ'); public static UnicodeRange CombiningDiacriticalMarksSupplement => _u1DC0 ?? CreateRange(ref _u1DC0, '\u1dc0', '\u1dff'); public static UnicodeRange LatinExtendedAdditional => _u1E00 ?? CreateRange(ref _u1E00, 'Ḁ', 'ỿ'); public static UnicodeRange GreekExtended => _u1F00 ?? CreateRange(ref _u1F00, 'ἀ', '\u1fff'); public static UnicodeRange GeneralPunctuation => _u2000 ?? CreateRange(ref _u2000, '\u2000', '\u206f'); public static UnicodeRange SuperscriptsandSubscripts => _u2070 ?? CreateRange(ref _u2070, '⁰', '\u209f'); public static UnicodeRange CurrencySymbols => _u20A0 ?? CreateRange(ref _u20A0, '₠', '\u20cf'); public static UnicodeRange CombiningDiacriticalMarksforSymbols => _u20D0 ?? CreateRange(ref _u20D0, '\u20d0', '\u20ff'); public static UnicodeRange LetterlikeSymbols => _u2100 ?? CreateRange(ref _u2100, '℀', '⅏'); public static UnicodeRange NumberForms => _u2150 ?? CreateRange(ref _u2150, '⅐', '\u218f'); public static UnicodeRange Arrows => _u2190 ?? CreateRange(ref _u2190, '←', '⇿'); public static UnicodeRange MathematicalOperators => _u2200 ?? CreateRange(ref _u2200, '∀', '⋿'); public static UnicodeRange MiscellaneousTechnical => _u2300 ?? CreateRange(ref _u2300, '⌀', '⏿'); public static UnicodeRange ControlPictures => _u2400 ?? CreateRange(ref _u2400, '␀', '\u243f'); public static UnicodeRange OpticalCharacterRecognition => _u2440 ?? CreateRange(ref _u2440, '⑀', '\u245f'); public static UnicodeRange EnclosedAlphanumerics => _u2460 ?? CreateRange(ref _u2460, '①', '⓿'); public static UnicodeRange BoxDrawing => _u2500 ?? CreateRange(ref _u2500, '─', '╿'); public static UnicodeRange BlockElements => _u2580 ?? CreateRange(ref _u2580, '▀', '▟'); public static UnicodeRange GeometricShapes => _u25A0 ?? CreateRange(ref _u25A0, '■', '◿'); public static UnicodeRange MiscellaneousSymbols => _u2600 ?? CreateRange(ref _u2600, '☀', '⛿'); public static UnicodeRange Dingbats => _u2700 ?? CreateRange(ref _u2700, '✀', '➿'); public static UnicodeRange MiscellaneousMathematicalSymbolsA => _u27C0 ?? CreateRange(ref _u27C0, '⟀', '⟯'); public static UnicodeRange SupplementalArrowsA => _u27F0 ?? CreateRange(ref _u27F0, '⟰', '⟿'); public static UnicodeRange BraillePatterns => _u2800 ?? CreateRange(ref _u2800, '⠀', '⣿'); public static UnicodeRange SupplementalArrowsB => _u2900 ?? CreateRange(ref _u2900, '⤀', '⥿'); public static UnicodeRange MiscellaneousMathematicalSymbolsB => _u2980 ?? CreateRange(ref _u2980, '⦀', '⧿'); public static UnicodeRange SupplementalMathematicalOperators => _u2A00 ?? CreateRange(ref _u2A00, '⨀', '⫿'); public static UnicodeRange MiscellaneousSymbolsandArrows => _u2B00 ?? CreateRange(ref _u2B00, '⬀', '⯿'); public static UnicodeRange Glagolitic => _u2C00 ?? CreateRange(ref _u2C00, 'Ⰰ', '\u2c5f'); public static UnicodeRange LatinExtendedC => _u2C60 ?? CreateRange(ref _u2C60, 'Ⱡ', 'Ɀ'); public static UnicodeRange Coptic => _u2C80 ?? CreateRange(ref _u2C80, 'Ⲁ', '⳿'); public static UnicodeRange GeorgianSupplement => _u2D00 ?? CreateRange(ref _u2D00, 'ⴀ', '\u2d2f'); public static UnicodeRange Tifinagh => _u2D30 ?? CreateRange(ref _u2D30, 'ⴰ', '\u2d7f'); public static UnicodeRange EthiopicExtended => _u2D80 ?? CreateRange(ref _u2D80, 'ⶀ', '\u2ddf'); public static UnicodeRange CyrillicExtendedA => _u2DE0 ?? CreateRange(ref _u2DE0, '\u2de0', '\u2dff'); public static UnicodeRange SupplementalPunctuation => _u2E00 ?? CreateRange(ref _u2E00, '⸀', '\u2e7f'); public static UnicodeRange CjkRadicalsSupplement => _u2E80 ?? CreateRange(ref _u2E80, '⺀', '\u2eff'); public static UnicodeRange KangxiRadicals => _u2F00 ?? CreateRange(ref _u2F00, '⼀', '\u2fdf'); public static UnicodeRange IdeographicDescriptionCharacters => _u2FF0 ?? CreateRange(ref _u2FF0, '⿰', '\u2fff'); public static UnicodeRange CjkSymbolsandPunctuation => _u3000 ?? CreateRange(ref _u3000, '\u3000', '〿'); public static UnicodeRange Hiragana => _u3040 ?? CreateRange(ref _u3040, '\u3040', 'ゟ'); public static UnicodeRange Katakana => _u30A0 ?? CreateRange(ref _u30A0, '゠', 'ヿ'); public static UnicodeRange Bopomofo => _u3100 ?? CreateRange(ref _u3100, '\u3100', 'ㄯ'); public static UnicodeRange HangulCompatibilityJamo => _u3130 ?? CreateRange(ref _u3130, '\u3130', '\u318f'); public static UnicodeRange Kanbun => _u3190 ?? CreateRange(ref _u3190, '㆐', '㆟'); public static UnicodeRange BopomofoExtended => _u31A0 ?? CreateRange(ref _u31A0, 'ㆠ', 'ㆿ'); public static UnicodeRange CjkStrokes => _u31C0 ?? CreateRange(ref _u31C0, '㇀', '\u31ef'); public static UnicodeRange KatakanaPhoneticExtensions => _u31F0 ?? CreateRange(ref _u31F0, 'ㇰ', 'ㇿ'); public static UnicodeRange EnclosedCjkLettersandMonths => _u3200 ?? CreateRange(ref _u3200, '㈀', '㋿'); public static UnicodeRange CjkCompatibility => _u3300 ?? CreateRange(ref _u3300, '㌀', '㏿'); public static UnicodeRange CjkUnifiedIdeographsExtensionA => _u3400 ?? CreateRange(ref _u3400, '㐀', '䶿'); public static UnicodeRange YijingHexagramSymbols => _u4DC0 ?? CreateRange(ref _u4DC0, '䷀', '䷿'); public static UnicodeRange CjkUnifiedIdeographs => _u4E00 ?? CreateRange(ref _u4E00, '一', '\u9fff'); public static UnicodeRange YiSyllables => _uA000 ?? CreateRange(ref _uA000, 'ꀀ', '\ua48f'); public static UnicodeRange YiRadicals => _uA490 ?? CreateRange(ref _uA490, '꒐', '\ua4cf'); public static UnicodeRange Lisu => _uA4D0 ?? CreateRange(ref _uA4D0, 'ꓐ', '꓿'); public static UnicodeRange Vai => _uA500 ?? CreateRange(ref _uA500, 'ꔀ', '\ua63f'); public static UnicodeRange CyrillicExtendedB => _uA640 ?? CreateRange(ref _uA640, 'Ꙁ', '\ua69f'); public static UnicodeRange Bamum => _uA6A0 ?? CreateRange(ref _uA6A0, 'ꚠ', '\ua6ff'); public static UnicodeRange ModifierToneLetters => _uA700 ?? CreateRange(ref _uA700, '\ua700', 'ꜟ'); public static UnicodeRange LatinExtendedD => _uA720 ?? CreateRange(ref _uA720, '\ua720', 'ꟿ'); public static UnicodeRange SylotiNagri => _uA800 ?? CreateRange(ref _uA800, 'ꠀ', '\ua82f'); public static UnicodeRange CommonIndicNumberForms => _uA830 ?? CreateRange(ref _uA830, '꠰', '\ua83f'); public static UnicodeRange Phagspa => _uA840 ?? CreateRange(ref _uA840, 'ꡀ', '\ua87f'); public static UnicodeRange Saurashtra => _uA880 ?? CreateRange(ref _uA880, '\ua880', '\ua8df'); public static UnicodeRange DevanagariExtended => _uA8E0 ?? CreateRange(ref _uA8E0, '\ua8e0', '\ua8ff'); public static UnicodeRange KayahLi => _uA900 ?? CreateRange(ref _uA900, '꤀', '꤯'); public static UnicodeRange Rejang => _uA930 ?? CreateRange(ref _uA930, 'ꤰ', '꥟'); public static UnicodeRange HangulJamoExtendedA => _uA960 ?? CreateRange(ref _uA960, 'ꥠ', '\ua97f'); public static UnicodeRange Javanese => _uA980 ?? CreateRange(ref _uA980, '\ua980', '꧟'); public static UnicodeRange MyanmarExtendedB => _uA9E0 ?? CreateRange(ref _uA9E0, 'ꧠ', '\ua9ff'); public static UnicodeRange Cham => _uAA00 ?? CreateRange(ref _uAA00, 'ꨀ', '꩟'); public static UnicodeRange MyanmarExtendedA => _uAA60 ?? CreateRange(ref _uAA60, 'ꩠ', 'ꩿ'); public static UnicodeRange TaiViet => _uAA80 ?? CreateRange(ref _uAA80, 'ꪀ', '꫟'); public static UnicodeRange MeeteiMayekExtensions => _uAAE0 ?? CreateRange(ref _uAAE0, 'ꫠ', '\uaaff'); public static UnicodeRange EthiopicExtendedA => _uAB00 ?? CreateRange(ref _uAB00, '\uab00', '\uab2f'); public static UnicodeRange LatinExtendedE => _uAB30 ?? CreateRange(ref _uAB30, 'ꬰ', '\uab6f'); public static UnicodeRange CherokeeSupplement => _uAB70 ?? CreateRange(ref _uAB70, 'ꭰ', 'ꮿ'); public static UnicodeRange MeeteiMayek => _uABC0 ?? CreateRange(ref _uABC0, 'ꯀ', '\uabff'); public static UnicodeRange HangulSyllables => _uAC00 ?? CreateRange(ref _uAC00, '가', '\ud7af'); public static UnicodeRange HangulJamoExtendedB => _uD7B0 ?? CreateRange(ref _uD7B0, 'ힰ', '\ud7ff'); public static UnicodeRange CjkCompatibilityIdeographs => _uF900 ?? CreateRange(ref _uF900, '豈', '\ufaff'); public static UnicodeRange AlphabeticPresentationForms => _uFB00 ?? CreateRange(ref _uFB00, 'ff', 'ﭏ'); public static UnicodeRange ArabicPresentationFormsA => _uFB50 ?? CreateRange(ref _uFB50, 'ﭐ', '\ufdff'); public static UnicodeRange VariationSelectors => _uFE00 ?? CreateRange(ref _uFE00, '\ufe00', '\ufe0f'); public static UnicodeRange VerticalForms => _uFE10 ?? CreateRange(ref _uFE10, '︐', '\ufe1f'); public static UnicodeRange CombiningHalfMarks => _uFE20 ?? CreateRange(ref _uFE20, '\ufe20', '\ufe2f'); public static UnicodeRange CjkCompatibilityForms => _uFE30 ?? CreateRange(ref _uFE30, '︰', '\ufe4f'); public static UnicodeRange SmallFormVariants => _uFE50 ?? CreateRange(ref _uFE50, '﹐', '\ufe6f'); public static UnicodeRange ArabicPresentationFormsB => _uFE70 ?? CreateRange(ref _uFE70, 'ﹰ', '\ufeff'); public static UnicodeRange HalfwidthandFullwidthForms => _uFF00 ?? CreateRange(ref _uFF00, '\uff00', '\uffef'); public static UnicodeRange Specials => _uFFF0 ?? CreateRange(ref _uFFF0, '\ufff0', '\uffff'); [MethodImpl(MethodImplOptions.NoInlining)] private static UnicodeRange CreateEmptyRange([NotNull] ref UnicodeRange range) { Volatile.Write(ref range, new UnicodeRange(0, 0)); return range; } [MethodImpl(MethodImplOptions.NoInlining)] private static UnicodeRange CreateRange([NotNull] ref UnicodeRange range, char first, char last) { Volatile.Write(ref range, UnicodeRange.Create(first, last)); return range; } } } namespace System.Text.Encodings.Web { internal struct AsciiByteMap { private const int BufferSize = 128; private unsafe fixed byte Buffer[128]; internal unsafe void InsertAsciiChar(char key, byte value) { if (key < '\u0080') { Buffer[(uint)key] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe readonly bool TryLookup(Rune key, out byte value) { if (key.IsAscii) { byte b = Buffer[(uint)key.Value]; if (b != 0) { value = b; return true; } } value = 0; return false; } } internal struct AllowedBmpCodePointsBitmap { private const int BitmapLengthInDWords = 2048; private unsafe fixed uint Bitmap[2048]; [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void AllowChar(char value) { _GetIndexAndOffset(value, out UIntPtr index, out int offset); ref uint reference = ref Bitmap[(ulong)index]; reference |= (uint)(1 << offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void ForbidChar(char value) { _GetIndexAndOffset(value, out UIntPtr index, out int offset); ref uint reference = ref Bitmap[(ulong)index]; reference &= (uint)(~(1 << offset)); } public void ForbidHtmlCharacters() { ForbidChar('<'); ForbidChar('>'); ForbidChar('&'); ForbidChar('\''); ForbidChar('"'); ForbidChar('+'); } public unsafe void ForbidUndefinedCharacters() { fixed (uint* pointer = Bitmap) { ReadOnlySpan<byte> definedBmpCodePointsBitmapLittleEndian = UnicodeHelpers.GetDefinedBmpCodePointsBitmapLittleEndian(); Span<uint> span = new Span<uint>(pointer, 2048); for (int i = 0; i < span.Length; i++) { span[i] &= BinaryPrimitives.ReadUInt32LittleEndian(definedBmpCodePointsBitmapLittleEndian.Slice(i * 4)); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe readonly bool IsCharAllowed(char value) { _GetIndexAndOffset(value, out UIntPtr index, out int offset); if ((Bitmap[(ulong)index] & (uint)(1 << offset)) != 0) { return true; } return
plugins/System.Text.Json.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Text; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.Encodings.Web; using System.Text.Json.Nodes; using System.Text.Json.Reflection; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Converters; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; using FxResources.System.Text.Json; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Text.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.\r\n\r\nThe System.Text.Json library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] [assembly: AssemblyFileVersion("7.0.723.27404")] [assembly: AssemblyInformationalVersion("7.0.7+5b20af47d99620150c53eaf5db8636fdf730b126")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Text.Json")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("7.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 IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Text.Json { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { 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; if ((long)(num2 & num3) >= 0L) { return false; } return true; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class Obsoletions { internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; internal const string ThreadAbortDiagId = "SYSLIB0006"; internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; internal const string AuthenticationManagerMessage = "The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException."; internal const string AuthenticationManagerDiagId = "SYSLIB0009"; internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; internal const string RemotingApisDiagId = "SYSLIB0010"; internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; internal const string BinaryFormatterDiagId = "SYSLIB0011"; internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; internal const string CodeBaseDiagId = "SYSLIB0012"; internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; internal const string EscapeUriStringDiagId = "SYSLIB0013"; internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; internal const string WebRequestDiagId = "SYSLIB0014"; internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; internal const string GetContextInfoDiagId = "SYSLIB0016"; internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; internal const string RijndaelDiagId = "SYSLIB0022"; internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate."; internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; internal const string UseManagedSha1DiagId = "SYSLIB0030"; internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead."; internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; internal const string TlsVersion10and11DiagId = "SYSLIB0039"; internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code."; internal const string EncryptionPolicyDiagId = "SYSLIB0040"; internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations."; internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041"; internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys."; internal const string EccXmlExportImportDiagId = "SYSLIB0042"; internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead."; internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043"; internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."; internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044"; internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead."; internal const string CryptoStringFactoryDiagId = "SYSLIB0045"; internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code."; internal const string ControlledExecutionRunDiagId = "SYSLIB0046"; internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution."; internal const string XmlSecureResolverDiagId = "SYSLIB0047"; } internal 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 ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge"); internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss"); internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16"); internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16"); internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose"); internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty"); internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8"); internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64"); internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16"); internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16"); internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8"); internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray"); internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty"); internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose"); internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject"); internal static string DepthTooLarge => GetResourceString("DepthTooLarge"); internal static string DestinationTooShort => GetResourceString("DestinationTooShort"); internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid"); internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound"); internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound"); internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson"); internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound"); internal static string ExpectedFalse => GetResourceString("ExpectedFalse"); internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens"); internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken"); internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound"); internal static string ExpectedNull => GetResourceString("ExpectedNull"); internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound"); internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound"); internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound"); internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound"); internal static string ExpectedTrue => GetResourceString("ExpectedTrue"); internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound"); internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan"); internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter"); internal static string InvalidCast => GetResourceString("InvalidCast"); internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString"); internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString"); internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive"); internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString"); internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments"); internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType"); internal static string TypeInfoResolverImmutable => GetResourceString("TypeInfoResolverImmutable"); internal static string TypeInfoImmutable => GetResourceString("TypeInfoImmutable"); internal static string PropertyInfoImmutable => GetResourceString("PropertyInfoImmutable"); internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive"); internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid"); internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray"); internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty"); internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge"); internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge"); internal static string FormatDecimal => GetResourceString("FormatDecimal"); internal static string FormatDouble => GetResourceString("FormatDouble"); internal static string FormatInt32 => GetResourceString("FormatInt32"); internal static string FormatInt64 => GetResourceString("FormatInt64"); internal static string FormatSingle => GetResourceString("FormatSingle"); internal static string FormatUInt32 => GetResourceString("FormatUInt32"); internal static string FormatUInt64 => GetResourceString("FormatUInt64"); internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal"); internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign"); internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData"); internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported"); internal static string ValueTooLarge => GetResourceString("ValueTooLarge"); internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd"); internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue"); internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType"); internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize"); internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar"); internal static string InvalidComparison => GetResourceString("InvalidComparison"); internal static string UnsupportedFormat => GetResourceString("UnsupportedFormat"); internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment"); internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd"); internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd"); internal static string SerializerOptionsImmutable => GetResourceString("SerializerOptionsImmutable"); internal static string StreamNotWritable => GetResourceString("StreamNotWritable"); internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter"); internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict"); internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull"); internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid"); internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute"); internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType"); internal static string TypeRequiresAsyncSerialization => GetResourceString("TypeRequiresAsyncSerialization"); internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment"); internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment"); internal static string CannotSkip => GetResourceString("CannotSkip"); internal static string NotEnoughData => GetResourceString("NotEnoughData"); internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator"); internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments"); internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor"); internal static string DeserializePolymorphicInterface => GetResourceString("DeserializePolymorphicInterface"); internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible"); internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid"); internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead"); internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible"); internal static string ResolverTypeNotCompatible => GetResourceString("ResolverTypeNotCompatible"); internal static string ResolverTypeInfoOptionsNotCompatible => GetResourceString("ResolverTypeInfoOptionsNotCompatible"); internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite"); internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull"); internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute"); internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize"); internal static string FormatByte => GetResourceString("FormatByte"); internal static string FormatInt16 => GetResourceString("FormatInt16"); internal static string FormatSByte => GetResourceString("FormatSByte"); internal static string FormatUInt16 => GetResourceString("FormatUInt16"); internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected"); internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber"); internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable"); internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound"); internal static string MetadataIdIsNotFirstProperty => GetResourceString("MetadataIdIsNotFirstProperty"); internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType"); internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues"); internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed"); internal static string MetadataInvalidPropertyInArrayMetadata => GetResourceString("MetadataInvalidPropertyInArrayMetadata"); internal static string MetadataStandaloneValuesProperty => GetResourceString("MetadataStandaloneValuesProperty"); internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties"); internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound"); internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString"); internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign"); internal static string MetadataUnexpectedProperty => GetResourceString("MetadataUnexpectedProperty"); internal static string MetadataDuplicateTypeProperty => GetResourceString("MetadataDuplicateTypeProperty"); internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter"); internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding"); internal static string ConstructorMaxOf64Parameters => GetResourceString("ConstructorMaxOf64Parameters"); internal static string ObjectWithParameterizedCtorRefMetadataNotSupported => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotSupported"); internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull"); internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType"); internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam"); internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded"); internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType"); internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported"); internal static string JsonIncludeOnNonPublicInvalid => GetResourceString("JsonIncludeOnNonPublicInvalid"); internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember"); internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection"); internal static string ConstructorContainsNullParameterNames => GetResourceString("ConstructorContainsNullParameterNames"); internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified"); internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid"); internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported"); internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid"); internal static string NumberHandlingOnPropertyInvalid => GetResourceString("NumberHandlingOnPropertyInvalid"); internal static string ConverterCanConvertMultipleTypes => GetResourceString("ConverterCanConvertMultipleTypes"); internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType"); internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue"); internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull"); internal static string SerializerConverterFactoryReturnsJsonConverterFactory => GetResourceString("SerializerConverterFactoryReturnsJsonConverterFactory"); internal static string NodeElementWrongType => GetResourceString("NodeElementWrongType"); internal static string NodeElementCannotBeObjectOrArray => GetResourceString("NodeElementCannotBeObjectOrArray"); internal static string NodeAlreadyHasParent => GetResourceString("NodeAlreadyHasParent"); internal static string NodeCycleDetected => GetResourceString("NodeCycleDetected"); internal static string NodeUnableToConvert => GetResourceString("NodeUnableToConvert"); internal static string NodeUnableToConvertElement => GetResourceString("NodeUnableToConvertElement"); internal static string NodeValueNotAllowed => GetResourceString("NodeValueNotAllowed"); internal static string NodeWrongType => GetResourceString("NodeWrongType"); internal static string NodeDuplicateKey => GetResourceString("NodeDuplicateKey"); internal static string SerializerContextOptionsImmutable => GetResourceString("SerializerContextOptionsImmutable"); internal static string ConverterForPropertyMustBeValid => GetResourceString("ConverterForPropertyMustBeValid"); internal static string NoMetadataForType => GetResourceString("NoMetadataForType"); internal static string CollectionIsReadOnly => GetResourceString("CollectionIsReadOnly"); internal static string ArrayIndexNegative => GetResourceString("ArrayIndexNegative"); internal static string ArrayTooSmall => GetResourceString("ArrayTooSmall"); internal static string NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty => GetResourceString("NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty"); internal static string NoMetadataForTypeProperties => GetResourceString("NoMetadataForTypeProperties"); internal static string FieldCannotBeVirtual => GetResourceString("FieldCannotBeVirtual"); internal static string MissingFSharpCoreMember => GetResourceString("MissingFSharpCoreMember"); internal static string FSharpDiscriminatedUnionsNotSupported => GetResourceString("FSharpDiscriminatedUnionsNotSupported"); internal static string NoMetadataForTypeCtorParams => GetResourceString("NoMetadataForTypeCtorParams"); internal static string Polymorphism_BaseConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_BaseConverterDoesNotSupportMetadata"); internal static string Polymorphism_DerivedConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_DerivedConverterDoesNotSupportMetadata"); internal static string Polymorphism_TypeDoesNotSupportPolymorphism => GetResourceString("Polymorphism_TypeDoesNotSupportPolymorphism"); internal static string Polymorphism_DerivedTypeIsNotSupported => GetResourceString("Polymorphism_DerivedTypeIsNotSupported"); internal static string Polymorphism_DerivedTypeIsAlreadySpecified => GetResourceString("Polymorphism_DerivedTypeIsAlreadySpecified"); internal static string Polymorphism_TypeDicriminatorIdIsAlreadySpecified => GetResourceString("Polymorphism_TypeDicriminatorIdIsAlreadySpecified"); internal static string Polymorphism_InvalidCustomTypeDiscriminatorPropertyName => GetResourceString("Polymorphism_InvalidCustomTypeDiscriminatorPropertyName"); internal static string Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes => GetResourceString("Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes"); internal static string Polymorphism_UnrecognizedTypeDiscriminator => GetResourceString("Polymorphism_UnrecognizedTypeDiscriminator"); internal static string Polymorphism_RuntimeTypeNotSupported => GetResourceString("Polymorphism_RuntimeTypeNotSupported"); internal static string Polymorphism_RuntimeTypeDiamondAmbiguity => GetResourceString("Polymorphism_RuntimeTypeDiamondAmbiguity"); internal static string InvalidJsonTypeInfoOperationForKind => GetResourceString("InvalidJsonTypeInfoOperationForKind"); internal static string CreateObjectConverterNotCompatible => GetResourceString("CreateObjectConverterNotCompatible"); internal static string CombineOneOfResolversIsNull => GetResourceString("CombineOneOfResolversIsNull"); internal static string JsonPropertyInfoBoundToDifferentParent => GetResourceString("JsonPropertyInfoBoundToDifferentParent"); internal static string JsonTypeInfoUsedButTypeInfoResolverNotSet => GetResourceString("JsonTypeInfoUsedButTypeInfoResolverNotSet"); internal static string JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo => GetResourceString("JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo"); internal static string JsonPropertyRequiredAndNotDeserializable => GetResourceString("JsonPropertyRequiredAndNotDeserializable"); internal static string JsonPropertyRequiredAndExtensionData => GetResourceString("JsonPropertyRequiredAndExtensionData"); internal static string JsonRequiredPropertiesMissing => GetResourceString("JsonRequiredPropertiesMissing"); 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; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class ObsoleteAttribute : Attribute { public string Message { get; } public bool IsError { get; } public string DiagnosticId { get; set; } public string UrlFormat { get; set; } public ObsoleteAttribute() { } public ObsoleteAttribute(string message) { Message = message; } public ObsoleteAttribute(string message, bool error) { Message = message; IsError = error; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class DynamicDependencyAttribute : Attribute { public string MemberSignature { get; } public DynamicallyAccessedMemberTypes MemberTypes { get; } public Type Type { get; } public string TypeName { get; } public string AssemblyName { get; } public string Condition { get; set; } public DynamicDependencyAttribute(string memberSignature) { MemberSignature = memberSignature; } public DynamicDependencyAttribute(string memberSignature, Type type) { MemberSignature = memberSignature; Type = type; } public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) { MemberSignature = memberSignature; TypeName = typeName; AssemblyName = assemblyName; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) { MemberTypes = memberTypes; Type = type; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) { MemberTypes = memberTypes; TypeName = typeName; AssemblyName = assemblyName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string Scope { get; set; } public string Target { get; set; } public string MessageId { get; set; } public string Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = Array.Empty<object>(); } public StringSyntaxAttribute(string syntax, params object[] arguments) { Syntax = syntax; Arguments = arguments; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.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)] 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 { [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } } namespace System.Collections.Generic { internal sealed class ReferenceEqualityComparer : IEqualityComparer<object>, IEqualityComparer { public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer(); private ReferenceEqualityComparer() { } public new bool Equals(object x, object y) { return x == y; } public int GetHashCode(object obj) { return RuntimeHelpers.GetHashCode(obj); } } internal static class StackExtensions { public static bool TryPeek<T>(this Stack<T> stack, [MaybeNullWhen(false)] out T result) { if (stack.Count > 0) { result = stack.Peek(); return true; } result = default(T); return false; } public static bool TryPop<T>(this Stack<T> stack, [MaybeNullWhen(false)] out T result) { if (stack.Count > 0) { result = stack.Pop(); return true; } result = default(T); return false; } } } namespace System.Buffers { internal sealed class ArrayBufferWriter<T> : IBufferWriter<T> { private const int ArrayMaxLength = 2147483591; private const int DefaultInitialBufferSize = 256; private T[] _buffer; private int _index; public ReadOnlyMemory<T> WrittenMemory => _buffer.AsMemory(0, _index); public ReadOnlySpan<T> WrittenSpan => _buffer.AsSpan(0, _index); public int WrittenCount => _index; public int Capacity => _buffer.Length; public int FreeCapacity => _buffer.Length - _index; public ArrayBufferWriter() { _buffer = Array.Empty<T>(); _index = 0; } public ArrayBufferWriter(int initialCapacity) { if (initialCapacity <= 0) { throw new ArgumentException(null, "initialCapacity"); } _buffer = new T[initialCapacity]; _index = 0; } public void Clear() { _buffer.AsSpan(0, _index).Clear(); _index = 0; } public void Advance(int count) { if (count < 0) { throw new ArgumentException(null, "count"); } if (_index > _buffer.Length - count) { ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length); } _index += count; } public Memory<T> GetMemory(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _buffer.AsMemory(_index); } public Span<T> GetSpan(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _buffer.AsSpan(_index); } private void CheckAndResizeBuffer(int sizeHint) { if (sizeHint < 0) { throw new ArgumentException("sizeHint"); } if (sizeHint == 0) { sizeHint = 1; } if (sizeHint <= FreeCapacity) { return; } int num = _buffer.Length; int num2 = Math.Max(sizeHint, num); if (num == 0) { num2 = Math.Max(num2, 256); } int num3 = num + num2; if ((uint)num3 > 2147483647u) { uint num4 = (uint)(num - FreeCapacity + sizeHint); if (num4 > 2147483591) { ThrowOutOfMemoryException(num4); } num3 = 2147483591; } Array.Resize(ref _buffer, num3); } private static void ThrowInvalidOperationException_AdvancedTooFar(int capacity) { throw new InvalidOperationException(System.SR.Format(System.SR.BufferWriterAdvancedTooFar, capacity)); } private static void ThrowOutOfMemoryException(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } } } namespace System.Buffers.Text { internal enum SequenceValidity { Empty, WellFormed, Incomplete, Invalid } } namespace System.Text.Json { internal sealed class PooledByteBufferWriter : IBufferWriter<byte>, IDisposable { private byte[] _rentedBuffer; private int _index; private const int MinimumBufferSize = 256; public ReadOnlyMemory<byte> WrittenMemory => _rentedBuffer.AsMemory(0, _index); public int WrittenCount => _index; public int Capacity => _rentedBuffer.Length; public int FreeCapacity => _rentedBuffer.Length - _index; private PooledByteBufferWriter() { } public PooledByteBufferWriter(int initialCapacity) { _rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } public void Clear() { ClearHelper(); } public void ClearAndReturnBuffers() { ClearHelper(); byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; ArrayPool<byte>.Shared.Return(rentedBuffer); } private void ClearHelper() { _rentedBuffer.AsSpan(0, _index).Clear(); _index = 0; } public void Dispose() { if (_rentedBuffer != null) { ClearHelper(); byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; ArrayPool<byte>.Shared.Return(rentedBuffer); } } public void InitializeEmptyInstance(int initialCapacity) { _rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } public static PooledByteBufferWriter CreateEmptyInstanceForCaching() { return new PooledByteBufferWriter(); } public void Advance(int count) { _index += count; } public Memory<byte> GetMemory(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _rentedBuffer.AsMemory(_index); } public Span<byte> GetSpan(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _rentedBuffer.AsSpan(_index); } internal Task WriteToStreamAsync(Stream destination, CancellationToken cancellationToken) { return destination.WriteAsync(_rentedBuffer, 0, _index, cancellationToken); } internal void WriteToStream(Stream destination) { destination.Write(_rentedBuffer, 0, _index); } private void CheckAndResizeBuffer(int sizeHint) { if (sizeHint == 0) { sizeHint = 256; } int num = _rentedBuffer.Length - _index; if (sizeHint <= num) { return; } int num2 = _rentedBuffer.Length; int num3 = Math.Max(sizeHint, num2); int num4 = num2 + num3; if ((uint)num4 > 2147483647u) { num4 = num2 + sizeHint; if ((uint)num4 > 2147483647u) { ThrowHelper.ThrowOutOfMemoryException_BufferMaximumSizeExceeded((uint)num4); } } byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = ArrayPool<byte>.Shared.Rent(num4); Span<byte> span = rentedBuffer.AsSpan(0, _index); span.CopyTo(_rentedBuffer); span.Clear(); ArrayPool<byte>.Shared.Return(rentedBuffer); } } internal static class ThrowHelper { public const string ExceptionSourceValueToRethrowAsJsonException = "System.Text.Json.Rethrowable"; [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowOutOfMemoryException_BufferMaximumSizeExceeded(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } [DoesNotReturn] public static void ThrowArgumentNullException(string parameterName) { throw new ArgumentNullException(parameterName); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_MaxDepthMustBePositive(string parameterName) { throw GetArgumentOutOfRangeException(parameterName, System.SR.MaxDepthMustBePositive); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(string parameterName, string message) { return new ArgumentOutOfRangeException(parameterName, message); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_CommentEnumMustBeInRange(string parameterName) { throw GetArgumentOutOfRangeException(parameterName, System.SR.CommentHandlingMustBeValid); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_ArrayIndexNegative(string paramName) { throw new ArgumentOutOfRangeException(paramName, System.SR.ArrayIndexNegative); } [DoesNotReturn] public static void ThrowArgumentException_ArrayTooSmall(string paramName) { throw new ArgumentException(System.SR.ArrayTooSmall, paramName); } private static ArgumentException GetArgumentException(string message) { return new ArgumentException(message); } [DoesNotReturn] public static void ThrowArgumentException(string message) { throw GetArgumentException(message); } public static InvalidOperationException GetInvalidOperationException_CallFlushFirst(int _buffered) { return GetInvalidOperationException(System.SR.Format(System.SR.CallFlushToAvoidDataLoss, _buffered)); } [DoesNotReturn] public static void ThrowArgumentException_DestinationTooShort() { throw GetArgumentException(System.SR.DestinationTooShort); } [DoesNotReturn] public static void ThrowArgumentException_PropertyNameTooLarge(int tokenLength) { throw GetArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, tokenLength)); } [DoesNotReturn] public static void ThrowArgumentException_ValueTooLarge(int tokenLength) { throw GetArgumentException(System.SR.Format(System.SR.ValueTooLarge, tokenLength)); } [DoesNotReturn] public static void ThrowArgumentException_ValueNotSupported() { throw GetArgumentException(System.SR.SpecialNumberValuesNotSupported); } [DoesNotReturn] public static void ThrowInvalidOperationException_NeedLargerSpan() { throw GetInvalidOperationException(System.SR.FailedToGetLargerSpan); } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<byte> propertyName, ReadOnlySpan<byte> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<byte> propertyName, ReadOnlySpan<char> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<char> propertyName, ReadOnlySpan<byte> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<char> propertyName, ReadOnlySpan<char> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan<byte> propertyName, int currentDepth, int maxDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth >= maxDepth) { ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); } else { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } } [DoesNotReturn] public static void ThrowInvalidOperationException(int currentDepth, int maxDepth) { currentDepth &= 0x7FFFFFFF; ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); } [DoesNotReturn] public static void ThrowInvalidOperationException(string message) { throw GetInvalidOperationException(message); } private static InvalidOperationException GetInvalidOperationException(string message) { return new InvalidOperationException(message) { Source = "System.Text.Json.Rethrowable" }; } [DoesNotReturn] public static void ThrowInvalidOperationException_DepthNonZeroOrEmptyJson(int currentDepth) { throw GetInvalidOperationException(currentDepth); } private static InvalidOperationException GetInvalidOperationException(int currentDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth != 0) { return GetInvalidOperationException(System.SR.Format(System.SR.ZeroDepthAtEnd, currentDepth)); } return GetInvalidOperationException(System.SR.EmptyJsonIsInvalid); } [DoesNotReturn] public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan<char> propertyName, int currentDepth, int maxDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth >= maxDepth) { ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); } else { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } } public static InvalidOperationException GetInvalidOperationException_ExpectedArray(JsonTokenType tokenType) { return GetInvalidOperationException("array", tokenType); } public static InvalidOperationException GetInvalidOperationException_ExpectedObject(JsonTokenType tokenType) { return GetInvalidOperationException("object", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedNumber(JsonTokenType tokenType) { throw GetInvalidOperationException("number", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedBoolean(JsonTokenType tokenType) { throw GetInvalidOperationException("boolean", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedString(JsonTokenType tokenType) { throw GetInvalidOperationException("string", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedStringComparison(JsonTokenType tokenType) { throw GetInvalidOperationException(tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedComment(JsonTokenType tokenType) { throw GetInvalidOperationException("comment", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_CannotSkipOnPartial() { throw GetInvalidOperationException(System.SR.CannotSkip); } private static InvalidOperationException GetInvalidOperationException(string message, JsonTokenType tokenType) { return GetInvalidOperationException(System.SR.Format(System.SR.InvalidCast, tokenType, message)); } private static InvalidOperationException GetInvalidOperationException(JsonTokenType tokenType) { return GetInvalidOperationException(System.SR.Format(System.SR.InvalidComparison, tokenType)); } [DoesNotReturn] internal static void ThrowJsonElementWrongTypeException(JsonTokenType expectedType, JsonTokenType actualType) { throw GetJsonElementWrongTypeException(expectedType.ToValueKind(), actualType.ToValueKind()); } internal static InvalidOperationException GetJsonElementWrongTypeException(JsonValueKind expectedType, JsonValueKind actualType) { return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedType, actualType)); } internal static InvalidOperationException GetJsonElementWrongTypeException(string expectedTypeName, JsonValueKind actualType) { return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedTypeName, actualType)); } [DoesNotReturn] public static void ThrowJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte = 0, ReadOnlySpan<byte> bytes = default(ReadOnlySpan<byte>)) { throw GetJsonReaderException(ref json, resource, nextByte, bytes); } [MethodImpl(MethodImplOptions.NoInlining)] public static JsonException GetJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, ReadOnlySpan<byte> bytes) { string resourceString = GetResourceString(ref json, resource, nextByte, JsonHelpers.Utf8GetString(bytes)); long lineNumber = json.CurrentState._lineNumber; long bytePositionInLine = json.CurrentState._bytePositionInLine; resourceString += $" LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; return new JsonReaderException(resourceString, lineNumber, bytePositionInLine); } private static bool IsPrintable(byte value) { if (value >= 32) { return value < 127; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static string GetPrintableString(byte value) { if (!IsPrintable(value)) { return $"0x{value:X2}"; } char c = (char)value; return c.ToString(); } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, string characters) { string printableString = GetPrintableString(nextByte); string result = ""; switch (resource) { case ExceptionResource.ArrayDepthTooLarge: result = System.SR.Format(System.SR.ArrayDepthTooLarge, json.CurrentState.Options.MaxDepth); break; case ExceptionResource.MismatchedObjectArray: result = System.SR.Format(System.SR.MismatchedObjectArray, printableString); break; case ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd: result = System.SR.TrailingCommaNotAllowedBeforeArrayEnd; break; case ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd: result = System.SR.TrailingCommaNotAllowedBeforeObjectEnd; break; case ExceptionResource.EndOfStringNotFound: result = System.SR.EndOfStringNotFound; break; case ExceptionResource.RequiredDigitNotFoundAfterSign: result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterSign, printableString); break; case ExceptionResource.RequiredDigitNotFoundAfterDecimal: result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterDecimal, printableString); break; case ExceptionResource.RequiredDigitNotFoundEndOfData: result = System.SR.RequiredDigitNotFoundEndOfData; break; case ExceptionResource.ExpectedEndAfterSingleJson: result = System.SR.Format(System.SR.ExpectedEndAfterSingleJson, printableString); break; case ExceptionResource.ExpectedEndOfDigitNotFound: result = System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, printableString); break; case ExceptionResource.ExpectedNextDigitEValueNotFound: result = System.SR.Format(System.SR.ExpectedNextDigitEValueNotFound, printableString); break; case ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound: result = System.SR.Format(System.SR.ExpectedSeparatorAfterPropertyNameNotFound, printableString); break; case ExceptionResource.ExpectedStartOfPropertyNotFound: result = System.SR.Format(System.SR.ExpectedStartOfPropertyNotFound, printableString); break; case ExceptionResource.ExpectedStartOfPropertyOrValueNotFound: result = System.SR.ExpectedStartOfPropertyOrValueNotFound; break; case ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment: result = System.SR.Format(System.SR.ExpectedStartOfPropertyOrValueAfterComment, printableString); break; case ExceptionResource.ExpectedStartOfValueNotFound: result = System.SR.Format(System.SR.ExpectedStartOfValueNotFound, printableString); break; case ExceptionResource.ExpectedValueAfterPropertyNameNotFound: result = System.SR.ExpectedValueAfterPropertyNameNotFound; break; case ExceptionResource.FoundInvalidCharacter: result = System.SR.Format(System.SR.FoundInvalidCharacter, printableString); break; case ExceptionResource.InvalidEndOfJsonNonPrimitive: result = System.SR.Format(System.SR.InvalidEndOfJsonNonPrimitive, json.TokenType); break; case ExceptionResource.ObjectDepthTooLarge: result = System.SR.Format(System.SR.ObjectDepthTooLarge, json.CurrentState.Options.MaxDepth); break; case ExceptionResource.ExpectedFalse: result = System.SR.Format(System.SR.ExpectedFalse, characters); break; case ExceptionResource.ExpectedNull: result = System.SR.Format(System.SR.ExpectedNull, characters); break; case ExceptionResource.ExpectedTrue: result = System.SR.Format(System.SR.ExpectedTrue, characters); break; case ExceptionResource.InvalidCharacterWithinString: result = System.SR.Format(System.SR.InvalidCharacterWithinString, printableString); break; case ExceptionResource.InvalidCharacterAfterEscapeWithinString: result = System.SR.Format(System.SR.InvalidCharacterAfterEscapeWithinString, printableString); break; case ExceptionResource.InvalidHexCharacterWithinString: result = System.SR.Format(System.SR.InvalidHexCharacterWithinString, printableString); break; case ExceptionResource.EndOfCommentNotFound: result = System.SR.EndOfCommentNotFound; break; case ExceptionResource.ZeroDepthAtEnd: result = System.SR.Format(System.SR.ZeroDepthAtEnd); break; case ExceptionResource.ExpectedJsonTokens: result = System.SR.ExpectedJsonTokens; break; case ExceptionResource.NotEnoughData: result = System.SR.NotEnoughData; break; case ExceptionResource.ExpectedOneCompleteToken: result = System.SR.ExpectedOneCompleteToken; break; case ExceptionResource.InvalidCharacterAtStartOfComment: result = System.SR.Format(System.SR.InvalidCharacterAtStartOfComment, printableString); break; case ExceptionResource.UnexpectedEndOfDataWhileReadingComment: result = System.SR.Format(System.SR.UnexpectedEndOfDataWhileReadingComment); break; case ExceptionResource.UnexpectedEndOfLineSeparator: result = System.SR.Format(System.SR.UnexpectedEndOfLineSeparator); break; case ExceptionResource.InvalidLeadingZeroInNumber: result = System.SR.Format(System.SR.InvalidLeadingZeroInNumber, printableString); break; } return result; } [DoesNotReturn] public static void ThrowInvalidOperationException(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) { throw GetInvalidOperationException(resource, currentDepth, maxDepth, token, tokenType); } [DoesNotReturn] public static void ThrowArgumentException_InvalidCommentValue() { throw new ArgumentException(System.SR.CannotWriteCommentWithEmbeddedDelimiter); } [DoesNotReturn] public static void ThrowArgumentException_InvalidUTF8(ReadOnlySpan<byte> value) { StringBuilder stringBuilder = new StringBuilder(); int num = Math.Min(value.Length, 10); for (int i = 0; i < num; i++) { byte b = value[i]; if (IsPrintable(b)) { stringBuilder.Append((char)b); } else { stringBuilder.Append($"0x{b:X2}"); } } if (num < value.Length) { stringBuilder.Append("..."); } throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF8, stringBuilder)); } [DoesNotReturn] public static void ThrowArgumentException_InvalidUTF16(int charAsInt) { throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF16, $"0x{charAsInt:X2}")); } [DoesNotReturn] public static void ThrowInvalidOperationException_ReadInvalidUTF16(int charAsInt) { throw GetInvalidOperationException(System.SR.Format(System.SR.CannotReadInvalidUTF16, $"0x{charAsInt:X2}")); } [DoesNotReturn] public static void ThrowInvalidOperationException_ReadIncompleteUTF16() { throw GetInvalidOperationException(System.SR.CannotReadIncompleteUTF16); } public static InvalidOperationException GetInvalidOperationException_ReadInvalidUTF8(DecoderFallbackException innerException) { return GetInvalidOperationException(System.SR.CannotTranscodeInvalidUtf8, innerException); } public static ArgumentException GetArgumentException_ReadInvalidUTF16(EncoderFallbackException innerException) { return new ArgumentException(System.SR.CannotTranscodeInvalidUtf16, innerException); } public static InvalidOperationException GetInvalidOperationException(string message, Exception innerException) { InvalidOperationException ex = new InvalidOperationException(message, innerException); ex.Source = "System.Text.Json.Rethrowable"; return ex; } [MethodImpl(MethodImplOptions.NoInlining)] public static InvalidOperationException GetInvalidOperationException(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) { string resourceString = GetResourceString(resource, currentDepth, maxDepth, token, tokenType); InvalidOperationException invalidOperationException = GetInvalidOperationException(resourceString); invalidOperationException.Source = "System.Text.Json.Rethrowable"; return invalidOperationException; } [DoesNotReturn] public static void ThrowOutOfMemoryException(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) { string result = ""; switch (resource) { case ExceptionResource.MismatchedObjectArray: result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWriteEndAfterProperty, (char)token) : System.SR.Format(System.SR.MismatchedObjectArray, (char)token)); break; case ExceptionResource.DepthTooLarge: result = System.SR.Format(System.SR.DepthTooLarge, currentDepth & 0x7FFFFFFF, maxDepth); break; case ExceptionResource.CannotStartObjectArrayWithoutProperty: result = System.SR.Format(System.SR.CannotStartObjectArrayWithoutProperty, tokenType); break; case ExceptionResource.CannotStartObjectArrayAfterPrimitiveOrClose: result = System.SR.Format(System.SR.CannotStartObjectArrayAfterPrimitiveOrClose, tokenType); break; case ExceptionResource.CannotWriteValueWithinObject: result = System.SR.Format(System.SR.CannotWriteValueWithinObject, tokenType); break; case ExceptionResource.CannotWritePropertyWithinArray: result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWritePropertyAfterProperty) : System.SR.Format(System.SR.CannotWritePropertyWithinArray, tokenType)); break; case ExceptionResource.CannotWriteValueAfterPrimitiveOrClose: result = System.SR.Format(System.SR.CannotWriteValueAfterPrimitiveOrClose, tokenType); break; } return result; } [DoesNotReturn] public static void ThrowFormatException() { throw new FormatException { Source = "System.Text.Json.Rethrowable" }; } public static void ThrowFormatException(NumericType numericType) { string message = ""; switch (numericType) { case NumericType.Byte: message = System.SR.FormatByte; break; case NumericType.SByte: message = System.SR.FormatSByte; break; case NumericType.Int16: message = System.SR.FormatInt16; break; case NumericType.Int32: message = System.SR.FormatInt32; break; case NumericType.Int64: message = System.SR.FormatInt64; break; case NumericType.UInt16: message = System.SR.FormatUInt16; break; case NumericType.UInt32: message = System.SR.FormatUInt32; break; case NumericType.UInt64: message = System.SR.FormatUInt64; break; case NumericType.Single: message = System.SR.FormatSingle; break; case NumericType.Double: message = System.SR.FormatDouble; break; case NumericType.Decimal: message = System.SR.FormatDecimal; break; } throw new FormatException(message) { Source = "System.Text.Json.Rethrowable" }; } [DoesNotReturn] public static void ThrowFormatException(DataType dataType) { string message = ""; switch (dataType) { case DataType.Boolean: case DataType.DateOnly: case DataType.DateTime: case DataType.DateTimeOffset: case DataType.TimeOnly: case DataType.TimeSpan: case DataType.Guid: case DataType.Version: message = System.SR.Format(System.SR.UnsupportedFormat, dataType); break; case DataType.Base64String: message = System.SR.CannotDecodeInvalidBase64; break; } throw new FormatException(message) { Source = "System.Text.Json.Rethrowable" }; } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedChar(JsonTokenType tokenType) { throw GetInvalidOperationException("char", tokenType); } [DoesNotReturn] public static void ThrowObjectDisposedException_Utf8JsonWriter() { throw new ObjectDisposedException("Utf8JsonWriter"); } [DoesNotReturn] public static void ThrowObjectDisposedException_JsonDocument() { throw new ObjectDisposedException("JsonDocument"); } [DoesNotReturn] public static void ThrowArgumentException_NodeValueNotAllowed(string paramName) { throw new ArgumentException(System.SR.NodeValueNotAllowed, paramName); } [DoesNotReturn] public static void ThrowArgumentException_DuplicateKey(string paramName, string propertyName) { throw new ArgumentException(System.SR.Format(System.SR.NodeDuplicateKey, propertyName), paramName); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeAlreadyHasParent() { throw new InvalidOperationException(System.SR.NodeAlreadyHasParent); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeCycleDetected() { throw new InvalidOperationException(System.SR.NodeCycleDetected); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeElementCannotBeObjectOrArray() { throw new InvalidOperationException(System.SR.NodeElementCannotBeObjectOrArray); } [DoesNotReturn] public static void ThrowNotSupportedException_CollectionIsReadOnly() { throw GetNotSupportedException_CollectionIsReadOnly(); } public static NotSupportedException GetNotSupportedException_CollectionIsReadOnly() { return new NotSupportedException(System.SR.CollectionIsReadOnly); } [DoesNotReturn] public static void ThrowArgumentException_DeserializeWrongType(Type type, object value) { throw new ArgumentException(System.SR.Format(System.SR.DeserializeWrongType, type, value.GetType())); } [DoesNotReturn] public static void ThrowArgumentException_SerializerDoesNotSupportComments(string paramName) { throw new ArgumentException(System.SR.JsonSerializerDoesNotSupportComments, paramName); } [DoesNotReturn] public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType) { throw new NotSupportedException(System.SR.Format(System.SR.SerializationNotSupportedType, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type propertyType) { throw new NotSupportedException(System.SR.Format(System.SR.TypeRequiresAsyncSerialization, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_ConstructorMaxOf64Parameters(Type type) { throw new NotSupportedException(System.SR.Format(System.SR.ConstructorMaxOf64Parameters, type)); } [DoesNotReturn] public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType, JsonConverter converter) { throw new NotSupportedException(System.SR.Format(System.SR.DictionaryKeyTypeNotSupported, keyType, converter.GetType())); } [DoesNotReturn] public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) { throw new JsonException(System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType) { throw new InvalidCastException(System.SR.Format(System.SR.DeserializeUnableToAssignValue, typeOfValue, declaredType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType) { throw new InvalidOperationException(System.SR.Format(System.SR.DeserializeUnableToAssignNull, declaredType)); } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterRead(JsonConverter converter) { throw new JsonException(System.SR.Format(System.SR.SerializationConverterRead, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterWrite(JsonConverter converter) { throw new JsonException(System.SR.Format(System.SR.SerializationConverterWrite, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializerCycleDetected(int maxDepth) { throw new JsonException(System.SR.Format(System.SR.SerializerCycleDetected, maxDepth)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException(string message = null) { throw new JsonException(message) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowArgumentException_CannotSerializeInvalidType(string paramName, Type typeToConvert, Type declaringType, string propertyName) { if (declaringType == null) { throw new ArgumentException(System.SR.Format(System.SR.CannotSerializeInvalidType, typeToConvert), paramName); } throw new ArgumentException(System.SR.Format(System.SR.CannotSerializeInvalidMember, typeToConvert, propertyName, declaringType), paramName); } [DoesNotReturn] public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type typeToConvert, Type declaringType, MemberInfo memberInfo) { if (declaringType == null) { throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidType, typeToConvert)); } throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidMember, typeToConvert, memberInfo.Name, declaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterNotCompatible, converterType, type)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ResolverTypeNotCompatible(Type requestedType, Type actualType) { throw new InvalidOperationException(System.SR.Format(System.SR.ResolverTypeNotCompatible, actualType, requestedType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ResolverTypeInfoOptionsNotCompatible() { throw new InvalidOperationException(System.SR.ResolverTypeInfoOptionsNotCompatible); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonTypeInfoUsedButTypeInfoResolverNotSet() { throw new InvalidOperationException(System.SR.JsonTypeInfoUsedButTypeInfoResolverNotSet); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo memberInfo) { string text = classType.ToString(); if (memberInfo != null) { text = text + "." + memberInfo.Name; } throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeInvalid, text)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo memberInfo, Type typeToConvert) { string text = classTypeAttributeIsOn.ToString(); if (memberInfo != null) { text = text + "." + memberInfo.Name; } throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeNotCompatible, text, typeToConvert)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerOptionsImmutable(JsonSerializerContext context) { string message = ((context == null) ? System.SR.SerializerOptionsImmutable : System.SR.SerializerContextOptionsImmutable); throw new InvalidOperationException(message); } [DoesNotReturn] public static void ThrowInvalidOperationException_TypeInfoResolverImmutable() { throw new InvalidOperationException(System.SR.TypeInfoResolverImmutable); } [DoesNotReturn] public static void ThrowInvalidOperationException_TypeInfoImmutable() { throw new InvalidOperationException(System.SR.TypeInfoImmutable); } [DoesNotReturn] public static void ThrowInvalidOperationException_PropertyInfoImmutable() { throw new InvalidOperationException(System.SR.PropertyInfoImmutable); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, string propertyName) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameConflict, type, propertyName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameNull(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameNull, jsonPropertyInfo.DeclaringType, jsonPropertyInfo.MemberName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonPropertyRequiredAndNotDeserializable(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.JsonPropertyRequiredAndNotDeserializable, jsonPropertyInfo.Name, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonPropertyRequiredAndExtensionData(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.JsonPropertyRequiredAndExtensionData, jsonPropertyInfo.Name, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowJsonException_JsonRequiredPropertyMissing(JsonTypeInfo parent, BitArray requiredPropertiesSet) { StringBuilder stringBuilder = new StringBuilder(); bool flag = true; for (int i = 0; i < parent.PropertyCache.List.Count; i++) { JsonPropertyInfo value = parent.PropertyCache.List[i].Value; if (value.IsRequired && !requiredPropertiesSet[value.RequiredPropertyIndex]) { if (!flag) { stringBuilder.Append(CultureInfo.CurrentUICulture.TextInfo.ListSeparator); stringBuilder.Append(' '); } stringBuilder.Append(value.Name); flag = false; if (stringBuilder.Length >= 50) { break; } } } throw new JsonException(System.SR.Format(System.SR.JsonRequiredPropertiesMissing, parent.Type, stringBuilder.ToString())); } [DoesNotReturn] public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy) { throw new InvalidOperationException(System.SR.Format(System.SR.NamingPolicyReturnNull, namingPolicy)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerConverterFactoryReturnsNull, converterType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsJsonConverterFactorty(Type converterType) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerConverterFactoryReturnsJsonConverterFactory, converterType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters(Type parentType, string parameterName, string firstMatchName, string secondMatchName) { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleMembersBindWithConstructorParameter, firstMatchName, secondMatchName, parentType, parameterName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType) { throw new InvalidOperationException(System.SR.Format(System.SR.ConstructorParamIncompleteBinding, parentType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(string propertyName, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ExtensionDataCannotBindToCtorParam, propertyName, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(string memberName, Type declaringType) { throw new InvalidOperationException(System.SR.Format(System.SR.JsonIncludeOnNonPublicInvalid, memberName, declaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(string clrPropertyName, Type propertyDeclaringType) { throw new InvalidOperationException(System.SR.Format(System.SR.IgnoreConditionOnValueTypeInvalid, clrPropertyName, propertyDeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.NumberHandlingOnPropertyInvalid, jsonPropertyInfo.MemberName, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(Type runtimePropertyType, JsonConverter jsonConverter) { throw new InvalidOperationException(System.SR.Format(System.SR.ConverterCanConvertMultipleTypes, jsonConverter.GetType(), jsonConverter.TypeToConvert, runtimePropertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(ReadOnlySpan<byte> propertyName, ref Utf8JsonReader reader, scoped ref ReadStack state) { JsonTypeInfo topJsonTypeInfoWithParameterizedConstructor = state.GetTopJsonTypeInfoWithParameterizedConstructor(); state.Current.JsonPropertyName = propertyName.ToArray(); NotSupportedException ex = new NotSupportedException(System.SR.Format(System.SR.ObjectWithParameterizedCtorRefMetadataNotSupported, topJsonTypeInfoWithParameterizedConstructor.Type)); ThrowNotSupportedException(ref state, in reader, ex); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(JsonTypeInfoKind kind) { throw new InvalidOperationException(System.SR.Format(System.SR.InvalidJsonTypeInfoOperationForKind, kind)); } [DoesNotReturn] public static void ThrowInvalidOperationException_CreateObjectConverterNotCompatible(Type type) { throw new InvalidOperationException(System.SR.Format(System.SR.CreateObjectConverterNotCompatible, type)); } [DoesNotReturn] public static void ReThrowWithPath(scoped ref ReadStack state, JsonReaderException ex) { string text = state.JsonPath(); string message = ex.Message; int num = message.LastIndexOf(" LineNumber: ", StringComparison.InvariantCulture); message = ((num < 0) ? (message + " Path: " + text + ".") : (message.Substring(0, num) + " Path: " + text + " |" + message.Substring(num))); throw new JsonException(message, text, ex.LineNumber, ex.BytePositionInLine, ex); } [DoesNotReturn] public static void ReThrowWithPath(scoped ref ReadStack state, in Utf8JsonReader reader, Exception ex) { JsonException ex2 = new JsonException(null, ex); AddJsonExceptionInformation(ref state, in reader, ex2); throw ex2; } public static void AddJsonExceptionInformation(scoped ref ReadStack state, in Utf8JsonReader reader, JsonException ex) { long lineNumber = reader.CurrentState._lineNumber; ex.LineNumber = lineNumber; long bytePositionInLine = reader.CurrentState._bytePositionInLine; ex.BytePositionInLine = bytePositionInLine; string arg = (ex.Path = state.JsonPath()); string text2 = ex._message; if (string.IsNullOrEmpty(text2)) { Type p = state.Current.JsonPropertyInfo?.PropertyType ?? state.Current.JsonTypeInfo.Type; text2 = System.SR.Format(System.SR.DeserializeUnableToConvertValue, p); ex.AppendPathInformation = true; } if (ex.AppendPathInformation) { text2 += $" Path: {arg} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; ex.SetMessage(text2); } } [DoesNotReturn] public static void ReThrowWithPath(ref WriteStack state, Exception ex) { JsonException ex2 = new JsonException(null, ex); AddJsonExceptionInformation(ref state, ex2); throw ex2; } public static void AddJsonExceptionInformation(ref WriteStack state, JsonException ex) { string text2 = (ex.Path = state.PropertyPath()); string text3 = ex._message; if (string.IsNullOrEmpty(text3)) { text3 = System.SR.Format(System.SR.SerializeUnableToSerialize); ex.AppendPathInformation = true; } if (ex.AppendPathInformation) { text3 = text3 + " Path: " + text2 + "."; ex.SetMessage(text3); } } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateAttribute(Type attribute, MemberInfo memberInfo) { string p = ((memberInfo is Type type) ? type.ToString() : $"{memberInfo.DeclaringType}.{memberInfo.Name}"); throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateAttribute, attribute, p)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType, Type attribute) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateTypeAttribute, classType, attribute)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute<TAttribute>(Type classType) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateTypeAttribute, classType, typeof(TAttribute))); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDataExtensionPropertyInvalid, jsonPropertyInfo.PropertyType, jsonPropertyInfo.MemberName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeJsonObjectCustomConverterNotAllowedOnExtensionPropert
plugins/System.Threading.Channels.dll
Decompiled 2 years agousing System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using FxResources.System.Threading.Channels; using Internal; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Threading.Channels")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides types for passing data between producers and consumers.\r\n\r\nCommonly Used Types:\r\nSystem.Threading.Channel\r\nSystem.Threading.Channel<T>")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Threading.Channels")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Threading.Channels { internal static class SR { } } namespace Internal { internal static class PaddingHelpers { internal const int CACHE_LINE_SIZE = 128; } [StructLayout(LayoutKind.Explicit, Size = 124)] internal struct PaddingFor32 { } } namespace System { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct VoidResult { } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ChannelClosedException_DefaultMessage => GetResourceString("ChannelClosedException_DefaultMessage"); internal static string InvalidOperation_IncompleteAsyncOperation => GetResourceString("InvalidOperation_IncompleteAsyncOperation"); internal static string InvalidOperation_MultipleContinuations => GetResourceString("InvalidOperation_MultipleContinuations"); internal static string InvalidOperation_IncorrectToken => GetResourceString("InvalidOperation_IncorrectToken"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.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.Collections.Generic { [DebuggerDisplay("Count = {_size}")] internal sealed class Deque<T> { private T[] _array = Array.Empty<T>(); private int _head; private int _tail; private int _size; public int Count => _size; public bool IsEmpty => _size == 0; public void EnqueueTail(T item) { if (_size == _array.Length) { Grow(); } _array[_tail] = item; if (++_tail == _array.Length) { _tail = 0; } _size++; } public T DequeueHead() { T result = _array[_head]; _array[_head] = default(T); if (++_head == _array.Length) { _head = 0; } _size--; return result; } public T PeekHead() { return _array[_head]; } public T PeekTail() { int num = _tail - 1; if (num == -1) { num = _array.Length - 1; } return _array[num]; } public T DequeueTail() { if (--_tail == -1) { _tail = _array.Length - 1; } T result = _array[_tail]; _array[_tail] = default(T); _size--; return result; } public IEnumerator<T> GetEnumerator() { int pos = _head; int count = _size; while (count-- > 0) { yield return _array[pos]; pos = (pos + 1) % _array.Length; } } private void Grow() { int num = (int)((long)_array.Length * 2L); if (num < _array.Length + 4) { num = _array.Length + 4; } T[] array = new T[num]; if (_head == 0) { Array.Copy(_array, array, _size); } else { Array.Copy(_array, _head, array, 0, _array.Length - _head); Array.Copy(_array, 0, array, _array.Length - _head, _tail); } _array = array; _head = 0; _tail = _size; } } } namespace System.Collections.Concurrent { [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))] internal sealed class SingleProducerSingleConsumerQueue<T> : IEnumerable<T>, IEnumerable { [StructLayout(LayoutKind.Sequential)] private sealed class Segment { internal Segment _next; internal readonly T[] _array; internal SegmentState _state; internal Segment(int size) { _array = new T[size]; } } private struct SegmentState { internal Internal.PaddingFor32 _pad0; internal volatile int _first; internal int _lastCopy; internal Internal.PaddingFor32 _pad1; internal int _firstCopy; internal volatile int _last; internal Internal.PaddingFor32 _pad2; } private sealed class SingleProducerSingleConsumerQueue_DebugView { private readonly SingleProducerSingleConsumerQueue<T> _queue; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => new List<T>(_queue).ToArray(); public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue) { _queue = queue; } } private const int InitialSegmentSize = 32; private const int MaxSegmentSize = 16777216; private volatile Segment _head; private volatile Segment _tail; public bool IsEmpty { get { Segment head = _head; if (head._state._first != head._state._lastCopy) { return false; } if (head._state._first != head._state._last) { return false; } return head._next == null; } } internal int Count { get { int num = 0; for (Segment segment = _head; segment != null; segment = segment._next) { int num2 = segment._array.Length; int first; int last; do { first = segment._state._first; last = segment._state._last; } while (first != segment._state._first); num += (last - first) & (num2 - 1); } return num; } } public SingleProducerSingleConsumerQueue() { _head = (_tail = new Segment(32)); } public void Enqueue(T item) { Segment segment = _tail; T[] array = segment._array; int last = segment._state._last; int num = (last + 1) & (array.Length - 1); if (num != segment._state._firstCopy) { array[last] = item; segment._state._last = num; } else { EnqueueSlow(item, ref segment); } } private void EnqueueSlow(T item, ref Segment segment) { if (segment._state._firstCopy != segment._state._first) { segment._state._firstCopy = segment._state._first; Enqueue(item); return; } int num = _tail._array.Length << 1; if (num > 16777216) { num = 16777216; } Segment segment2 = new Segment(num); segment2._array[0] = item; segment2._state._last = 1; segment2._state._lastCopy = 1; try { } finally { Volatile.Write(ref _tail._next, segment2); _tail = segment2; } } public bool TryDequeue([MaybeNullWhen(false)] out T result) { Segment head = _head; T[] array = head._array; int first = head._state._first; if (first != head._state._lastCopy) { result = array[first]; array[first] = default(T); head._state._first = (first + 1) & (array.Length - 1); return true; } return TryDequeueSlow(head, array, peek: false, out result); } public bool TryPeek([MaybeNullWhen(false)] out T result) { Segment head = _head; T[] array = head._array; int first = head._state._first; if (first != head._state._lastCopy) { result = array[first]; return true; } return TryDequeueSlow(head, array, peek: true, out result); } private bool TryDequeueSlow(Segment segment, T[] array, bool peek, [MaybeNullWhen(false)] out T result) { if (segment._state._last != segment._state._lastCopy) { segment._state._lastCopy = segment._state._last; if (!peek) { return TryDequeue(out result); } return TryPeek(out result); } if (segment._next != null && segment._state._first == segment._state._last) { segment = segment._next; array = segment._array; _head = segment; } int first = segment._state._first; if (first == segment._state._last) { result = default(T); return false; } result = array[first]; if (!peek) { array[first] = default(T); segment._state._first = (first + 1) & (segment._array.Length - 1); segment._state._lastCopy = segment._state._last; } return true; } public IEnumerator<T> GetEnumerator() { for (Segment segment = _head; segment != null; segment = segment._next) { for (int pt = segment._state._first; pt != segment._state._last; pt = (pt + 1) & (segment._array.Length - 1)) { yield return segment._array[pt]; } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } namespace System.Threading.Channels { internal abstract class AsyncOperation { protected static readonly Action<object> s_availableSentinel = AvailableSentinel; protected static readonly Action<object> s_completedSentinel = CompletedSentinel; private static void AvailableSentinel(object s) { } private static void CompletedSentinel(object s) { } protected static void ThrowIncompleteOperationException() { throw new InvalidOperationException(System.SR.InvalidOperation_IncompleteAsyncOperation); } protected static void ThrowMultipleContinuations() { throw new InvalidOperationException(System.SR.InvalidOperation_MultipleContinuations); } protected static void ThrowIncorrectCurrentIdException() { throw new InvalidOperationException(System.SR.InvalidOperation_IncorrectToken); } } internal class AsyncOperation<TResult> : AsyncOperation, IValueTaskSource, IValueTaskSource<TResult> { private readonly CancellationTokenRegistration _registration; private readonly bool _pooled; private readonly bool _runContinuationsAsynchronously; private volatile int _completionReserved; private TResult _result; private ExceptionDispatchInfo _error; private Action<object> _continuation; private object _continuationState; private object _schedulingContext; private ExecutionContext _executionContext; private short _currentId; public AsyncOperation<TResult> Next { get; set; } public CancellationToken CancellationToken { get; } public ValueTask ValueTask => new ValueTask(this, _currentId); public ValueTask<TResult> ValueTaskOfT => new ValueTask<TResult>(this, _currentId); internal bool IsCompleted => (object)_continuation == AsyncOperation.s_completedSentinel; public AsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false) { _continuation = (pooled ? AsyncOperation.s_availableSentinel : null); _pooled = pooled; _runContinuationsAsynchronously = runContinuationsAsynchronously; if (cancellationToken.CanBeCanceled) { CancellationToken = cancellationToken; _registration = UnsafeRegister(cancellationToken, delegate(object s) { AsyncOperation<TResult> asyncOperation = (AsyncOperation<TResult>)s; asyncOperation.TrySetCanceled(asyncOperation.CancellationToken); }, this); } } public ValueTaskSourceStatus GetStatus(short token) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (IsCompleted) { if (_error != null) { if (!(_error.SourceException is OperationCanceledException)) { return ValueTaskSourceStatus.Faulted; } return ValueTaskSourceStatus.Canceled; } return ValueTaskSourceStatus.Succeeded; } return ValueTaskSourceStatus.Pending; } public TResult GetResult(short token) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (!IsCompleted) { AsyncOperation.ThrowIncompleteOperationException(); } ExceptionDispatchInfo error = _error; TResult result = _result; _currentId++; if (_pooled) { Volatile.Write(ref _continuation, AsyncOperation.s_availableSentinel); } error?.Throw(); return result; } void IValueTaskSource.GetResult(short token) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (!IsCompleted) { AsyncOperation.ThrowIncompleteOperationException(); } ExceptionDispatchInfo error = _error; _currentId++; if (_pooled) { Volatile.Write(ref _continuation, AsyncOperation.s_availableSentinel); } error?.Throw(); } public bool TryOwnAndReset() { if ((object)Interlocked.CompareExchange(ref _continuation, null, AsyncOperation.s_availableSentinel) == AsyncOperation.s_availableSentinel) { _continuationState = null; _result = default(TResult); _error = null; _schedulingContext = null; _executionContext = null; return true; } return false; } public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (_continuationState != null) { AsyncOperation.ThrowMultipleContinuations(); } _continuationState = state; if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) { _executionContext = ExecutionContext.Capture(); } SynchronizationContext synchronizationContext = null; TaskScheduler taskScheduler = null; if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { synchronizationContext = SynchronizationContext.Current; if (synchronizationContext != null && synchronizationContext.GetType() != typeof(SynchronizationContext)) { _schedulingContext = synchronizationContext; } else { synchronizationContext = null; taskScheduler = TaskScheduler.Current; if (taskScheduler != TaskScheduler.Default) { _schedulingContext = taskScheduler; } } } Action<object> action = Interlocked.CompareExchange(ref _continuation, continuation, null); if (action == null) { return; } if ((object)action != AsyncOperation.s_completedSentinel) { AsyncOperation.ThrowMultipleContinuations(); } if (_schedulingContext == null) { if (_executionContext == null) { UnsafeQueueUserWorkItem(continuation, state); } else { QueueUserWorkItem(continuation, state); } } else if (synchronizationContext != null) { synchronizationContext.Post(delegate(object s) { KeyValuePair<Action<object>, object> keyValuePair = (KeyValuePair<Action<object>, object>)s; keyValuePair.Key(keyValuePair.Value); }, new KeyValuePair<Action<object>, object>(continuation, state)); } else { Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, taskScheduler); } } public bool UnregisterCancellation() { if (CancellationToken.CanBeCanceled) { CancellationTokenRegistration registration = _registration; registration.Dispose(); return _completionReserved == 0; } return true; } public bool TrySetResult(TResult item) { UnregisterCancellation(); if (TryReserveCompletionIfCancelable()) { _result = item; SignalCompletion(); return true; } return false; } public bool TrySetException(Exception exception) { UnregisterCancellation(); if (TryReserveCompletionIfCancelable()) { _error = ExceptionDispatchInfo.Capture(exception); SignalCompletion(); return true; } return false; } public bool TrySetCanceled(CancellationToken cancellationToken = default(CancellationToken)) { if (TryReserveCompletionIfCancelable()) { _error = ExceptionDispatchInfo.Capture(new OperationCanceledException(cancellationToken)); SignalCompletion(); return true; } return false; } private bool TryReserveCompletionIfCancelable() { if (CancellationToken.CanBeCanceled) { return Interlocked.CompareExchange(ref _completionReserved, 1, 0) == 0; } return true; } private void SignalCompletion() { if (_continuation == null && Interlocked.CompareExchange(ref _continuation, AsyncOperation.s_completedSentinel, null) == null) { return; } if (_schedulingContext == null) { if (_runContinuationsAsynchronously) { UnsafeQueueSetCompletionAndInvokeContinuation(); return; } } else if (_schedulingContext is SynchronizationContext synchronizationContext) { if (_runContinuationsAsynchronously || synchronizationContext != SynchronizationContext.Current) { synchronizationContext.Post(delegate(object s) { ((AsyncOperation<TResult>)s).SetCompletionAndInvokeContinuation(); }, this); return; } } else { TaskScheduler taskScheduler = (TaskScheduler)_schedulingContext; if (_runContinuationsAsynchronously || taskScheduler != TaskScheduler.Current) { Task.Factory.StartNew(delegate(object s) { ((AsyncOperation<TResult>)s).SetCompletionAndInvokeContinuation(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, taskScheduler); return; } } SetCompletionAndInvokeContinuation(); } private void SetCompletionAndInvokeContinuation() { if (_executionContext == null) { Action<object> continuation = _continuation; _continuation = AsyncOperation.s_completedSentinel; continuation(_continuationState); return; } ExecutionContext.Run(_executionContext, delegate(object s) { AsyncOperation<TResult> asyncOperation = (AsyncOperation<TResult>)s; Action<object> continuation2 = asyncOperation._continuation; asyncOperation._continuation = AsyncOperation.s_completedSentinel; continuation2(asyncOperation._continuationState); }, this); } private void UnsafeQueueSetCompletionAndInvokeContinuation() { ThreadPool.UnsafeQueueUserWorkItem(delegate(object s) { ((AsyncOperation<TResult>)s).SetCompletionAndInvokeContinuation(); }, this); } private static void UnsafeQueueUserWorkItem(Action<object> action, object state) { QueueUserWorkItem(action, state); } private static void QueueUserWorkItem(Action<object> action, object state) { Task.Factory.StartNew(action, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } private static CancellationTokenRegistration UnsafeRegister(CancellationToken cancellationToken, Action<object> action, object state) { return cancellationToken.Register(action, state); } } internal sealed class VoidAsyncOperationWithData<TData> : AsyncOperation<VoidResult> { public TData Item { get; set; } public VoidAsyncOperationWithData(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false) : base(runContinuationsAsynchronously, cancellationToken, pooled) { } } [DebuggerDisplay("Items={ItemsCountForDebugger}, Capacity={_bufferedCapacity}, Mode={_mode}, Closed={ChannelIsClosedForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] internal sealed class BoundedChannel<T> : Channel<T>, IDebugEnumerable<T> { [DebuggerDisplay("Items={ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class BoundedChannelReader : ChannelReader<T>, IDebugEnumerable<T> { internal readonly BoundedChannel<T> _parent; private readonly AsyncOperation<T> _readerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; public override Task Completion => _parent._completion.Task; public override bool CanCount => true; public override bool CanPeek => true; public override int Count { get { BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { return parent._items.Count; } } } private int ItemsCountForDebugger => _parent._items.Count; internal BoundedChannelReader(BoundedChannel<T> parent) { _parent = parent; _readerSingleton = new AsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); } public override bool TryRead([MaybeNullWhen(false)] out T item) { BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { item = DequeueItemAndPostProcess(); return true; } } item = default(T); return false; } public override bool TryPeek([MaybeNullWhen(false)] out T item) { BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { item = parent._items.PeekHead(); return true; } } item = default(T); return false; } public override ValueTask<T> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<T>(DequeueItemAndPostProcess()); } if (parent._doneWriting != null) { return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<T> readerSingleton = _readerSingleton; if (readerSingleton.TryOwnAndReset()) { parent._blockedReaders.EnqueueTail(readerSingleton); return readerSingleton.ValueTaskOfT; } } AsyncOperation<T> asyncOperation = new AsyncOperation<T>(parent._runContinuationsAsynchronously | cancellationToken.CanBeCanceled, cancellationToken); parent._blockedReaders.EnqueueTail(asyncOperation); return asyncOperation.ValueTaskOfT; } } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<bool> waiterSingleton = _waiterSingleton; if (waiterSingleton.TryOwnAndReset()) { ChannelUtilities.QueueWaiter(ref parent._waitingReadersTail, waiterSingleton); return waiterSingleton.ValueTaskOfT; } } AsyncOperation<bool> asyncOperation = new AsyncOperation<bool>(parent._runContinuationsAsynchronously | cancellationToken.CanBeCanceled, cancellationToken); ChannelUtilities.QueueWaiter(ref _parent._waitingReadersTail, asyncOperation); return asyncOperation.ValueTaskOfT; } } private T DequeueItemAndPostProcess() { BoundedChannel<T> parent = _parent; T result = parent._items.DequeueHead(); if (parent._doneWriting != null) { if (parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } } else { while (!parent._blockedWriters.IsEmpty) { VoidAsyncOperationWithData<T> voidAsyncOperationWithData = parent._blockedWriters.DequeueHead(); if (voidAsyncOperationWithData.TrySetResult(default(VoidResult))) { parent._items.EnqueueTail(voidAsyncOperationWithData.Item); return result; } } ChannelUtilities.WakeUpWaiters(ref parent._waitingWritersTail, result: true); } return result; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } [DebuggerDisplay("Items={ItemsCountForDebugger}, Capacity={CapacityForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class BoundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T> { internal readonly BoundedChannel<T> _parent; private readonly VoidAsyncOperationWithData<T> _writerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; private int ItemsCountForDebugger => _parent._items.Count; private int CapacityForDebugger => _parent._bufferedCapacity; internal BoundedChannelWriter(BoundedChannel<T> parent) { _parent = parent; _writerSingleton = new VoidAsyncOperationWithData<T>(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true); } public override bool TryComplete(Exception error) { BoundedChannel<T> parent = _parent; bool isEmpty; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel; isEmpty = parent._items.IsEmpty; } if (isEmpty) { ChannelUtilities.Complete(parent._completion, error); } ChannelUtilities.FailOperations<AsyncOperation<T>, T>(parent._blockedReaders, ChannelUtilities.CreateInvalidCompletionException(error)); ChannelUtilities.FailOperations<VoidAsyncOperationWithData<T>, VoidResult>(parent._blockedWriters, ChannelUtilities.CreateInvalidCompletionException(error)); ChannelUtilities.WakeUpWaiters(ref parent._waitingReadersTail, result: false, error); ChannelUtilities.WakeUpWaiters(ref parent._waitingWritersTail, result: false, error); return true; } public override bool TryWrite(T item) { AsyncOperation<T> asyncOperation = null; AsyncOperation<bool> listTail = null; BoundedChannel<T> parent = _parent; bool lockTaken = false; try { Monitor.Enter(parent.SyncObj, ref lockTaken); if (parent._doneWriting != null) { return false; } int count = parent._items.Count; if (count != 0) { if (count < parent._bufferedCapacity) { parent._items.EnqueueTail(item); return true; } if (parent._mode == BoundedChannelFullMode.Wait) { return false; } if (parent._mode == BoundedChannelFullMode.DropWrite) { Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(item); return true; } T obj = ((parent._mode == BoundedChannelFullMode.DropNewest) ? parent._items.DequeueTail() : parent._items.DequeueHead()); parent._items.EnqueueTail(item); Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(obj); return true; } while (!parent._blockedReaders.IsEmpty) { AsyncOperation<T> asyncOperation2 = parent._blockedReaders.DequeueHead(); if (asyncOperation2.UnregisterCancellation()) { asyncOperation = asyncOperation2; break; } } if (asyncOperation == null) { parent._items.EnqueueTail(item); listTail = parent._waitingReadersTail; if (listTail == null) { return true; } parent._waitingReadersTail = null; } } finally { if (lockTaken) { Monitor.Exit(parent.SyncObj); } } if (asyncOperation != null) { bool flag = asyncOperation.TrySetResult(item); } else { ChannelUtilities.WakeUpWaiters(ref listTail, result: true); } return true; } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } if (parent._items.Count < parent._bufferedCapacity || parent._mode != 0) { return new ValueTask<bool>(result: true); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<bool> waiterSingleton = _waiterSingleton; if (waiterSingleton.TryOwnAndReset()) { ChannelUtilities.QueueWaiter(ref parent._waitingWritersTail, waiterSingleton); return waiterSingleton.ValueTaskOfT; } } AsyncOperation<bool> asyncOperation = new AsyncOperation<bool>(runContinuationsAsynchronously: true, cancellationToken); ChannelUtilities.QueueWaiter(ref parent._waitingWritersTail, asyncOperation); return asyncOperation.ValueTaskOfT; } } public override ValueTask WriteAsync(T item, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask(Task.FromCanceled(cancellationToken)); } AsyncOperation<T> asyncOperation = null; AsyncOperation<bool> listTail = null; BoundedChannel<T> parent = _parent; bool lockTaken = false; try { Monitor.Enter(parent.SyncObj, ref lockTaken); if (parent._doneWriting != null) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(parent._doneWriting))); } int count = parent._items.Count; if (count != 0) { if (count < parent._bufferedCapacity) { parent._items.EnqueueTail(item); return default(ValueTask); } if (parent._mode == BoundedChannelFullMode.Wait) { if (!cancellationToken.CanBeCanceled) { VoidAsyncOperationWithData<T> writerSingleton = _writerSingleton; if (writerSingleton.TryOwnAndReset()) { writerSingleton.Item = item; parent._blockedWriters.EnqueueTail(writerSingleton); return writerSingleton.ValueTask; } } VoidAsyncOperationWithData<T> voidAsyncOperationWithData = new VoidAsyncOperationWithData<T>(runContinuationsAsynchronously: true, cancellationToken); voidAsyncOperationWithData.Item = item; parent._blockedWriters.EnqueueTail(voidAsyncOperationWithData); return voidAsyncOperationWithData.ValueTask; } if (parent._mode == BoundedChannelFullMode.DropWrite) { Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(item); return default(ValueTask); } T obj = ((parent._mode == BoundedChannelFullMode.DropNewest) ? parent._items.DequeueTail() : parent._items.DequeueHead()); parent._items.EnqueueTail(item); Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(obj); return default(ValueTask); } while (!parent._blockedReaders.IsEmpty) { AsyncOperation<T> asyncOperation2 = parent._blockedReaders.DequeueHead(); if (asyncOperation2.UnregisterCancellation()) { asyncOperation = asyncOperation2; break; } } if (asyncOperation == null) { parent._items.EnqueueTail(item); listTail = parent._waitingReadersTail; if (listTail == null) { return default(ValueTask); } parent._waitingReadersTail = null; } } finally { if (lockTaken) { Monitor.Exit(parent.SyncObj); } } if (asyncOperation != null) { bool flag = asyncOperation.TrySetResult(item); } else { ChannelUtilities.WakeUpWaiters(ref listTail, result: true); } return default(ValueTask); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } private readonly BoundedChannelFullMode _mode; private readonly Action<T> _itemDropped; private readonly TaskCompletionSource _completion; private readonly int _bufferedCapacity; private readonly Deque<T> _items = new Deque<T>(); private readonly Deque<AsyncOperation<T>> _blockedReaders = new Deque<AsyncOperation<T>>(); private readonly Deque<VoidAsyncOperationWithData<T>> _blockedWriters = new Deque<VoidAsyncOperationWithData<T>>(); private AsyncOperation<bool> _waitingReadersTail; private AsyncOperation<bool> _waitingWritersTail; private readonly bool _runContinuationsAsynchronously; private Exception _doneWriting; private object SyncObj => _items; private int ItemsCountForDebugger => _items.Count; private bool ChannelIsClosedForDebugger => _doneWriting != null; internal BoundedChannel(int bufferedCapacity, BoundedChannelFullMode mode, bool runContinuationsAsynchronously, Action<T> itemDropped) { _bufferedCapacity = bufferedCapacity; _mode = mode; _runContinuationsAsynchronously = runContinuationsAsynchronously; _itemDropped = itemDropped; _completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); base.Reader = new BoundedChannelReader(this); base.Writer = new BoundedChannelWriter(this); } [Conditional("DEBUG")] private void AssertInvariants() { _ = _items.IsEmpty; _ = _items.Count; _ = _bufferedCapacity; _ = _blockedReaders.IsEmpty; _ = _blockedWriters.IsEmpty; _ = _completion.Task.IsCompleted; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _items.GetEnumerator(); } } public enum BoundedChannelFullMode { Wait, DropNewest, DropOldest, DropWrite } public static class Channel { public static Channel<T> CreateUnbounded<T>() { return new UnboundedChannel<T>(runContinuationsAsynchronously: true); } public static Channel<T> CreateUnbounded<T>(UnboundedChannelOptions options) { if (options == null) { throw new ArgumentNullException("options"); } if (options.SingleReader) { return new SingleConsumerUnboundedChannel<T>(!options.AllowSynchronousContinuations); } return new UnboundedChannel<T>(!options.AllowSynchronousContinuations); } public static Channel<T> CreateBounded<T>(int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity"); } return new BoundedChannel<T>(capacity, BoundedChannelFullMode.Wait, runContinuationsAsynchronously: true, null); } public static Channel<T> CreateBounded<T>(BoundedChannelOptions options) { return CreateBounded<T>(options, null); } public static Channel<T> CreateBounded<T>(BoundedChannelOptions options, Action<T>? itemDropped) { if (options == null) { throw new ArgumentNullException("options"); } return new BoundedChannel<T>(options.Capacity, options.FullMode, !options.AllowSynchronousContinuations, itemDropped); } } public class ChannelClosedException : InvalidOperationException { public ChannelClosedException() : base(System.SR.ChannelClosedException_DefaultMessage) { } public ChannelClosedException(string? message) : base(message) { } public ChannelClosedException(Exception? innerException) : base(System.SR.ChannelClosedException_DefaultMessage, innerException) { } public ChannelClosedException(string? message, Exception? innerException) : base(message, innerException) { } } public abstract class ChannelOptions { public bool SingleWriter { get; set; } public bool SingleReader { get; set; } public bool AllowSynchronousContinuations { get; set; } } public sealed class BoundedChannelOptions : ChannelOptions { private int _capacity; private BoundedChannelFullMode _mode; public int Capacity { get { return _capacity; } set { if (value < 1) { throw new ArgumentOutOfRangeException("value"); } _capacity = value; } } public BoundedChannelFullMode FullMode { get { return _mode; } set { if ((uint)value <= 3u) { _mode = value; return; } throw new ArgumentOutOfRangeException("value"); } } public BoundedChannelOptions(int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity"); } _capacity = capacity; } } public sealed class UnboundedChannelOptions : ChannelOptions { } public abstract class ChannelReader<T> { public virtual Task Completion => ChannelUtilities.s_neverCompletingTask; public virtual bool CanCount => false; public virtual bool CanPeek => false; public virtual int Count { get { throw new NotSupportedException(); } } public abstract bool TryRead([MaybeNullWhen(false)] out T item); public virtual bool TryPeek([MaybeNullWhen(false)] out T item) { item = default(T); return false; } public abstract ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default(CancellationToken)); public virtual ValueTask<T> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } try { if (TryRead(out var item)) { return new ValueTask<T>(item); } } catch (Exception ex) when (!(ex is ChannelClosedException) && !(ex is OperationCanceledException)) { return new ValueTask<T>(Task.FromException<T>(ex)); } return ReadAsyncCore(cancellationToken); async ValueTask<T> ReadAsyncCore(CancellationToken ct) { T item2; do { if (!(await WaitToReadAsync(ct).ConfigureAwait(continueOnCapturedContext: false))) { throw new ChannelClosedException(); } } while (!TryRead(out item2)); return item2; } } } internal static class ChannelUtilities { internal static readonly Exception s_doneWritingSentinel = new Exception("s_doneWritingSentinel"); internal static readonly Task<bool> s_trueTask = Task.FromResult(result: true); internal static readonly Task<bool> s_falseTask = Task.FromResult(result: false); internal static readonly Task s_neverCompletingTask = new TaskCompletionSource<bool>().Task; internal static void Complete(TaskCompletionSource tcs, Exception error = null) { if (error is OperationCanceledException ex) { tcs.TrySetCanceled(ex.CancellationToken); } else if (error != null && error != s_doneWritingSentinel) { tcs.TrySetException(error); } else { tcs.TrySetResult(); } } internal static ValueTask<T> GetInvalidCompletionValueTask<T>(Exception error) { Task<T> task = ((error == s_doneWritingSentinel) ? Task.FromException<T>(CreateInvalidCompletionException()) : ((error is OperationCanceledException ex) ? Task.FromCanceled<T>(ex.CancellationToken.IsCancellationRequested ? ex.CancellationToken : new CancellationToken(canceled: true)) : Task.FromException<T>(CreateInvalidCompletionException(error)))); return new ValueTask<T>(task); } internal static void QueueWaiter(ref AsyncOperation<bool> tail, AsyncOperation<bool> waiter) { AsyncOperation<bool> asyncOperation = tail; if (asyncOperation == null) { waiter.Next = waiter; } else { waiter.Next = asyncOperation.Next; asyncOperation.Next = waiter; } tail = waiter; } internal static void WakeUpWaiters(ref AsyncOperation<bool> listTail, bool result, Exception error = null) { AsyncOperation<bool> asyncOperation = listTail; if (asyncOperation != null) { listTail = null; AsyncOperation<bool> next = asyncOperation.Next; AsyncOperation<bool> asyncOperation2 = next; do { AsyncOperation<bool> next2 = asyncOperation2.Next; asyncOperation2.Next = null; bool flag = ((error != null) ? asyncOperation2.TrySetException(error) : asyncOperation2.TrySetResult(result)); asyncOperation2 = next2; } while (asyncOperation2 != next); } } internal static void FailOperations<T, TInner>(Deque<T> operations, Exception error) where T : AsyncOperation<TInner> { while (!operations.IsEmpty) { operations.DequeueHead().TrySetException(error); } } internal static Exception CreateInvalidCompletionException(Exception inner = null) { if (!(inner is OperationCanceledException)) { if (inner == null || inner == s_doneWritingSentinel) { return new ChannelClosedException(); } return new ChannelClosedException(inner); } return inner; } } public abstract class ChannelWriter<T> { public virtual bool TryComplete(Exception? error = null) { return false; } public abstract bool TryWrite(T item); public abstract ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken = default(CancellationToken)); public virtual ValueTask WriteAsync(T item, CancellationToken cancellationToken = default(CancellationToken)) { try { return cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled<T>(cancellationToken)) : (TryWrite(item) ? default(ValueTask) : WriteAsyncCore(item, cancellationToken)); } catch (Exception exception) { return new ValueTask(Task.FromException(exception)); } } private async ValueTask WriteAsyncCore(T innerItem, CancellationToken ct) { while (await WaitToWriteAsync(ct).ConfigureAwait(continueOnCapturedContext: false)) { if (TryWrite(innerItem)) { return; } } throw ChannelUtilities.CreateInvalidCompletionException(); } public void Complete(Exception? error = null) { if (!TryComplete(error)) { throw ChannelUtilities.CreateInvalidCompletionException(); } } } public abstract class Channel<T> : Channel<T, T> { } public abstract class Channel<TWrite, TRead> { public ChannelReader<TRead> Reader { get; protected set; } public ChannelWriter<TWrite> Writer { get; protected set; } public static implicit operator ChannelReader<TRead>(Channel<TWrite, TRead> channel) { return channel.Reader; } public static implicit operator ChannelWriter<TWrite>(Channel<TWrite, TRead> channel) { return channel.Writer; } } internal interface IDebugEnumerable<T> { IEnumerator<T> GetEnumerator(); } internal sealed class DebugEnumeratorDebugView<T> { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get; } public DebugEnumeratorDebugView(IDebugEnumerable<T> enumerable) { List<T> list = new List<T>(); foreach (T item in enumerable) { list.Add(item); } Items = list.ToArray(); } } [DebuggerDisplay("Items={ItemsCountForDebugger}, Closed={ChannelIsClosedForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] internal sealed class SingleConsumerUnboundedChannel<T> : Channel<T>, IDebugEnumerable<T> { [DebuggerDisplay("Items={ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelReader : ChannelReader<T>, IDebugEnumerable<T> { internal readonly SingleConsumerUnboundedChannel<T> _parent; private readonly AsyncOperation<T> _readerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; public override Task Completion => _parent._completion.Task; public override bool CanPeek => true; private int ItemsCountForDebugger => _parent._items.Count; internal UnboundedChannelReader(SingleConsumerUnboundedChannel<T> parent) { _parent = parent; _readerSingleton = new AsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); } public override ValueTask<T> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } if (TryRead(out var item)) { return new ValueTask<T>(item); } SingleConsumerUnboundedChannel<T> parent = _parent; AsyncOperation<T> asyncOperation; AsyncOperation<T> asyncOperation2; lock (parent.SyncObj) { if (TryRead(out item)) { return new ValueTask<T>(item); } if (parent._doneWriting != null) { return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting); } asyncOperation = parent._blockedReader; if (!cancellationToken.CanBeCanceled && _readerSingleton.TryOwnAndReset()) { asyncOperation2 = _readerSingleton; if (asyncOperation2 == asyncOperation) { asyncOperation = null; } } else { asyncOperation2 = new AsyncOperation<T>(_parent._runContinuationsAsynchronously, cancellationToken); } parent._blockedReader = asyncOperation2; } asyncOperation?.TrySetCanceled(); return asyncOperation2.ValueTaskOfT; } public override bool TryRead([MaybeNullWhen(false)] out T item) { SingleConsumerUnboundedChannel<T> parent = _parent; if (parent._items.TryDequeue(out item)) { if (parent._doneWriting != null && parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } return true; } return false; } public override bool TryPeek([MaybeNullWhen(false)] out T item) { return _parent._items.TryPeek(out item); } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } if (!_parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } SingleConsumerUnboundedChannel<T> parent = _parent; AsyncOperation<bool> asyncOperation = null; AsyncOperation<bool> asyncOperation2; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } asyncOperation = parent._waitingReader; if (!cancellationToken.CanBeCanceled && _waiterSingleton.TryOwnAndReset()) { asyncOperation2 = _waiterSingleton; if (asyncOperation2 == asyncOperation) { asyncOperation = null; } } else { asyncOperation2 = new AsyncOperation<bool>(_parent._runContinuationsAsynchronously, cancellationToken); } parent._waitingReader = asyncOperation2; } asyncOperation?.TrySetCanceled(); return asyncOperation2.ValueTaskOfT; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } [DebuggerDisplay("Items={ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T> { internal readonly SingleConsumerUnboundedChannel<T> _parent; private int ItemsCountForDebugger => _parent._items.Count; internal UnboundedChannelWriter(SingleConsumerUnboundedChannel<T> parent) { _parent = parent; } public override bool TryComplete(Exception error) { AsyncOperation<T> asyncOperation = null; AsyncOperation<bool> asyncOperation2 = null; bool flag = false; SingleConsumerUnboundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel; if (parent._items.IsEmpty) { flag = true; if (parent._blockedReader != null) { asyncOperation = parent._blockedReader; parent._blockedReader = null; } if (parent._waitingReader != null) { asyncOperation2 = parent._waitingReader; parent._waitingReader = null; } } } if (flag) { ChannelUtilities.Complete(parent._completion, error); } if (asyncOperation != null) { error = ChannelUtilities.CreateInvalidCompletionException(error); asyncOperation.TrySetException(error); } if (asyncOperation2 != null) { if (error != null) { asyncOperation2.TrySetException(error); } else { asyncOperation2.TrySetResult(item: false); } } return true; } public override bool TryWrite(T item) { SingleConsumerUnboundedChannel<T> parent = _parent; AsyncOperation<T> asyncOperation; do { asyncOperation = null; AsyncOperation<bool> asyncOperation2 = null; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } asyncOperation = parent._blockedReader; if (asyncOperation != null) { parent._blockedReader = null; } else { parent._items.Enqueue(item); asyncOperation2 = parent._waitingReader; if (asyncOperation2 == null) { return true; } parent._waitingReader = null; } } if (asyncOperation2 != null) { asyncOperation2.TrySetResult(item: true); return true; } } while (!asyncOperation.TrySetResult(item)); return true; } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) { Exception doneWriting = _parent._doneWriting; if (!cancellationToken.IsCancellationRequested) { if (doneWriting != null) { if (doneWriting == ChannelUtilities.s_doneWritingSentinel) { return default(ValueTask<bool>); } return new ValueTask<bool>(Task.FromException<bool>(doneWriting)); } return new ValueTask<bool>(result: true); } return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } public override ValueTask WriteAsync(T item, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { if (!TryWrite(item)) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(_parent._doneWriting))); } return default(ValueTask); } return new ValueTask(Task.FromCanceled(cancellationToken)); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } private readonly TaskCompletionSource _completion; private readonly SingleProducerSingleConsumerQueue<T> _items = new SingleProducerSingleConsumerQueue<T>(); private readonly bool _runContinuationsAsynchronously; private volatile Exception _doneWriting; private AsyncOperation<T> _blockedReader; private AsyncOperation<bool> _waitingReader; private object SyncObj => _items; private int ItemsCountForDebugger => _items.Count; private bool ChannelIsClosedForDebugger => _doneWriting != null; internal SingleConsumerUnboundedChannel(bool runContinuationsAsynchronously) { _runContinuationsAsynchronously = runContinuationsAsynchronously; _completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); base.Reader = new UnboundedChannelReader(this); base.Writer = new UnboundedChannelWriter(this); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _items.GetEnumerator(); } } internal sealed class TaskCompletionSource : TaskCompletionSource<VoidResult> { public TaskCompletionSource(TaskCreationOptions creationOptions) : base(creationOptions) { } public bool TrySetResult() { return TrySetResult(default(VoidResult)); } } [DebuggerDisplay("Items={ItemsCountForDebugger}, Closed={ChannelIsClosedForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] internal sealed class UnboundedChannel<T> : Channel<T>, IDebugEnumerable<T> { [DebuggerDisplay("Items={Count}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelReader : ChannelReader<T>, IDebugEnumerable<T> { internal readonly UnboundedChannel<T> _parent; private readonly AsyncOperation<T> _readerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; public override Task Completion => _parent._completion.Task; public override bool CanCount => true; public override bool CanPeek => true; public override int Count => _parent._items.Count; internal UnboundedChannelReader(UnboundedChannel<T> parent) { _parent = parent; _readerSingleton = new AsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); } public override ValueTask<T> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } UnboundedChannel<T> parent = _parent; if (parent._items.TryDequeue(out var result)) { CompleteIfDone(parent); return new ValueTask<T>(result); } lock (parent.SyncObj) { if (parent._items.TryDequeue(out result)) { CompleteIfDone(parent); return new ValueTask<T>(result); } if (parent._doneWriting != null) { return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<T> readerSingleton = _readerSingleton; if (readerSingleton.TryOwnAndReset()) { parent._blockedReaders.EnqueueTail(readerSingleton); return readerSingleton.ValueTaskOfT; } } AsyncOperation<T> asyncOperation = new AsyncOperation<T>(parent._runContinuationsAsynchronously, cancellationToken); parent._blockedReaders.EnqueueTail(asyncOperation); return asyncOperation.ValueTaskOfT; } } public override bool TryRead([MaybeNullWhen(false)] out T item) { UnboundedChannel<T> parent = _parent; if (parent._items.TryDequeue(out item)) { CompleteIfDone(parent); return true; } item = default(T); return false; } public override bool TryPeek([MaybeNullWhen(false)] out T item) { return _parent._items.TryPeek(out item); } private static void CompleteIfDone(UnboundedChannel<T> parent) { if (parent._doneWriting != null && parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } if (!_parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } UnboundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<bool> waiterSingleton = _waiterSingleton; if (waiterSingleton.TryOwnAndReset()) { ChannelUtilities.QueueWaiter(ref parent._waitingReadersTail, waiterSingleton); return waiterSingleton.ValueTaskOfT; } } AsyncOperation<bool> asyncOperation = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, cancellationToken); ChannelUtilities.QueueWaiter(ref parent._waitingReadersTail, asyncOperation); return asyncOperation.ValueTaskOfT; } } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } [DebuggerDisplay("Items={ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T> { internal readonly UnboundedChannel<T> _parent; private int ItemsCountForDebugger => _parent._items.Count; internal UnboundedChannelWriter(UnboundedChannel<T> parent) { _parent = parent; } public override bool TryComplete(Exception error) { UnboundedChannel<T> parent = _parent; bool isEmpty; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel; isEmpty = parent._items.IsEmpty; } if (isEmpty) { ChannelUtilities.Complete(parent._completion, error); } ChannelUtilities.FailOperations<AsyncOperation<T>, T>(parent._blockedReaders, ChannelUtilities.CreateInvalidCompletionException(error)); ChannelUtilities.WakeUpWaiters(ref parent._waitingReadersTail, result: false, error); return true; } public override bool TryWrite(T item) { UnboundedChannel<T> parent = _parent; AsyncOperation<bool> listTail; while (true) { AsyncOperation<T> asyncOperation = null; listTail = null; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } if (parent._blockedReaders.IsEmpty) { parent._items.Enqueue(item); listTail = parent._waitingReadersTail; if (listTail == null) { return true; } parent._waitingReadersTail = null; } else { asyncOperation = parent._blockedReaders.DequeueHead(); } } if (asyncOperation == null) { break; } if (asyncOperation.TrySetResult(item)) { return true; } } ChannelUtilities.WakeUpWaiters(ref listTail, result: true); return true; } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) { Exception doneWriting = _parent._doneWriting; if (!cancellationToken.IsCancellationRequested) { if (doneWriting != null) { if (doneWriting == ChannelUtilities.s_doneWritingSentinel) { return default(ValueTask<bool>); } return new ValueTask<bool>(Task.FromException<bool>(doneWriting)); } return new ValueTask<bool>(result: true); } return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } public override ValueTask WriteAsync(T item, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { if (!TryWrite(item)) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(_parent._doneWriting))); } return default(ValueTask); } return new ValueTask(Task.FromCanceled(cancellationToken)); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } private readonly TaskCompletionSource _completion; private readonly ConcurrentQueue<T> _items = new ConcurrentQueue<T>(); private readonly Deque<AsyncOperation<T>> _blockedReaders = new Deque<AsyncOperation<T>>(); private readonly bool _runContinuationsAsynchronously; private AsyncOperation<bool> _waitingReadersTail; private Exception _doneWriting; private object SyncObj => _items; private int ItemsCountForDebugger => _items.Count; private bool ChannelIsClosedForDebugger => _doneWriting != null; internal UnboundedChannel(bool runContinuationsAsynchronously) { _runContinuationsAsynchronously = runContinuationsAsynchronously; _completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); base.Reader = new UnboundedChannelReader(this); base.Writer = new UnboundedChannelWriter(this); } [Conditional("DEBUG")] private void AssertInvariants() { if (!_items.IsEmpty) { _ = _runContinuationsAsynchronously; } if (!_blockedReaders.IsEmpty || _waitingReadersTail != null) { _ = _runContinuationsAsynchronously; } _ = _completion.Task.IsCompleted; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _items.GetEnumerator(); } } }
plugins/System.Threading.Tasks.Extensions.dll
Decompiled 2 years agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Threading.Tasks.Extensions")] [assembly: AssemblyDescription("System.Threading.Tasks.Extensions")] [assembly: AssemblyDefaultAlias("System.Threading.Tasks.Extensions")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.28619.01")] [assembly: AssemblyInformationalVersion("4.6.28619.01 @BuiltBy: dlab14-DDVSOWINAGE069 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/7601f4f6225089ffb291dc7d58293c7bbf5c5d4f")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyVersion("4.2.0.1")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } } namespace System { internal static class ThrowHelper { internal static void ThrowArgumentNullException(System.ExceptionArgument argument) { throw GetArgumentNullException(argument); } internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument) { throw GetArgumentOutOfRangeException(argument); } private static ArgumentNullException GetArgumentNullException(System.ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(System.ExceptionArgument argument) { return new ArgumentOutOfRangeException(GetArgumentName(argument)); } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetArgumentName(System.ExceptionArgument argument) { return argument.ToString(); } } internal enum ExceptionArgument { task, source, state } } namespace System.Threading.Tasks { [StructLayout(LayoutKind.Auto)] [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] public readonly struct ValueTask : IEquatable<ValueTask> { private sealed class ValueTaskSourceAsTask : TaskCompletionSource<bool> { private static readonly Action<object> s_completionAction = delegate(object state) { IValueTaskSource source; if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state); return; } valueTaskSourceAsTask._source = null; ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token); try { source.GetResult(valueTaskSourceAsTask._token); valueTaskSourceAsTask.TrySetResult(result: false); } catch (Exception exception) { if (status == ValueTaskSourceStatus.Canceled) { valueTaskSourceAsTask.TrySetCanceled(); } else { valueTaskSourceAsTask.TrySetException(exception); } } }; private IValueTaskSource _source; private readonly short _token; public ValueTaskSourceAsTask(IValueTaskSource source, short token) { _token = token; _source = source; source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None); } } private static readonly Task s_canceledTask = Task.Delay(-1, new CancellationToken(canceled: true)); internal readonly object _obj; internal readonly short _token; internal readonly bool _continueOnCapturedContext; internal static Task CompletedTask { get; } = Task.Delay(0); public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return true; } if (obj is Task task) { return task.IsCompleted; } return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending; } } public bool IsCompletedSuccessfully { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return true; } if (obj is Task task) { return task.Status == TaskStatus.RanToCompletion; } return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; } } public bool IsFaulted { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsFaulted; } return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; } } public bool IsCanceled { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsCanceled; } return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(Task task) { if (task == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task); } _obj = task; _continueOnCapturedContext = true; _token = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(IValueTaskSource source, short token) { if (source == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source); } _obj = source; _token = token; _continueOnCapturedContext = true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ValueTask(object obj, short token, bool continueOnCapturedContext) { _obj = obj; _token = token; _continueOnCapturedContext = continueOnCapturedContext; } public override int GetHashCode() { return _obj?.GetHashCode() ?? 0; } public override bool Equals(object obj) { if (obj is ValueTask) { return Equals((ValueTask)obj); } return false; } public bool Equals(ValueTask other) { if (_obj == other._obj) { return _token == other._token; } return false; } public static bool operator ==(ValueTask left, ValueTask right) { return left.Equals(right); } public static bool operator !=(ValueTask left, ValueTask right) { return !left.Equals(right); } public Task AsTask() { object obj = _obj; object obj2; if (obj != null) { obj2 = obj as Task; if (obj2 == null) { return GetTaskForValueTaskSource(Unsafe.As<IValueTaskSource>(obj)); } } else { obj2 = CompletedTask; } return (Task)obj2; } public ValueTask Preserve() { if (_obj != null) { return new ValueTask(AsTask()); } return this; } private Task GetTaskForValueTaskSource(IValueTaskSource t) { ValueTaskSourceStatus status = t.GetStatus(_token); if (status != 0) { try { t.GetResult(_token); return CompletedTask; } catch (Exception exception) { if (status == ValueTaskSourceStatus.Canceled) { return s_canceledTask; } TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(); taskCompletionSource.TrySetException(exception); return taskCompletionSource.Task; } } ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token); return valueTaskSourceAsTask.Task; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] internal void ThrowIfCompletedUnsuccessfully() { object obj = _obj; if (obj != null) { if (obj is Task task) { task.GetAwaiter().GetResult(); } else { Unsafe.As<IValueTaskSource>(obj).GetResult(_token); } } } public ValueTaskAwaiter GetAwaiter() { return new ValueTaskAwaiter(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _token, continueOnCapturedContext)); } } [StructLayout(LayoutKind.Auto)] [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] public readonly struct ValueTask<TResult> : IEquatable<ValueTask<TResult>> { private sealed class ValueTaskSourceAsTask : TaskCompletionSource<TResult> { private static readonly Action<object> s_completionAction = delegate(object state) { IValueTaskSource<TResult> source; if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state); return; } valueTaskSourceAsTask._source = null; ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token); try { valueTaskSourceAsTask.TrySetResult(source.GetResult(valueTaskSourceAsTask._token)); } catch (Exception exception) { if (status == ValueTaskSourceStatus.Canceled) { valueTaskSourceAsTask.TrySetCanceled(); } else { valueTaskSourceAsTask.TrySetException(exception); } } }; private IValueTaskSource<TResult> _source; private readonly short _token; public ValueTaskSourceAsTask(IValueTaskSource<TResult> source, short token) { _source = source; _token = token; source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None); } } private static Task<TResult> s_canceledTask; internal readonly object _obj; internal readonly TResult _result; internal readonly short _token; internal readonly bool _continueOnCapturedContext; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return true; } if (obj is Task<TResult> task) { return task.IsCompleted; } return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending; } } public bool IsCompletedSuccessfully { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return true; } if (obj is Task<TResult> task) { return task.Status == TaskStatus.RanToCompletion; } return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; } } public bool IsFaulted { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task<TResult> task) { return task.IsFaulted; } return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; } } public bool IsCanceled { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task<TResult> task) { return task.IsCanceled; } return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; } } public TResult Result { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return _result; } if (obj is Task<TResult> task) { return task.GetAwaiter().GetResult(); } return Unsafe.As<IValueTaskSource<TResult>>(obj).GetResult(_token); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(TResult result) { _result = result; _obj = null; _continueOnCapturedContext = true; _token = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(Task<TResult> task) { if (task == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task); } _obj = task; _result = default(TResult); _continueOnCapturedContext = true; _token = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(IValueTaskSource<TResult> source, short token) { if (source == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source); } _obj = source; _token = token; _result = default(TResult); _continueOnCapturedContext = true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ValueTask(object obj, TResult result, short token, bool continueOnCapturedContext) { _obj = obj; _result = result; _token = token; _continueOnCapturedContext = continueOnCapturedContext; } public override int GetHashCode() { if (_obj == null) { if (_result == null) { return 0; } return _result.GetHashCode(); } return _obj.GetHashCode(); } public override bool Equals(object obj) { if (obj is ValueTask<TResult>) { return Equals((ValueTask<TResult>)obj); } return false; } public bool Equals(ValueTask<TResult> other) { if (_obj == null && other._obj == null) { return EqualityComparer<TResult>.Default.Equals(_result, other._result); } if (_obj == other._obj) { return _token == other._token; } return false; } public static bool operator ==(ValueTask<TResult> left, ValueTask<TResult> right) { return left.Equals(right); } public static bool operator !=(ValueTask<TResult> left, ValueTask<TResult> right) { return !left.Equals(right); } public Task<TResult> AsTask() { object obj = _obj; if (obj == null) { return Task.FromResult(_result); } if (obj is Task<TResult> result) { return result; } return GetTaskForValueTaskSource(Unsafe.As<IValueTaskSource<TResult>>(obj)); } public ValueTask<TResult> Preserve() { if (_obj != null) { return new ValueTask<TResult>(AsTask()); } return this; } private Task<TResult> GetTaskForValueTaskSource(IValueTaskSource<TResult> t) { ValueTaskSourceStatus status = t.GetStatus(_token); if (status != 0) { try { return Task.FromResult(t.GetResult(_token)); } catch (Exception exception) { if (status == ValueTaskSourceStatus.Canceled) { Task<TResult> task = s_canceledTask; if (task == null) { TaskCompletionSource<TResult> taskCompletionSource = new TaskCompletionSource<TResult>(); taskCompletionSource.TrySetCanceled(); task = (s_canceledTask = taskCompletionSource.Task); } return task; } TaskCompletionSource<TResult> taskCompletionSource2 = new TaskCompletionSource<TResult>(); taskCompletionSource2.TrySetException(exception); return taskCompletionSource2.Task; } } ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token); return valueTaskSourceAsTask.Task; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTaskAwaiter<TResult> GetAwaiter() { return new ValueTaskAwaiter<TResult>(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredValueTaskAwaitable<TResult>(new ValueTask<TResult>(_obj, _result, _token, continueOnCapturedContext)); } public override string ToString() { if (IsCompletedSuccessfully) { TResult result = Result; if (result != null) { return result.ToString(); } } return string.Empty; } } } namespace System.Threading.Tasks.Sources { [Flags] public enum ValueTaskSourceOnCompletedFlags { None = 0, UseSchedulingContext = 1, FlowExecutionContext = 2 } public enum ValueTaskSourceStatus { Pending, Succeeded, Faulted, Canceled } public interface IValueTaskSource { ValueTaskSourceStatus GetStatus(short token); void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags); void GetResult(short token); } public interface IValueTaskSource<out TResult> { ValueTaskSourceStatus GetStatus(short token); void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags); TResult GetResult(short token); } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)] public sealed class AsyncMethodBuilderAttribute : Attribute { public Type BuilderType { get; } public AsyncMethodBuilderAttribute(Type builderType) { BuilderType = builderType; } } [StructLayout(LayoutKind.Auto)] public struct AsyncValueTaskMethodBuilder { private AsyncTaskMethodBuilder _methodBuilder; private bool _haveResult; private bool _useBuilder; public ValueTask Task { get { if (_haveResult) { return default(ValueTask); } _useBuilder = true; return new ValueTask(_methodBuilder.Task); } } public static AsyncValueTaskMethodBuilder Create() { return default(AsyncValueTaskMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { _methodBuilder.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { _methodBuilder.SetStateMachine(stateMachine); } public void SetResult() { if (_useBuilder) { _methodBuilder.SetResult(); } else { _haveResult = true; } } public void SetException(Exception exception) { _methodBuilder.SetException(exception); } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); } [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } } [StructLayout(LayoutKind.Auto)] public struct AsyncValueTaskMethodBuilder<TResult> { private AsyncTaskMethodBuilder<TResult> _methodBuilder; private TResult _result; private bool _haveResult; private bool _useBuilder; public ValueTask<TResult> Task { get { if (_haveResult) { return new ValueTask<TResult>(_result); } _useBuilder = true; return new ValueTask<TResult>(_methodBuilder.Task); } } public static AsyncValueTaskMethodBuilder<TResult> Create() { return default(AsyncValueTaskMethodBuilder<TResult>); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { _methodBuilder.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { _methodBuilder.SetStateMachine(stateMachine); } public void SetResult(TResult result) { if (_useBuilder) { _methodBuilder.SetResult(result); return; } _result = result; _haveResult = true; } public void SetException(Exception exception) { _methodBuilder.SetException(exception); } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); } [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } } [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaitable { [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public void GetResult() { _value.ThrowIfCompletedUnsuccessfully(); } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } } private readonly ValueTask _value; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() { return new ConfiguredValueTaskAwaiter(_value); } } [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaitable<TResult> { [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly ValueTask<TResult> _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(ValueTask<TResult> value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public TResult GetResult() { return _value.Result; } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task<TResult> task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task<TResult> task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } } private readonly ValueTask<TResult> _value; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(ValueTask<TResult> value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() { return new ConfiguredValueTaskAwaiter(_value); } } public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { internal static readonly Action<object> s_invokeActionDelegate = delegate(object state) { if (!(state is Action action)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state); } else { action(); } }; private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ValueTaskAwaiter(ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public void GetResult() { _value.ThrowIfCompletedUnsuccessfully(); } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); } else { ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation); } } } public readonly struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion, INotifyCompletion { private readonly ValueTask<TResult> _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ValueTaskAwaiter(ValueTask<TResult> value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public TResult GetResult() { return _value.Result; } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task<TResult> task) { task.GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); } else { ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task<TResult> task) { task.GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation); } } } [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class StackTraceHiddenAttribute : Attribute { } }