Decompiled source of OOD LIB v1.0.2
System.Buffers.dll
Decompiled 2 months 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.Buffers { public abstract class ArrayPool<T> { private static ArrayPool<T> s_sharedInstance; public static ArrayPool<T> Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static ArrayPool<T> EnsureSharedCreated() { Interlocked.CompareExchange(ref s_sharedInstance, Create(), null); return s_sharedInstance; } public static ArrayPool<T> Create() { return new DefaultArrayPool<T>(); } public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket) { return new DefaultArrayPool<T>(maxArrayLength, maxArraysPerBucket); } public abstract T[] Rent(int minimumLength); public abstract void Return(T[] array, bool clearArray = false); } [EventSource(Name = "System.Buffers.ArrayPoolEventSource")] internal sealed class ArrayPoolEventSource : EventSource { internal enum BufferAllocatedReason { Pooled, OverMaximumSize, PoolExhausted } internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource(); [Event(1, Level = EventLevel.Verbose)] internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId) { EventData* ptr = stackalloc EventData[4]; *ptr = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, DataPointer = (IntPtr)(&bucketId) }; WriteEventCore(1, 4, ptr); } [Event(2, Level = EventLevel.Informational)] internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason) { EventData* ptr = stackalloc EventData[5]; *ptr = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, DataPointer = (IntPtr)(&bucketId) }; ptr[4] = new EventData { Size = 4, DataPointer = (IntPtr)(&reason) }; WriteEventCore(2, 5, ptr); } [Event(3, Level = EventLevel.Verbose)] internal void BufferReturned(int bufferId, int bufferSize, int poolId) { WriteEvent(3, bufferId, bufferSize, poolId); } } internal sealed class DefaultArrayPool<T> : ArrayPool<T> { private sealed class Bucket { internal readonly int _bufferLength; private readonly T[][] _buffers; private readonly int _poolId; private SpinLock _lock; private int _index; internal int Id => GetHashCode(); internal Bucket(int bufferLength, int numberOfBuffers, int poolId) { _lock = new SpinLock(Debugger.IsAttached); _buffers = new T[numberOfBuffers][]; _bufferLength = bufferLength; _poolId = poolId; } internal T[] Rent() { T[][] buffers = _buffers; T[] array = null; bool lockTaken = false; bool flag = false; try { _lock.Enter(ref lockTaken); if (_index < buffers.Length) { array = buffers[_index]; buffers[_index++] = null; flag = array == null; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } if (flag) { array = new T[_bufferLength]; System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled); } } return array; } internal void Return(T[] array) { if (array.Length != _bufferLength) { throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array"); } bool lockTaken = false; try { _lock.Enter(ref lockTaken); if (_index != 0) { _buffers[--_index] = array; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } } } private const int DefaultMaxArrayLength = 1048576; private const int DefaultMaxNumberOfArraysPerBucket = 50; private static T[] s_emptyArray; private readonly Bucket[] _buckets; private int Id => GetHashCode(); internal DefaultArrayPool() : this(1048576, 50) { } internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket) { if (maxArrayLength <= 0) { throw new ArgumentOutOfRangeException("maxArrayLength"); } if (maxArraysPerBucket <= 0) { throw new ArgumentOutOfRangeException("maxArraysPerBucket"); } if (maxArrayLength > 1073741824) { maxArrayLength = 1073741824; } else if (maxArrayLength < 16) { maxArrayLength = 16; } int id = Id; int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength); Bucket[] array = new Bucket[num + 1]; for (int i = 0; i < array.Length; i++) { array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id); } _buckets = array; } public override T[] Rent(int minimumLength) { if (minimumLength < 0) { throw new ArgumentOutOfRangeException("minimumLength"); } if (minimumLength == 0) { return s_emptyArray ?? (s_emptyArray = new T[0]); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; T[] array = null; int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength); if (num < _buckets.Length) { int num2 = num; do { array = _buckets[num2].Rent(); if (array != null) { if (log.IsEnabled()) { log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id); } return array; } } while (++num2 < _buckets.Length && num2 != num + 2); array = new T[_buckets[num]._bufferLength]; } else { array = new T[minimumLength]; } if (log.IsEnabled()) { int hashCode = array.GetHashCode(); int bucketId = -1; log.BufferRented(hashCode, array.Length, Id, bucketId); log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted); } return array; } public override void Return(T[] array, bool clearArray = false) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Length == 0) { return; } int num = System.Buffers.Utilities.SelectBucketIndex(array.Length); if (num < _buckets.Length) { if (clearArray) { Array.Clear(array, 0, array.Length); } _buckets[num].Return(array); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferReturned(array.GetHashCode(), array.Length, Id); } } } internal static class Utilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int SelectBucketIndex(int bufferSize) { uint num = (uint)(bufferSize - 1) >> 4; int num2 = 0; if (num > 65535) { num >>= 16; num2 = 16; } if (num > 255) { num >>= 8; num2 += 8; } if (num > 15) { num >>= 4; num2 += 4; } if (num > 3) { num >>= 2; num2 += 2; } if (num > 1) { num >>= 1; num2++; } return num2 + (int)num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetMaxSizeForBucket(int binIndex) { return 16 << binIndex; } } }
System.Memory.dll
Decompiled 2 months 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 value2 = 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)) && (value2.High < 429496729 || (value2.High == 429496729 && (value2.Mid < 2576980377u || (value2.Mid == 2576980377u && (value2.Low < 2576980377u || (value2.Low == 2576980377u && *ptr <= 53))))))) { DecimalDecCalc.DecMul10(ref value2); if (*ptr != 0) { DecimalDecCalc.DecAddInt32(ref value2, (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 value2, 1u); if ((value2.High | value2.Mid | value2.Low) == 0) { value2.High = 429496729u; value2.Mid = 2576980377u; value2.Low = 2576980378u; num++; } } } } if (num > 0) { return false; } if (num <= -29) { value2.High = 0u; value2.Low = 0u; value2.Mid = 0u; value2.Scale = 28; } else { value2.Scale = -num; } value2.IsNegative = number.IsNegative; value = System.Runtime.CompilerServices.Unsafe.As<MutableDecimal, decimal>(ref value2); return true; } public static void DecimalToNumber(decimal value, ref NumberBuffer number) { ref MutableDecimal reference = ref System.Runtime.CompilerServices.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>(System.Runtime.CompilerServices.Unsafe.AsPointer<byte>(ref _b0), 51); public unsafe byte* UnsafeDigits => (byte*)System.Runtime.CompilerServices.Unsafe.AsPointer<byte>(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>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)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 System.Runtime.CompilerServices.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 = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = System.Runtime.CompilerServices.Unsafe.Add<T>(System.Runtime.CompilerServices.Unsafe.AsPointer<T>(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<T>(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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<T>(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 = System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num); System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num) = System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num2); System.Runtime.CompilerServices.Unsafe.Add<T>(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 = System.Runtime.CompilerServices.Unsafe.ByteOffset<T>(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (System.Runtime.CompilerServices.Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr >= (uint)(span.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>())) { return (uint)(int)intPtr > (uint)(-(other.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>())); } return true; } if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>())) { return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)System.Runtime.CompilerServices.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 = System.Runtime.CompilerServices.Unsafe.ByteOffset<T>(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (System.Runtime.CompilerServices.Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr < (uint)(span.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>()) || (uint)(int)intPtr > (uint)(-(other.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>()))) { if ((int)intPtr % System.Runtime.CompilerServices.Unsafe.SizeOf<T>() != 0) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)intPtr / System.Runtime.CompilerServices.Unsafe.SizeOf<T>(); return true; } elementOffset = 0; return false; } if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>()))) { if ((long)intPtr % System.Runtime.CompilerServices.Unsafe.SizeOf<T>() != 0L) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)((long)intPtr / System.Runtime.CompilerServices.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>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)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>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)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>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)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* ptr = text) { return System.Runtime.CompilerServices.Unsafe.ByteOffset<char>(ref System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)text).Data, ref System.Runtime.CompilerServices.Unsafe.AsRef<char>((void*)ptr)); } } } [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>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)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 = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = System.Runtime.CompilerServices.Unsafe.Add<T>(System.Runtime.CompilerServices.Unsafe.AsPointer<T>(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(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 = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)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 = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)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 System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset); } return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>((void*)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 System.Runtime.CompilerServices.Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { if (_byteOffset == MemoryExtensions.StringAdjustment) { object obj = System.Runtime.CompilerServices.Unsafe.As<object>((object)_pinnable); if (obj is string text && _length == text.Length) { return text; } } fixed (char* value = &System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(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 System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(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 = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)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>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)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 = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)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 System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset); } return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>((void*)null); } public unsafe void Clear() { int length = _length; if (length == 0) { return; } UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>()); if ((System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset)), byteLength); } } else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>() / sizeof(IntPtr)); System.SpanHelpers.ClearPointerSizedWithReferences(ref System.Runtime.CompilerServices.Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength); } else { System.SpanHelpers.ClearPointerSizedWithoutReferences(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength); } } public unsafe void Fill(T value) { int length = _length; if (length == 0) { return; } if (System.Runtime.CompilerServices.Unsafe.SizeOf<T>() == 1) { byte b = System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value); if (_pinnable == null) { IntPtr byteOffset = _byteOffset; System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), b, (uint)length); } else { System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset)), b, (uint)length); } return; } ref T reference = ref DangerousGetPinnableReference(); int i; for (i = 0; i < (length & -8); i += 8) { System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 1) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 2) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 3) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 4) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 5) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 6) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 7) = value; } if (i < (length & -4)) { System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 1) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 2) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 3) = value; i += 4; } for (; i < length; i++) { System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, 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 System.Runtime.CompilerServices.Unsafe.AreSame<T>(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 = &System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(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 System.Runtime.CompilerServices.Unsafe.ByteOffset<T>(ref System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)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(System.Runtime.CompilerServices.Unsafe.Add<T>(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 System.Runtime.CompilerServices.Unsafe.Add<byte>(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 System.Runtime.CompilerServices.Unsafe.Add<byte>(ref searchSpace, num2), value2, num3); if (num4 == -1) { break; } num2 += num4; if (SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<byte>(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, System.Runtime.CompilerServices.Unsafe.Add<byte>(ref value, i), searchSpaceLength); if ((uint)num2 < (uint)num) { num = num2; searchSpaceLength = num2; if (num == 0) { break;
AngleSharp.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using AngleSharp.Attributes; using AngleSharp.Browser; using AngleSharp.Browser.Dom; using AngleSharp.Browser.Dom.Events; using AngleSharp.Common; using AngleSharp.Css; using AngleSharp.Css.Dom; using AngleSharp.Css.Parser; using AngleSharp.Dom; using AngleSharp.Dom.Events; using AngleSharp.Html; using AngleSharp.Html.Construction; using AngleSharp.Html.Dom; using AngleSharp.Html.Dom.Events; using AngleSharp.Html.Forms; using AngleSharp.Html.Forms.Submitters; using AngleSharp.Html.Forms.Submitters.Json; using AngleSharp.Html.InputTypes; using AngleSharp.Html.LinkRels; using AngleSharp.Html.Parser; using AngleSharp.Html.Parser.Tokens; using AngleSharp.Html.Parser.Tokens.Struct; using AngleSharp.Io; using AngleSharp.Io.Dom; using AngleSharp.Io.Processors; using AngleSharp.Mathml; using AngleSharp.Mathml.Dom; using AngleSharp.Media; using AngleSharp.Media.Dom; using AngleSharp.Scripting; using AngleSharp.Svg; using AngleSharp.Svg.Dom; using AngleSharp.Text; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCopyright("Copyright © AngleSharp, 2013-2024")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("AngleSharp.Core.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010001adf274fa2b375134e8e4558d606f1a0f96f5cd0c6b99970f7cce9887477209d7c29f814e2508d8bd2526e99e8cd273bd1158a3984f1ea74830ec5329a77c6ff201a15edeb8b36ab046abd1bce211fe8dbb076d7d806f46b15bfda44def04ead0669971e96c5f666c9eda677f28824fff7aa90d32929ed91d529a7a41699893")] [assembly: TargetFramework(".NETFramework,Version=v4.6.1", FrameworkDisplayName = ".NET Framework 4.6.1")] [assembly: AssemblyCompany("AngleSharp")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("AngleSharp is the ultimate angle brackets parser library. It parses HTML5, CSS3, and XML to construct a DOM based on the official W3C specification.")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0+7ef54d45e2fc0479f0a50958452e3211af40269e")] [assembly: AssemblyProduct("AngleSharp")] [assembly: AssemblyTitle("AngleSharp")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/AngleSharp/AngleSharp")] [assembly: AssemblyVersion("1.1.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace AngleSharp { public sealed class BrowsingContext : EventTarget, IBrowsingContext, IEventTarget, IDisposable { private readonly IEnumerable<object> _originalServices; private readonly List<object> _services; private readonly Sandboxes _security; private readonly IBrowsingContext? _parent; private readonly IDocument? _creator; private readonly IHistory? _history; private readonly Dictionary<string, WeakReference<IBrowsingContext>> _children; public IDocument? Active { get; set; } public IDocument? Creator => _creator; public IEnumerable<object> OriginalServices => _originalServices; public IWindow? Current => Active?.DefaultView; public IBrowsingContext? Parent => _parent; public IHistory? SessionHistory => _history; public Sandboxes Security => _security; public BrowsingContext(IConfiguration? configuration = null) : this((configuration ?? Configuration.Default).Services, Sandboxes.None) { } private BrowsingContext(Sandboxes security) { _services = new List<object>(); _originalServices = _services; _security = security; _children = new Dictionary<string, WeakReference<IBrowsingContext>>(); } internal BrowsingContext(IEnumerable<object> services, Sandboxes security) : this(security) { _services.AddRange(services); _originalServices = services; _history = GetService<IHistory>(); } internal BrowsingContext(IBrowsingContext parent, Sandboxes security) : this(parent.OriginalServices, security) { _parent = parent; _creator = _parent.Active; } public T? GetService<T>() where T : class { int count = _services.Count; int num = 0; while (num < count) { object obj = _services[num]; T val = obj as T; if (val == null) { if (!(obj is Func<IBrowsingContext, T> func)) { num++; continue; } val = func(this); _services[num] = val; } return val; } return null; } public IEnumerable<T> GetServices<T>() where T : class { int count = _services.Count; for (int i = 0; i < count; i++) { object obj = _services[i]; T val = obj as T; if (val == null) { if (!(obj is Func<IBrowsingContext, T> func)) { continue; } val = func(this); _services[i] = val; } yield return val; } } public IBrowsingContext CreateChild(string? name, Sandboxes security) { BrowsingContext browsingContext = new BrowsingContext(this, security); if (name != null && name.Length > 0) { _children[name] = new WeakReference<IBrowsingContext>(browsingContext); } return browsingContext; } public IBrowsingContext? FindChild(string name) { IBrowsingContext target = null; if (!string.IsNullOrEmpty(name) && _children.TryGetValue(name, out WeakReference<IBrowsingContext> value)) { value.TryGetTarget(out target); } return target; } public static IBrowsingContext New(IConfiguration? configuration = null) { if (configuration == null) { configuration = Configuration.Default; } return new BrowsingContext(configuration.Services, Sandboxes.None); } public static IBrowsingContext NewFrom<TService>(TService instance) { return new BrowsingContext(Configuration.Default.WithOnly(instance).Services, Sandboxes.None); } void IDisposable.Dispose() { Active?.Dispose(); Active = null; } } public static class BrowsingContextExtensions { public static Task<IDocument> OpenNewAsync(this IBrowsingContext context, string? url = null, CancellationToken cancellation = default(CancellationToken)) { string url2 = url; return context.OpenAsync(delegate(VirtualResponse m) { m.Address(url2 ?? "http://localhost/"); }, cancellation); } public static Task<IDocument> OpenAsync(this IBrowsingContext context, IResponse response, CancellationToken cancel = default(CancellationToken)) { response = response ?? throw new ArgumentNullException("response"); if (context == null) { context = BrowsingContext.New(); } Encoding defaultEncoding = context.GetDefaultEncoding(); IDocumentFactory factory = context.GetFactory<IDocumentFactory>(); CreateDocumentOptions options = new CreateDocumentOptions(response, defaultEncoding); return factory.CreateAsync(context, options, cancel); } public static Task<IDocument> OpenAsync(this IBrowsingContext context, DocumentRequest request, CancellationToken cancel = default(CancellationToken)) { request = request ?? throw new ArgumentNullException("request"); if (context == null) { context = BrowsingContext.New(); } return context.NavigateToAsync(request, cancel); } public static Task<IDocument> OpenAsync(this IBrowsingContext context, Url url, CancellationToken cancel = default(CancellationToken)) { url = url ?? throw new ArgumentNullException("url"); return context.OpenAsync(DocumentRequest.Get(url, null, context?.Active?.DocumentUri), cancel); } public static async Task<IDocument> OpenAsync(this IBrowsingContext context, Action<VirtualResponse> request, CancellationToken cancel = default(CancellationToken)) { request = request ?? throw new ArgumentNullException("request"); using IResponse response = VirtualResponse.Create(request); return await context.OpenAsync(response, cancel).ConfigureAwait(continueOnCapturedContext: false); } public static Task<IDocument> OpenAsync(this IBrowsingContext context, string address, CancellationToken cancellation = default(CancellationToken)) { address = address ?? throw new ArgumentNullException("address"); return context.OpenAsync(Url.Create(address), cancellation); } internal static Task<IDocument> NavigateToAsync(this IBrowsingContext context, DocumentRequest request, CancellationToken cancel = default(CancellationToken)) { return context.GetNavigationHandler(request.Target)?.NavigateAsync(request, cancel) ?? Task.FromResult<IDocument>(null); } public static void NavigateTo(this IBrowsingContext context, IDocument document) { context.SessionHistory?.PushState(document, document.Title, document.Url); context.Active = document; } public static INavigationHandler? GetNavigationHandler(this IBrowsingContext context, Url url) { Url url2 = url; return context.GetServices<INavigationHandler>().FirstOrDefault((INavigationHandler m) => m.SupportsProtocol(url2.Scheme)); } public static Encoding GetDefaultEncoding(this IBrowsingContext context) { IEncodingProvider? provider = context.GetProvider<IEncodingProvider>(); string language = context.GetLanguage(); return provider?.Suggest(language) ?? Encoding.UTF8; } public static CultureInfo GetCulture(this IBrowsingContext context) { return context.GetService<CultureInfo>() ?? CultureInfo.CurrentUICulture; } public static CultureInfo GetCultureFrom(this IBrowsingContext context, string language) { try { return new CultureInfo(language); } catch (CultureNotFoundException ex) { context.TrackError(ex); return context.GetCulture(); } } public static string GetLanguage(this IBrowsingContext context) { return context.GetCulture().Name; } public static TFactory GetFactory<TFactory>(this IBrowsingContext context) where TFactory : class { return context.GetServices<TFactory>().Single(); } public static TProvider? GetProvider<TProvider>(this IBrowsingContext context) where TProvider : class { return context.GetServices<TProvider>().SingleOrDefault(); } public static IResourceService<TResource>? GetResourceService<TResource>(this IBrowsingContext context, string type) where TResource : IResourceInfo { foreach (IResourceService<TResource> service in context.GetServices<IResourceService<TResource>>()) { if (service.SupportsType(type)) { return service; } } return null; } public static string GetCookie(this IBrowsingContext context, Url url) { return context.GetProvider<ICookieProvider>()?.GetCookie(url) ?? string.Empty; } public static void SetCookie(this IBrowsingContext context, Url url, string value) { context.GetProvider<ICookieProvider>()?.SetCookie(url, value); } public static ISpellCheckService? GetSpellCheck(this IBrowsingContext context, string language) { ISpellCheckService spellCheckService = null; IEnumerable<ISpellCheckService> services = context.GetServices<ISpellCheckService>(); CultureInfo cultureFrom = context.GetCultureFrom(language); string twoLetterISOLanguageName = cultureFrom.TwoLetterISOLanguageName; foreach (ISpellCheckService item in services) { CultureInfo culture = item.Culture; if (culture != null) { string twoLetterISOLanguageName2 = culture.TwoLetterISOLanguageName; if (culture.Equals(cultureFrom)) { return item; } if (spellCheckService == null && twoLetterISOLanguageName2.Is(twoLetterISOLanguageName)) { spellCheckService = item; } } } return spellCheckService; } public static IStylingService? GetCssStyling(this IBrowsingContext context) { return context.GetStyling(MimeTypeNames.Css); } public static IStylingService? GetStyling(this IBrowsingContext context, string type) { foreach (IStylingService service in context.GetServices<IStylingService>()) { if (service.SupportsType(type)) { return service; } } return null; } public static bool IsScripting(this IBrowsingContext context) { return context.GetServices<IScriptingService>().Any(); } public static IScriptingService? GetJsScripting(this IBrowsingContext context) { return context.GetScripting(MimeTypeNames.DefaultJavaScript); } public static IScriptingService? GetScripting(this IBrowsingContext context, string type) { foreach (IScriptingService service in context.GetServices<IScriptingService>()) { if (service.SupportsType(type)) { return service; } } return null; } public static ICommand? GetCommand(this IBrowsingContext context, string commandId) { return context.GetProvider<ICommandProvider>()?.GetCommand(commandId); } public static void TrackError(this IBrowsingContext context, Exception ex) { AngleSharp.Browser.Dom.Events.TrackEvent eventData = new AngleSharp.Browser.Dom.Events.TrackEvent("error", ex); context.Fire(eventData); } public static Task InteractAsync<T>(this IBrowsingContext context, string eventName, T data) { InteractivityEvent<T> interactivityEvent = new InteractivityEvent<T>(eventName, data); context.Fire(interactivityEvent); return interactivityEvent.Result ?? Task.FromResult(result: false); } public static IBrowsingContext ResolveTargetContext(this IBrowsingContext context, string? target) { bool flag = false; IBrowsingContext browsingContext = context; if (target != null && target.Length > 0) { browsingContext = context.FindChildFor(target); flag = browsingContext == null; } if (flag) { browsingContext = context.CreateChildFor(target); } return browsingContext; } public static IBrowsingContext CreateChildFor(this IBrowsingContext context, string? target) { Sandboxes security = Sandboxes.None; if (target == "_blank") { target = null; } return context.CreateChild(target, security); } public static IBrowsingContext? FindChildFor(this IBrowsingContext context, string target) { if (!string.IsNullOrEmpty(target)) { switch (target) { case "_self": break; case "_parent": return context.Parent ?? context; case "_top": return context; default: return context.FindChild(target); } } return context; } public static IEnumerable<Task> GetDownloads<T>(this IBrowsingContext context) where T : INode { IResourceLoader service = context.GetService<IResourceLoader>(); if (service == null) { return Array.Empty<Task>(); } return from m in service.GetDownloads() where m.Source is T select m.Task; } } public class Configuration : IConfiguration { private readonly IEnumerable<object> _services; public static IConfiguration Default => new Configuration(); public IEnumerable<object> Services => _services; private static T Instance<T>(T instance) { return instance; } private static Func<IBrowsingContext, T> Creator<T>(Func<IBrowsingContext, T> creator) { return creator; } public Configuration(IEnumerable<object>? services = null) { _services = services ?? new object[17] { Instance((IElementFactory<Document, HtmlElement>)new HtmlElementFactory()), Instance((IElementFactory<Document, MathElement>)new MathElementFactory()), Instance((IElementFactory<Document, SvgElement>)new SvgElementFactory()), Instance((IEventFactory)new DefaultEventFactory()), Instance((IInputTypeFactory)new DefaultInputTypeFactory()), Instance((IAttributeSelectorFactory)new DefaultAttributeSelectorFactory()), Instance((IPseudoElementSelectorFactory)new DefaultPseudoElementSelectorFactory()), Instance((IPseudoClassSelectorFactory)new DefaultPseudoClassSelectorFactory()), Instance((ILinkRelationFactory)new DefaultLinkRelationFactory()), Instance((IDocumentFactory)new DefaultDocumentFactory()), Instance((IAttributeObserver)new DefaultAttributeObserver()), Instance((IMetaHandler)new EncodingMetaHandler()), Instance((IHtmlEncoder)new DefaultHtmlEncoder()), Creator((Func<IBrowsingContext, ICssSelectorParser>)((IBrowsingContext ctx) => new CssSelectorParser(ctx))), Creator((Func<IBrowsingContext, IHtmlParser>)((IBrowsingContext ctx) => new HtmlParser(ctx))), Creator((Func<IBrowsingContext, INavigationHandler>)((IBrowsingContext ctx) => new DefaultNavigationHandler(ctx))), Creator((Func<IBrowsingContext, IHtmlElementConstructionFactory>)((IBrowsingContext ctx) => new HtmlDomConstructionFactory(ctx))) }; } } public static class ConfigurationExtensions { public static IConfiguration With(this IConfiguration configuration, object service) { configuration = configuration ?? throw new ArgumentNullException("configuration"); service = service ?? throw new ArgumentNullException("service"); return new Configuration(configuration.Services.Concat(service)); } public static IConfiguration WithOnly<TService>(this IConfiguration configuration, TService service) { if (service == null) { throw new ArgumentNullException("service"); } return configuration.Without<TService>().With(service); } public static IConfiguration WithOnly<TService>(this IConfiguration configuration, Func<IBrowsingContext, TService> creator) { creator = creator ?? throw new ArgumentNullException("creator"); return configuration.Without<TService>().With(creator); } public static IConfiguration Without(this IConfiguration configuration, object service) { configuration = configuration ?? throw new ArgumentNullException("configuration"); service = service ?? throw new ArgumentNullException("service"); return new Configuration(configuration.Services.Except(service)); } public static IConfiguration With(this IConfiguration configuration, IEnumerable<object> services) { configuration = configuration ?? throw new ArgumentNullException("configuration"); services = services ?? throw new ArgumentNullException("services"); return new Configuration(services.Concat(configuration.Services)); } public static IConfiguration Without(this IConfiguration configuration, IEnumerable<object> services) { configuration = configuration ?? throw new ArgumentNullException("configuration"); services = services ?? throw new ArgumentNullException("services"); return new Configuration(configuration.Services.Except(services)); } public static IConfiguration With<TService>(this IConfiguration configuration, Func<IBrowsingContext, TService> creator) { creator = creator ?? throw new ArgumentNullException("creator"); return configuration.With((object)creator); } public static IConfiguration Without<TService>(this IConfiguration configuration) { configuration = configuration ?? throw new ArgumentNullException("configuration"); IEnumerable<object> services = configuration.Services.OfType<TService>().Cast<object>(); IEnumerable<Func<IBrowsingContext, TService>> services2 = configuration.Services.OfType<Func<IBrowsingContext, TService>>(); return configuration.Without(services).Without(services2); } public static bool Has<TService>(this IConfiguration configuration) { configuration = configuration ?? throw new ArgumentNullException("configuration"); if (!configuration.Services.OfType<TService>().Any()) { return configuration.Services.OfType<Func<IBrowsingContext, TService>>().Any(); } return true; } public static IConfiguration WithDefaultLoader(this IConfiguration configuration, LoaderOptions? setup = null) { LoaderOptions config = setup ?? new LoaderOptions(); if (!configuration.Has<IRequester>()) { configuration = configuration.With(new DefaultHttpRequester()); } if (!config.IsNavigationDisabled) { configuration = configuration.With((Func<IBrowsingContext, IDocumentLoader>)((IBrowsingContext ctx) => new DefaultDocumentLoader(ctx, config.Filter))); } if (config.IsResourceLoadingEnabled) { configuration = configuration.With((Func<IBrowsingContext, IResourceLoader>)((IBrowsingContext ctx) => new DefaultResourceLoader(ctx, config.Filter))); } return configuration; } public static IConfiguration WithCulture(this IConfiguration configuration, string name) { CultureInfo culture = new CultureInfo(name); return configuration.WithCulture(culture); } public static IConfiguration WithCulture(this IConfiguration configuration, CultureInfo culture) { return configuration.With(culture); } public static IConfiguration WithMetaRefresh(this IConfiguration configuration, Predicate<Url>? shouldRefresh = null) { RefreshMetaHandler service = new RefreshMetaHandler(shouldRefresh); return configuration.With(service); } public static IConfiguration WithLocaleBasedEncoding(this IConfiguration configuration) { LocaleEncodingProvider service = new LocaleEncodingProvider(); return configuration.With(service); } public static IConfiguration WithDefaultCookies(this IConfiguration configuration) { MemoryCookieProvider service = new MemoryCookieProvider(); return configuration.With(service); } } public static class FormatExtensions { public static string ToCss(this IStyleFormattable style) { return style.ToCss(CssStyleFormatter.Instance); } public static string ToCss(this IStyleFormattable style, IStyleFormatter formatter) { StringBuilder sb = StringBuilderPool.Obtain(); using (StringWriter writer = new StringWriter(sb)) { style.ToCss(writer, formatter); } return sb.ToPool(); } public static void ToCss(this IStyleFormattable style, TextWriter writer) { style.ToCss(writer, CssStyleFormatter.Instance); } public static Task ToCssAsync(this IStyleFormattable style, TextWriter writer) { return writer.WriteAsync(style.ToCss()); } public static async Task ToCssAsync(this IStyleFormattable style, Stream stream) { using StreamWriter writer = new StreamWriter(stream); await style.ToCssAsync(writer).ConfigureAwait(continueOnCapturedContext: false); } public static string ToHtml(this IMarkupFormattable markup) { return markup.ToHtml(HtmlMarkupFormatter.Instance); } public static string ToHtml(this IMarkupFormattable markup, IMarkupFormatter formatter) { StringBuilder sb = StringBuilderPool.Obtain(); using (StringWriter writer = new StringWriter(sb)) { markup.ToHtml(writer, formatter); } return sb.ToPool(); } public static void ToHtml(this IMarkupFormattable markup, TextWriter writer) { markup.ToHtml(writer, HtmlMarkupFormatter.Instance); } public static string Minify(this IMarkupFormattable markup) { return markup.ToHtml(new MinifyMarkupFormatter()); } public static string Prettify(this IMarkupFormattable markup) { return markup.ToHtml(new PrettyMarkupFormatter()); } public static Task ToHtmlAsync(this IMarkupFormattable markup, TextWriter writer) { return writer.WriteAsync(markup.ToHtml()); } public static async Task ToHtmlAsync(this IMarkupFormattable markup, Stream stream) { using StreamWriter writer = new StreamWriter(stream); await markup.ToHtmlAsync(writer).ConfigureAwait(continueOnCapturedContext: false); } } public interface IBrowsingContext : IEventTarget, IDisposable { IWindow? Current { get; } IDocument? Active { get; set; } IHistory? SessionHistory { get; } Sandboxes Security { get; } IBrowsingContext? Parent { get; } IDocument? Creator { get; } IEnumerable<object> OriginalServices { get; } T? GetService<T>() where T : class; IEnumerable<T> GetServices<T>() where T : class; IBrowsingContext CreateChild(string? name, Sandboxes security); IBrowsingContext? FindChild(string name); } public interface IConfiguration { IEnumerable<object> Services { get; } } public interface IMarkupFormattable { void ToHtml(TextWriter writer, IMarkupFormatter formatter); } public interface IMarkupFormatter { string Text(ICharacterData text); string LiteralText(ICharacterData text); string Comment(IComment comment); string Processing(IProcessingInstruction processing); string Doctype(IDocumentType doctype); string OpenTag(IElement element, bool selfClosing); string CloseTag(IElement element, bool selfClosing); } public interface IStyleFormattable { void ToCss(TextWriter writer, IStyleFormatter formatter); } public interface IStyleFormatter { string Sheet(IEnumerable<IStyleFormattable> rules); string Declaration(string name, string value, bool important); string BlockDeclarations(IEnumerable<IStyleFormattable> declarations); string Rule(string name, string value); string Rule(string name, string prelude, string rules); string BlockRules(IEnumerable<IStyleFormattable> rules); string Comment(string data); } } namespace AngleSharp.Xhtml { public class XhtmlMarkupFormatter : IMarkupFormatter { public static readonly IMarkupFormatter Instance = new XhtmlMarkupFormatter(); private readonly bool _emptyTagsToSelfClosing; public bool IsSelfClosingEmptyTags => _emptyTagsToSelfClosing; public XhtmlMarkupFormatter() : this(emptyTagsToSelfClosing: true) { } public XhtmlMarkupFormatter(bool emptyTagsToSelfClosing) { _emptyTagsToSelfClosing = emptyTagsToSelfClosing; } public virtual string CloseTag(IElement element, bool selfClosing) { string prefix = element.Prefix; string localName = element.LocalName; string text = ((!string.IsNullOrEmpty(prefix)) ? (prefix + ":" + localName) : localName); if (!selfClosing && (!_emptyTagsToSelfClosing || element.HasChildNodes)) { return "</" + text + ">"; } return string.Empty; } public virtual string Comment(IComment comment) { return "<!--" + comment.Data + "-->"; } public virtual string Doctype(IDocumentType doctype) { string publicIdentifier = doctype.PublicIdentifier; string systemIdentifier = doctype.SystemIdentifier; string text = ((string.IsNullOrEmpty(publicIdentifier) && string.IsNullOrEmpty(systemIdentifier)) ? string.Empty : (" " + (string.IsNullOrEmpty(publicIdentifier) ? ("SYSTEM \"" + systemIdentifier + "\"") : ("PUBLIC \"" + publicIdentifier + "\" \"" + systemIdentifier + "\"")))); return "<!DOCTYPE " + doctype.Name + text + ">"; } public virtual string OpenTag(IElement element, bool selfClosing) { string prefix = element.Prefix; StringBuilder stringBuilder = StringBuilderPool.Obtain(); stringBuilder.Append('<'); if (!string.IsNullOrEmpty(prefix)) { stringBuilder.Append(prefix).Append(':'); } stringBuilder.Append(element.LocalName); foreach (IAttr attribute in element.Attributes) { stringBuilder.Append(' ').Append(Attribute(attribute)); } if (selfClosing || (_emptyTagsToSelfClosing && !element.HasChildNodes)) { stringBuilder.Append(" /"); } stringBuilder.Append('>'); return stringBuilder.ToPool(); } public virtual string Processing(IProcessingInstruction processing) { string text = processing.Target + " " + processing.Data; return "<?" + text + "?>"; } public virtual string LiteralText(ICharacterData text) { return text.Data; } public virtual string Text(ICharacterData text) { return EscapeText(text.Data); } protected virtual string Attribute(IAttr attribute) { string namespaceUri = attribute.NamespaceUri; string localName = attribute.LocalName; string value = attribute.Value; StringBuilder stringBuilder = StringBuilderPool.Obtain(); if (string.IsNullOrEmpty(namespaceUri)) { stringBuilder.Append(localName); } else if (namespaceUri.Is(NamespaceNames.XmlUri)) { stringBuilder.Append(NamespaceNames.XmlPrefix).Append(':').Append(localName); } else if (namespaceUri.Is(NamespaceNames.XLinkUri)) { stringBuilder.Append(NamespaceNames.XLinkPrefix).Append(':').Append(localName); } else if (namespaceUri.Is(NamespaceNames.XmlNsUri)) { stringBuilder.Append(XmlNamespaceLocalName(localName)); } else { stringBuilder.Append(attribute.Name); } stringBuilder.Append('=').Append('"'); for (int i = 0; i < value.Length; i++) { switch (value[i]) { case '&': stringBuilder.Append("&"); break; case '\u00a0': stringBuilder.Append(" "); break; case '<': stringBuilder.Append("<"); break; case '"': stringBuilder.Append("""); break; default: stringBuilder.Append(value[i]); break; } } return stringBuilder.Append('"').ToPool(); } public static string EscapeText(string content) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); for (int i = 0; i < content.Length; i++) { switch (content[i]) { case '&': stringBuilder.Append("&"); break; case '\u00a0': stringBuilder.Append(" "); break; case '>': stringBuilder.Append(">"); break; case '<': stringBuilder.Append("<"); break; default: stringBuilder.Append(content[i]); break; } } return stringBuilder.ToPool(); } public static string XmlNamespaceLocalName(string localName) { if (localName.Is(NamespaceNames.XmlNsPrefix)) { return localName; } return NamespaceNames.XmlNsPrefix + ':' + localName; } } } namespace AngleSharp.Text { public sealed class CharArrayTextSource : IReadOnlyTextSource, IDisposable { private int _index; private string? _content; private readonly char[] _array; private readonly ReadOnlyMemory<char> _memory; private readonly int _length; public string Text => _content ?? (_content = new string(_array, 0, _length)); public char this[int index] => _array[index]; public int Length => _length; public Encoding CurrentEncoding { get { return TextEncoding.Utf8; } set { } } public int Index { get { return _index; } set { _index = value; } } public CharArrayTextSource(char[] array, int length) { _array = array; _length = length; _memory = array.AsMemory(0, length); } public void Dispose() { } public char ReadCharacter() { if (_index < _length) { return _array[_index++]; } _index++; return '\uffff'; } public string ReadCharacters(int characters) { return ReadMemory(characters).ToString(); } public StringOrMemory ReadMemory(int characters) { int index = _index; if (index + characters <= _length) { _index += characters; return _memory.Slice(index, characters); } _index += characters; characters = Math.Min(characters, _length - index); return _memory.Slice(index, characters); } public Task PrefetchAsync(int length, CancellationToken cancellationToken) { return Task.CompletedTask; } public Task PrefetchAllAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public bool TryGetContentLength(out int length) { length = _length; return true; } } public static class CharExtensions { public static int FromHex(this char c) { if (!c.IsDigit()) { return c - (c.IsLowercaseAscii() ? 87 : 55); } return c - 48; } public static string ToHex(this byte num) { Span<char> span = stackalloc char[2]; int num2 = num >> 4; span[0] = (char)(num2 + ((num2 < 10) ? 48 : 55)); num2 = num - 16 * num2; span[1] = (char)(num2 + ((num2 < 10) ? 48 : 55)); return span.ToString(); } public static string ToHex(this char character) { int num = character; return num.ToString("x"); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRange(this char c, int lower, int upper) { if (c >= lower) { return c <= upper; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNormalQueryCharacter(this char c) { if (c.IsInRange(33, 126) && c != '"' && c != '`' && c != '#' && c != '<') { return c != '>'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNormalPathCharacter(this char c) { if (c.IsInRange(32, 126) && c != '"' && c != '`' && c != '#' && c != '<' && c != '>' && c != ' ') { return c != '?'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsUppercaseAscii(this char c) { if (c >= 'A') { return c <= 'Z'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLowercaseAscii(this char c) { if (c >= 'a') { return c <= 'z'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAlphanumericAscii(this char c) { if (!c.IsDigit() && !c.IsUppercaseAscii()) { return c.IsLowercaseAscii(); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHex(this char c) { if (!c.IsDigit() && (c < 'A' || c > 'F')) { if (c >= 'a') { return c <= 'f'; } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNonAscii(this char c) { if (c != '\uffff') { return c >= '\u0080'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNonPrintable(this char c) { if ((c < '\0' || c > '\b') && (c < '\u000e' || c > '\u001f')) { if (c >= '\u007f') { return c <= '\u009f'; } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLetter(this char c) { if (!c.IsUppercaseAscii()) { return c.IsLowercaseAscii(); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsName(this char c) { if (!c.IsNonAscii() && !c.IsLetter() && c != '_' && c != '-') { return c.IsDigit(); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsCustomElementName(this char c) { if (c != '_' && c != '-' && c != '.' && !c.IsDigit() && !c.IsLowercaseAscii() && c != '·' && !c.IsInRange(192, 214) && !c.IsInRange(216, 246) && !c.IsInRange(248, 893) && !c.IsInRange(895, 8191) && !c.IsInRange(8204, 8205) && !c.IsInRange(8255, 8256) && !c.IsInRange(8304, 8591) && !c.IsInRange(11264, 12271) && !c.IsInRange(12289, 55295) && !c.IsInRange(63744, 64975) && !c.IsInRange(65008, 65533)) { return c.IsInRange(65536, 2031615); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNameStart(this char c) { if (!c.IsNonAscii() && !c.IsUppercaseAscii() && !c.IsLowercaseAscii()) { return c == '_'; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLineBreak(this char c) { if (c != '\n') { return c == '\r'; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsSpaceCharacter(this char c) { if (c != ' ' && c != '\t' && c != '\n' && c != '\r') { return c == '\f'; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsWhiteSpaceCharacter(this char c) { if (!c.IsInRange(9, 13) && c != ' ' && c != '\u0085' && c != '\u00a0' && c != '\u1680' && c != '\u180e' && !c.IsInRange(8192, 8202) && c != '\u2028' && c != '\u2029' && c != '\u202f' && c != '\u205f') { return c == '\u3000'; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDigit(this char c) { if (c >= '0') { return c <= '9'; } return false; } public static bool IsUrlCodePoint(this char c) { if (!c.IsAlphanumericAscii() && c != '!' && c != '$' && c != '&' && c != '\'' && c != '(' && c != ')' && c != '*' && c != '+' && c != '-' && c != ',' && c != '.' && c != '/' && c != ':' && c != ';' && c != '=' && c != '?' && c != '@' && c != '_' && c != '~' && !c.IsInRange(160, 55295) && !c.IsInRange(57344, 64975) && !c.IsInRange(65008, 65533) && !c.IsInRange(65536, 131069) && !c.IsInRange(131072, 196605) && !c.IsInRange(196608, 262141) && !c.IsInRange(262144, 327677) && !c.IsInRange(327680, 393213) && !c.IsInRange(393216, 458749) && !c.IsInRange(458752, 524285) && !c.IsInRange(524288, 589821) && !c.IsInRange(589824, 655357) && !c.IsInRange(655360, 720893) && !c.IsInRange(720896, 786429) && !c.IsInRange(786432, 851965) && !c.IsInRange(851968, 917501) && !c.IsInRange(917504, 983037) && !c.IsInRange(983040, 1048573)) { return c.IsInRange(1048576, 1114109); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInvalid(this int c) { if (c != 0 && c <= 1114111) { if (c > 55296) { return c < 57343; } return false; } return true; } } public interface ITextSource : IReadOnlyTextSource, IDisposable { void InsertText(string content); } public interface IReadOnlyTextSource : IDisposable { string Text { get; } int Length { get; } Encoding CurrentEncoding { get; set; } int Index { get; set; } char this[int index] { get; } char ReadCharacter(); string ReadCharacters(int characters); StringOrMemory ReadMemory(int characters); Task PrefetchAsync(int length, CancellationToken cancellationToken); Task PrefetchAllAsync(CancellationToken cancellationToken); bool TryGetContentLength(out int length); } public static class Punycode { private const int PunycodeBase = 36; private const int Tmin = 1; private const int Tmax = 26; private static readonly string acePrefix = "xn--"; private static readonly char[] possibleDots = new char[4] { '.', '。', '.', '。' }; public static IDictionary<char, char> Symbols = new Dictionary<char, char> { { '。', '.' }, { '.', '.' }, { 'G', 'g' }, { 'o', 'o' }, { 'c', 'c' }, { 'X', 'x' }, { '0', '0' }, { '1', '1' }, { '2', '2' }, { '5', '5' }, { '⁰', '0' }, { '¹', '1' }, { '²', '2' }, { '³', '3' }, { '⁴', '4' }, { '⁵', '5' }, { '⁶', '6' }, { '⁷', '7' }, { '⁸', '8' }, { '⁹', '9' }, { '₀', '0' }, { '₁', '1' }, { '₂', '2' }, { '₃', '3' }, { '₄', '4' }, { '₅', '5' }, { '₆', '6' }, { '₇', '7' }, { '₈', '8' }, { '₉', '9' }, { 'ᵃ', 'a' }, { 'ᵇ', 'b' }, { 'ᶜ', 'c' }, { 'ᵈ', 'd' }, { 'ᵉ', 'e' }, { 'ᶠ', 'f' }, { 'ᵍ', 'g' }, { 'ʰ', 'h' }, { 'ⁱ', 'i' }, { 'ʲ', 'j' }, { 'ᵏ', 'k' }, { 'ˡ', 'l' }, { 'ᵐ', 'm' }, { 'ⁿ', 'n' }, { 'ᵒ', 'o' }, { 'ᵖ', 'p' }, { 'ʳ', 'r' }, { 'ˢ', 's' }, { 'ᵗ', 't' }, { 'ᵘ', 'u' }, { 'ᵛ', 'v' }, { 'ʷ', 'w' }, { 'ˣ', 'x' }, { 'ʸ', 'y' }, { 'ᶻ', 'z' }, { 'ᴬ', 'A' }, { 'ᴮ', 'B' }, { 'ᴰ', 'D' }, { 'ᴱ', 'E' }, { 'ᴳ', 'G' }, { 'ᴴ', 'H' }, { 'ᴵ', 'I' }, { 'ᴶ', 'J' }, { 'ᴷ', 'K' }, { 'ᴸ', 'L' }, { 'ᴹ', 'M' }, { 'ᴺ', 'N' }, { 'ᴼ', 'O' }, { 'ᴾ', 'P' }, { 'ᴿ', 'R' }, { 'ᵀ', 'T' }, { 'ᵁ', 'U' }, { 'ⱽ', 'V' }, { 'ᵂ', 'W' } }; public static string Encode(string text) { if (text.Length == 0) { return text; } StringBuilder stringBuilder = new StringBuilder(text.Length); int num = 0; int num2 = 0; int num3 = 0; while (num < text.Length) { num = text.IndexOfAny(possibleDots, num2); if (num < 0) { num = text.Length; } if (num == num2) { break; } stringBuilder.Append(acePrefix); int num4 = 0; int num5 = 0; for (num4 = num2; num4 < num; num4++) { if (text[num4] < '\u0080') { stringBuilder.Append(EncodeBasic(text[num4])); num5++; } else if (char.IsSurrogatePair(text, num4)) { num4++; } } int num6 = num5; if (num6 == num - num2) { stringBuilder.Remove(num3, acePrefix.Length); } else { if (text.Length - num2 >= acePrefix.Length && text.Substring(num2, acePrefix.Length).Isi(acePrefix)) { break; } int num7 = 0; if (num6 > 0) { stringBuilder.Append('-'); } int num8 = 128; int num9 = 0; int num10 = 72; while (num5 < num - num2) { int num11 = 0; int num12 = 0; int num13 = 0; num12 = 134217727; for (num11 = num2; num11 < num; num11 += ((!IsSupplementary(num13)) ? 1 : 2)) { num13 = char.ConvertToUtf32(text, num11); if (num13 >= num8 && num13 < num12) { num12 = num13; } } num9 += (num12 - num8) * (num5 - num7 + 1); num8 = num12; for (num11 = num2; num11 < num; num11 += ((!IsSupplementary(num13)) ? 1 : 2)) { num13 = char.ConvertToUtf32(text, num11); if (num13 < num8) { num9++; } else { if (num13 != num8) { continue; } int num14 = num9; int num15 = 36; while (true) { int num16 = ((num15 <= num10) ? 1 : ((num15 >= num10 + 26) ? 26 : (num15 - num10))); if (num14 < num16) { break; } stringBuilder.Append(EncodeDigit(num16 + (num14 - num16) % (36 - num16))); num14 = (num14 - num16) / (36 - num16); num15 += 36; } stringBuilder.Append(EncodeDigit(num14)); num10 = AdaptChar(num9, num5 - num7 + 1, num5 == num6); num9 = 0; num5++; if (IsSupplementary(num12)) { num5++; num7++; } } } num9++; num8++; } } if (stringBuilder.Length - num3 > 63) { throw new ArgumentException(); } if (num != text.Length) { stringBuilder.Append(possibleDots[0]); } num2 = num + 1; num3 = stringBuilder.Length; } int num17 = ((!IsDot(text[text.Length - 1])) ? 1 : 0); int num18 = 255 - num17; if (stringBuilder.Length > num18) { stringBuilder.Remove(num18, stringBuilder.Length - num18); } return stringBuilder.ToString(); } private static bool IsSupplementary(int test) { return test >= 65536; } private static bool IsDot(char c) { for (int i = 0; i < possibleDots.Length; i++) { if (possibleDots[i] == c) { return true; } } return false; } private static char EncodeDigit(int digit) { if (digit > 25) { return (char)(digit + 22); } return (char)(digit + 97); } private static char EncodeBasic(char character) { if (char.IsUpper(character)) { character = (char)(character + 32); } return character; } private static int AdaptChar(int delta, int numPoints, bool firstTime) { uint num = 0u; delta = (firstTime ? (delta / 700) : (delta / 2)); delta += delta / numPoints; num = 0u; while (delta > 455) { delta /= 35; num += 36; } return (int)(num + 36 * delta / (delta + 38)); } } public sealed class ReadOnlyMemoryTextSource : IReadOnlyTextSource, IDisposable { private int _index; private string? _content; private readonly ReadOnlyMemory<char> _memory; private readonly int _length; public string Text => _content ?? (_content = _memory.Span.ToString()); public char this[int index] { get { if (_content == null) { return _memory.Span[index]; } return _content[index]; } } public int Length => _length; public Encoding CurrentEncoding { get { return TextEncoding.Utf8; } set { } } public int Index { get { return _index; } set { _index = value; } } public ReadOnlyMemoryTextSource(ReadOnlyMemory<char> memory) { _memory = memory; _length = memory.Length; } public ReadOnlyMemoryTextSource(string str) { _content = str; _memory = str.AsMemory(); _length = _memory.Length; } public void Dispose() { } public char ReadCharacter() { if (_index < _length) { return _memory.Span[_index++]; } _index++; return '\uffff'; } public string ReadCharacters(int characters) { return ReadMemory(characters).ToString(); } public StringOrMemory ReadMemory(int characters) { int index = _index; if (index + characters <= _length) { _index += characters; return _memory.Slice(index, characters); } _index += characters; characters = Math.Min(characters, _length - index); return _memory.Slice(index, characters); } public Task PrefetchAsync(int length, CancellationToken cancellationToken) { return Task.CompletedTask; } public Task PrefetchAllAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public bool TryGetContentLength(out int length) { length = _length; return true; } } public static class StringBuilderPool { private static readonly Stack<StringBuilder> _builder = new Stack<StringBuilder>(); private static readonly object _lock = new object(); private static int _count = 4; private static int _limit = 85000; public static int MaxCount { get { return _count; } set { _count = Math.Max(1, value); } } public static int SizeLimit { get { return _limit; } set { _limit = Math.Max(1024, value); } } public static StringBuilder Obtain() { lock (_lock) { if (_builder.Count == 0) { return new StringBuilder(1024); } return _builder.Pop().Clear(); } } public static string ToPool(this StringBuilder sb) { string result = sb.ToString(); sb.ReturnToPool(); return result; } internal static void ReturnToPool(this StringBuilder sb) { lock (_lock) { int count = _builder.Count; if (sb.Capacity <= _limit) { if (count == _count) { DropMinimum(sb); } else if (count < Math.Min(2, _count) || _builder.Peek().Capacity < sb.Capacity) { _builder.Push(sb); } } } } private static void DropMinimum(StringBuilder sb) { int capacity = sb.Capacity; StringBuilder[] instances = _builder.ToArray(); int num = FindIndex(instances, capacity); if (num > -1) { RebuildPool(sb, instances, num); } } private static void RebuildPool(StringBuilder sb, StringBuilder[] instances, int index) { _builder.Clear(); int num = instances.Length - 1; while (num > index) { _builder.Push(instances[num--]); } while (num > 0) { _builder.Push(instances[--num]); } _builder.Push(sb); } private static int FindIndex(StringBuilder[] instances, int minimum) { int result = -1; for (int i = 0; i < instances.Length; i++) { int capacity = instances[i].Capacity; if (capacity < minimum) { minimum = capacity; result = i; } } return result; } } public static class StringExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Has([NotNullWhen(true)] this string? value, char chr, int index = 0) { if (value != null && value.Length > index) { return value[index] == chr; } return false; } internal static string GetCompatiblity(this QuirksMode mode) { string result = "CSS1Compat"; string text = mode.ToString(); if (text != null) { FieldInfo field = typeof(QuirksMode).GetField(text); if (field != null) { DomDescriptionAttribute customAttribute = field.GetCustomAttribute<DomDescriptionAttribute>(); if (customAttribute != null) { result = customAttribute.Description; } } } return result; } public static StringOrMemory HtmlLower(this StringOrMemory value) { int length = value.Length; for (int j = 0; j < length; j++) { if (value[j].IsUppercaseAscii()) { if (length < 128) { Span<char> result2 = stackalloc char[length]; return Slow(value, j, result2); } char[] array = ArrayPool<char>.Shared.Rent(length); Span<char> result3 = array.AsSpan(0, length); string text = Slow(value, j, result3); ArrayPool<char>.Shared.Return(array); return text; } } return value; static string Slow(StringOrMemory value, int i, Span<char> result) { for (int k = 0; k < i; k++) { result[k] = value[k]; } char c = value[i]; result[i] = char.ToLowerInvariant(c); for (int l = i + 1; l < value.Length; l++) { c = value[l]; if (c.IsUppercaseAscii()) { c = char.ToLowerInvariant(c); } result[l] = c; } return result.ToString(); } } public static string HtmlLower(this string value) { return new StringOrMemory(value).HtmlLower().ToString(); } public static Sandboxes ParseSecuritySettings(this string value, bool allowFullscreen = false) { string[] list = value.SplitSpaces(); Sandboxes sandboxes = Sandboxes.Navigation | Sandboxes.Plugins | Sandboxes.DocumentDomain; if (!list.Contains("allow-popups", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.AuxiliaryNavigation; } if (!list.Contains("allow-top-navigation", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.TopLevelNavigation; } if (!list.Contains("allow-same-origin", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.Origin; } if (!list.Contains("allow-forms", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.Forms; } if (!list.Contains("allow-pointer-lock", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.PointerLock; } if (!list.Contains("allow-scripts", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.Scripts; sandboxes |= Sandboxes.AutomaticFeatures; } if (!list.Contains("allow-presentation", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.Presentation; } if (!allowFullscreen) { sandboxes |= Sandboxes.Fullscreen; } return sandboxes; } public static T ToEnum<T>(this string? value, T defaultValue) where T : struct, Enum { if (!string.IsNullOrEmpty(value) && Enum.TryParse<T>(value, ignoreCase: true, out var result)) { return result; } return defaultValue; } public static double ToDouble(this string? value, double defaultValue = 0.0) { if (!string.IsNullOrEmpty(value) && double.TryParse(value, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var result)) { return result; } return defaultValue; } public static int ToInteger(this string? value, int defaultValue = 0) { if (!string.IsNullOrEmpty(value) && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) { return result; } return defaultValue; } public static uint ToInteger(this string? value, uint defaultValue = 0u) { if (!string.IsNullOrEmpty(value) && uint.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) { return result; } return defaultValue; } public static bool ToBoolean(this string? value, bool defaultValue = false) { if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out var result)) { return result; } return defaultValue; } public static string ReplaceFirst(this string text, string search, string replace) { int num = text.IndexOf(search); if (num < 0) { return text; } return text.Substring(0, num) + replace + text.Substring(num + search.Length); } public static string CollapseAndStrip(this string str) { if (str.Length == 0) { return str; } char[] array = ArrayPool<char>.Shared.Rent(str.Length); bool flag = true; int num = 0; int length = str.Length; for (int i = 0; i < length; i++) { if (str[i].IsSpaceCharacter()) { if (!flag) { flag = true; array[num++] = ' '; } } else { flag = false; array[num++] = str[i]; } } if (flag && num > 0) { num--; } string result = new string(array, 0, num); ArrayPool<char>.Shared.Return(array); return result; } public static string Collapse(this string str) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); bool flag = false; int length = str.Length; for (int i = 0; i < length; i++) { if (str[i].IsSpaceCharacter()) { if (!flag) { stringBuilder.Append(' '); flag = true; } } else { flag = false; stringBuilder.Append(str[i]); } } return stringBuilder.ToPool(); } public static bool Contains(this string[] list, string element, StringComparison comparison = StringComparison.Ordinal) { int num = list.Length; for (int i = 0; i < num; i++) { if (list[i].Equals(element, comparison)) { return true; } } return false; } public static bool IsCustomElement(this string tag) { if (tag.IndexOf('-') != -1 && !TagNames.DisallowedCustomElementNames.Contains(tag)) { int length = tag.Length; for (int i = 0; i < length; i++) { if (!tag[i].IsCustomElementName()) { return false; } } return true; } return false; } public static bool IsCustomElement(this StringOrMemory tag) { if (tag.Memory.Span.IndexOf('-') != -1 && !TagNames.DisallowedCustomElementNames.Contains(tag)) { int length = tag.Length; for (int i = 0; i < length; i++) { if (!tag[i].IsCustomElementName()) { return false; } } return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Is(this string? current, string? other) { return string.Equals(current, other, StringComparison.Ordinal); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Is(this string? current, StringOrMemory other) { return other.Memory.Span.SequenceEqual(current.AsSpan()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Is(this Span<char> current, string? other) { if (other == null) { return false; } return current.SequenceEqual(other.AsSpan()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Is(this ReadOnlySpan<char> current, ReadOnlyMemory<char> other) { return current.SequenceEqual(other.Span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Is(this ReadOnlySpan<char> current, ReadOnlySpan<char> other) { return current.SequenceEqual(other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Isi(this string? current, string? other) { return string.Equals(current, other, StringComparison.OrdinalIgnoreCase); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Isi(this string? current, StringOrMemory other) { return MemoryExtensions.Equals(current.AsSpan(), other.Memory.Span, StringComparison.OrdinalIgnoreCase); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Isi(this Span<char> current, string? other) { if (other == null) { return false; } return MemoryExtensions.Equals(current, other.AsSpan(), StringComparison.OrdinalIgnoreCase); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Isi(this Span<char> current, ReadOnlySpan<char> other) { return MemoryExtensions.Equals(current, other, StringComparison.OrdinalIgnoreCase); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Isi(this Span<char> current, ReadOnlyMemory<char> other) { return MemoryExtensions.Equals(current, other.Span, StringComparison.OrdinalIgnoreCase); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Isi(this ReadOnlySpan<char> current, string? other) { if (other == null) { return false; } return MemoryExtensions.Equals(current, other.AsSpan(), StringComparison.OrdinalIgnoreCase); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOneOf(this string? element, string item1, string item2) { if (!element.Is(item1)) { return element.Is(item2); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOneOf(this string element, string item1, string item2, string item3) { if (!element.Is(item1) && !element.Is(item2)) { return element.Is(item3); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOneOf(this string element, string item1, string item2, string item3, string item4) { if (!element.Is(item1) && !element.Is(item2) && !element.Is(item3)) { return element.Is(item4); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOneOf(this string element, string item1, string item2, string item3, string item4, string item5) { if (!element.Is(item1) && !element.Is(item2) && !element.Is(item3) && !element.Is(item4)) { return element.Is(item5); } return true; } public static string StripLineBreaks(this string str) { char[] array = str.ToCharArray(); int num = 0; int num2 = array.Length; int num3 = 0; while (num3 < num2) { array[num3] = array[num3 + num]; if (array[num3].IsLineBreak()) { num++; num2--; } else { num3++; } } return new string(array, 0, num2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string StripLeadingTrailingSpaces(this string str) { int i = 0; int num = str.Length - 1; for (; i < str.Length && str[i].IsSpaceCharacter(); i++) { } while (num > i && str[num].IsSpaceCharacter()) { num--; } return str.Substring(i, 1 + num - i); } public static string[] SplitWithoutTrimming(this string str, char c) { List<string> list = new List<string>(); int num = 0; int length = str.Length; for (int i = 0; i < length; i++) { if (str[i] == c) { if (i > num) { list.Add(str.Substring(num, i - num)); } num = i + 1; } } if (length > num) { list.Add(str.Substring(num, length - num)); } return list.ToArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string[] SplitCommas(this string str) { return str.SplitWithTrimming(','); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasHyphen(this string str, string value, StringComparison comparison = StringComparison.Ordinal) { if (!string.Equals(str, value, comparison)) { if (str.Length > value.Length && str.StartsWith(value, comparison)) { return str[value.Length] == '-'; } return false; } return true; } public static string[] SplitSpaces(this string str) { List<string> list = new List<string>(); char[] array = ArrayPool<char>.Shared.Rent(str.Length); int num = 0; for (int i = 0; i <= str.Length; i++) { if (i == str.Length || str[i].IsSpaceCharacter()) { if (num > 0) { string text = new string(array, 0, num).StripLeadingTrailingSpaces(); if (text.Length != 0) { list.Add(text); } num = 0; } } else { array[num] = str[i]; num++; } } ArrayPool<char>.Shared.Return(array); return list.ToArray(); } public static string[] SplitWithTrimming(this string str, char ch) { List<string> list = new List<string>(); char[] array = ArrayPool<char>.Shared.Rent(str.Length); int num = 0; for (int i = 0; i <= str.Length; i++) { if (i == str.Length || str[i] == ch) { if (num > 0) { string text = new string(array, 0, num).StripLeadingTrailingSpaces(); if (text.Length != 0) { list.Add(text); } num = 0; } } else { array[num] = str[i]; num++; } } ArrayPool<char>.Shared.Return(array); return list.ToArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromHex(this string s) { return int.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromDec(this string s) { return int.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string HtmlEncode(this string value, Encoding encoding) { return value; } public static string CssString(this string value) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); stringBuilder.Append('"'); if (!string.IsNullOrEmpty(value)) { int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; switch (c) { case '\0': stringBuilder.ReturnToPool(); throw new DomException(DomError.InvalidCharacter); case '"': case '\\': stringBuilder.Append('\\').Append(c); continue; } if (c.IsInRange(1, 31) || c == '{') { stringBuilder.Append('\\').Append(c.ToHex()).Append((i + 1 != length) ? " " : ""); } else { stringBuilder.Append(c); } } } stringBuilder.Append('"'); return stringBuilder.ToPool(); } public static string CssFunction(this string value, string argument) { return value + "(" + argument + ")"; } public static string UrlEncode(this byte[] content) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); int num = content.Length; for (int i = 0; i < num; i++) { char c = (char)content[i]; switch (c) { case ' ': stringBuilder.Append('+'); break; default: if (!c.IsAlphanumericAscii()) { stringBuilder.Append('%').Append(content[i].ToString("X2")); break; } goto case '*'; case '*': case '-': case '.': case '_': case '~': stringBuilder.Append(c); break; } } return stringBuilder.ToPool(); } public static byte[] UrlDecode(this string value) { MemoryStream memoryStream = new MemoryStream(); int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; switch (c) { case '+': { byte value4 = 32; memoryStream.WriteByte(value4); break; } case '%': { if (i + 2 >= length) { throw new FormatException(); } byte value3 = (byte)(16 * value[++i].FromHex() + value[++i].FromHex()); memoryStream.WriteByte(value3); break; } default: { byte value2 = (byte)c; memoryStream.WriteByte(value2); break; } } } return memoryStream.ToArray(); } public static string NormalizeLineEndings(this string value) { if (!string.IsNullOrEmpty(value)) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); bool flag = false; int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; bool flag2 = c == '\n'; if (flag && !flag2) { stringBuilder.Append('\n'); } else if (!flag && flag2) { stringBuilder.Append('\r'); } flag = c == '\r'; stringBuilder.Append(c); } if (flag) { stringBuilder.Append('\n'); } return stringBuilder.ToPool(); } return value; } public static string? ToEncodingType(this string? encType) { if (!encType.Isi(MimeTypeNames.Plain) && !encType.Isi(MimeTypeNames.MultipartForm) && !encType.Isi(MimeTypeNames.ApplicationJson)) { return null; } return encType?.ToLowerInvariant(); } public static string? ToFormMethod(this string? method) { if (!method.Isi(FormMethodNames.Get) && !method.Isi(FormMethodNames.Post) && !method.Isi(FormMethodNames.Dialog)) { return null; } return method?.ToLowerInvariant(); } } public sealed class StringSource { private readonly string _content; private readonly int _last; private int _index; private char _current; public char Current => _current; public bool IsDone => _current == '\uffff'; public int Index => _index; public string Content => _content; public StringSource(string content) { _content = content ?? string.Empty; _last = _content.Length - 1; _index = 0; _current = ((_last == -1) ? '\uffff' : content[0]); } public char Next() { if (_index == _last) { _current = '\uffff'; _index = _content.Length; } else if (_index < _content.Length) { _current = _content[++_index]; } return _current; } public char Back() { if (_index > 0) { _current = _content[--_index]; } return _current; } } public static class StringSourceExtensions { public static char SkipSpaces(this StringSource source) { char c = source.Current; while (c.IsSpaceCharacter()) { c = source.Next(); } return c; } public static char Next(this StringSource source, int n) { for (int i = 0; i < n; i++) { source.Next(); } return source.Current; } public static char Back(this StringSource source, int n) { for (int i = 0; i < n; i++) { source.Back(); } return source.Current; } public static char Peek(this StringSource source) { char result = source.Next(); source.Back(); return result; } } public sealed class StringTextSource : IReadOnlyTextSource, IDisposable { private readonly string _string; private readonly ReadOnlyMemory<char> _memory; private readonly int _length; private int _index; public string Text => _string; public char this[int index] => _string[index]; public int Length => _length; public Encoding CurrentEncoding { get { return TextEncoding.Utf8; } set { } } public int Index { get { return _index; } set { _index = value; } } public StringTextSource(string source) { _string = source; _length = source.Length; _memory = source.AsMemory(); } public void Dispose() { } public char ReadCharacter() { if (_index < _length) { return _string[_index++]; } _index++; return '\uffff'; } public string ReadCharacters(int characters) { return ReadMemory(characters).ToString(); } public StringOrMemory ReadMemory(int characters) { int index = _index; if (index + characters <= _length) { _index += characters; return _memory.Slice(index, characters); } _index += characters; characters = Math.Min(characters, _length - index); return _memory.Slice(index, characters); } public Task PrefetchAsync(int length, CancellationToken cancellationToken) { return Task.CompletedTask; } public Task PrefetchAllAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public bool TryGetContentLength(out int length) { length = _length; return true; } } public static class Symbols { public const char EndOfFile = '\uffff'; public const char Tilde = '~'; public const char Pipe = '|'; public const char Null = '\0'; public const char Ampersand = '&'; public const char Num = '#'; public const char Dollar = '$'; public const char Semicolon = ';'; public const char Asterisk = '*'; public const char Equality = '='; public const char Plus = '+'; public const char Minus = '-'; public const char Comma = ','; public const char Dot = '.'; public const char Accent = '^'; public const char At = '@'; public const char LessThan = '<'; public const char GreaterThan = '>'; public const char SingleQuote = '\''; public const char DoubleQuote = '"'; public const char CurvedQuote = '`'; public const char QuestionMark = '?'; public const char Tab = '\t'; public const char LineFeed = '\n'; public const char CarriageReturn = '\r'; public const char FormFeed = '\f'; public const char Space = ' '; public const char Solidus = '/'; public const char NoBreakSpace = '\u00a0'; public const char ReverseSolidus = '\\'; public const char Colon = ':'; public const char ExclamationMark = '!'; public const char Replacement = '\ufffd'; public const char Underscore = '_'; public const char RoundBracketOpen = '('; public const char RoundBracketClose = ')'; public const char SquareBracketOpen = '['; public const char SquareBracketClose = ']'; public const char CurlyBracketOpen = '{'; public const char CurlyBracketClose = '}'; public const char Percent = '%'; public const int MaximumCodepoint = 1114111; } public static class TextEncoding { public static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); public static readonly Encoding Utf16Be = new UnicodeEncoding(bigEndian: true, byteOrderMark: false); public static readonly Encoding Utf16Le = new UnicodeEncoding(bigEndian: false, byteOrderMark: false); public static readonly Encoding Utf32Le = GetEncoding("UTF-32LE"); public static readonly Encoding Utf32Be = GetEncoding("UTF-32BE"); public static readonly Encoding Gb18030 = GetEncoding("GB18030"); public static readonly Encoding Big5 = GetEncoding("big5"); public static readonly Encoding Windows874 = GetEncoding("windows-874"); public static readonly Encoding Windows1250 = GetEncoding("windows-1250"); public static readonly Encoding Windows1251 = GetEncoding("windows-1251"); public static readonly Encoding Windows1252 = GetEncoding("windows-1252"); public static readonly Encoding Windows1253 = GetEncoding("windows-1253"); public static readonly Encoding Windows1254 = GetEncoding("windows-1254"); public static readonly Encoding Windows1255 = GetEncoding("windows-1255"); public static readonly Encoding Windows1256 = GetEncoding("windows-1256"); public static readonly Encoding Windows1257 = GetEncoding("windows-1257"); public static readonly Encoding Windows1258 = GetEncoding("windows-1258"); public static readonly Encoding Latin2 = GetEncoding("iso-8859-2"); public static readonly Encoding Latin3 = GetEncoding("iso-8859-3"); public static readonly Encoding Latin4 = GetEncoding("iso-8859-4"); public static readonly Encoding Latin5 = GetEncoding("iso-8859-5"); public static readonly Encoding Latin13 = GetEncoding("iso-8859-13"); public static readonly Encoding UsAscii = GetEncoding("us-ascii"); public static readonly Encoding Korean = GetEncoding("ks_c_5601-1987"); private static readonly Dictionary<string, Encoding> encodings = CreateEncodings(); public static bool IsUnicode(this Encoding encoding) { if (encoding != Utf16Be) { return encoding == Utf16Le; } return true; } public static Encoding? Parse(string content) { string charset = string.Empty; int num = 0; for (int i = num; i < content.Length - 7; i++) { if (content.Substring(i).StartsWith(AttributeNames.Charset, StringComparison.OrdinalIgnoreCase)) { num = i + 7; break; } } if (num > 0 && num < content.Length) { for (int j = num; j < content.Length - 1 && content[j].IsSpaceCharacter(); j++) { num++; } if (content[num] != '=') { return Parse(content.Substring(num)); } num++; for (int k = num; k < content.Length && content[k].IsSpaceCharacter(); k++) { num++; } if (num < content.Length) { if (content[num] == '"') { content = content.Substring(num + 1); int num2 = content.IndexOf('"'); if (num2 != -1) { charset = content.Substring(0, num2); } } else if (content[num] == '\'') { content = content.Substring(num + 1); int num3 = content.IndexOf('\''); if (num3 != -1) { charset = content.Substring(0, num3); } } else { content = content.Substring(num); int num4 = 0; for (int l = 0; l < content.Length && !content[l].IsSpaceCharacter() && content[l] != ';'; l++) { num4++; } charset = content.Substring(0, num4); } } } if (!IsSupported(charset)) { return null; } return Resolve(charset); } public static bool IsSupported(string charset) { return encodings.ContainsKey(charset); } public static Encoding Resolve(string? charset) { if (charset != null && encodings.TryGetValue(charset, out Encoding value)) { return value; } return Utf8; } private static Encoding GetEncoding(string name, Encoding? fallback = null) { try { return Encoding.GetEncoding(name); } catch (Exception) { return fallback ?? Utf8; } } private static Dictionary<string, Encoding> CreateEncodings() { Dictionary<string, Encoding> obj = new Dictionary<string, Encoding>(StringComparer.OrdinalIgnoreCase) { { "unicode-1-1-utf-8", Utf8 }, { "utf-8", Utf8 }, { "utf8", Utf8 }, { "utf-16be", Utf16Be }, { "utf-16", Utf16Le }, { "utf-16le", Utf16Le }, { "dos-874", Windows874 }, { "iso-8859-11", Windows874 }, { "iso8859-11", Windows874 }, { "iso885911", Windows874 }, { "tis-620", Windows874 }, { "windows-874", Windows874 }, { "cp1250", Windows1250 }, { "windows-1250", Windows1250 }, { "x-cp1250", Windows1250 }, { "cp1251", Windows1251 }, { "windows-1251", Windows1251 }, { "x-cp1251", Windows1251 }, { "x-user-defined", Windows1252 }, { "ansi_x3.4-1968", Windows1252 }, { "ascii", Windows1252 }, { "cp1252", Windows1252 }, { "cp819", Windows1252 }, { "csisolatin1", Windows1252 }, { "ibm819", Windows1252 }, { "iso-8859-1", Windows1252 }, { "iso-ir-100", Windows1252 }, { "iso8859-1", Windows1252 }, { "iso88591", Windows1252 }, { "iso_8859-1", Windows1252 }, { "iso_8859-1:1987", Windows1252 }, { "l1", Windows1252 }, { "latin1", Windows1252 }, { "us-ascii", Windows1252 }, { "windows-1252", Windows1252 }, { "x-cp1252", Windows1252 }, { "cp1253", Windows1253 }, { "windows-1253", Windows1253 }, { "x-cp1253", Windows1253 }, { "cp1254", Windows1254 }, { "csisolatin5", Windows1254 }, { "iso-8859-9", Windows1254 }, { "iso-ir-148", Windows1254 }, { "iso8859-9", Windows1254 }, { "iso88599", Windows1254 }, { "iso_8859-9", Windows1254 }, { "iso_8859-9:1989", Windows1254 }, { "l5", Windows1254 }, { "latin5", Windows1254 }, { "windows-1254", Windows1254 }, { "x-cp1254", Windows1254 }, { "cp1255", Windows1255 }, { "windows-1255", Windows1255 }, { "x-cp1255", Windows1255 }, { "cp1256", Windows1256 }, { "windows-1256", Windows1256 }, { "x-cp1256", Windows1256 }, { "cp1257", Windows1257 }, { "windows-1257", Windows1257 }, { "x-cp1257", Windows1257 }, { "cp1258", Windows1258 }, { "windows-1258", Windows1258 }, { "x-cp1258", Windows1258 } }; Encoding encoding = GetEncoding("macintosh"); obj.Add("csmacintosh", encoding); obj.Add("mac", encoding); obj.Add("macintosh", encoding); obj.Add("x-mac-roman", encoding); Encoding encoding2 = GetEncoding("x-mac-cyrillic"); obj.Add("x-mac-cyrillic", encoding2); obj.Add("x-mac-ukrainian", encoding2); Encoding encoding3 = GetEncoding("cp866"); obj.Add("866", encoding3); obj.Add("cp866", encoding3); obj.Add("csibm866", encoding3); obj.Add("ibm866", encoding3); obj.Add("csisolatin2", Latin2); obj.Add("iso-8859-2", Latin2); obj.Add("iso-ir-101", Latin2); obj.Add("iso8859-2", Latin2); obj.Add("iso88592", Latin2); obj.Add("iso_8859-2", Latin2); obj.Add("iso_8859-2:1987", Latin2); obj.Add("l2", Latin2); obj.Add("latin2", Latin2); obj.Add("csisolatin3", Latin3); obj.Add("iso-8859-3", Latin3); obj.Add("iso-ir-109", Latin3); obj.Add("iso8859-3", Latin3); obj.Add("iso88593", Latin3); obj.Add("iso_8859-3", Latin3); obj.Add("iso_8859-3:1988", Latin3); obj.Add("l3", Latin3); obj.Add("latin3", Latin3); obj.Add("csisolatin4", Latin4); obj.Add("iso-8859-4", Latin4); obj.Add("iso-ir-110", Latin4); obj.Add("iso8859-4", Latin4); obj.Add("iso88594", Latin4); obj.Add("iso_8859-4", Latin4); obj.Add("iso_8859-4:1988", Latin4); obj.Add("l4", Latin4); obj.Add("latin4", Latin4); obj.Add("csisolatincyrillic", Latin5); obj.Add("cyrillic", Latin5); obj.Add("iso-8859-5", Latin5); obj.Add("iso-ir-144", Latin5); obj.Add("iso8859-5", Latin5); obj.Add("iso88595", Latin5); obj.Add("iso_8859-5", Latin5); obj.Add("iso_8859-5:1988", Latin5); Encoding encoding4 = GetEncoding("iso-8859-6"); obj.Add("arabic", encoding4); obj.Add("asmo-708", encoding4); obj.Add("csiso88596e", encoding4); obj.Add("csiso88596i", encoding4); obj.Add("csisolatinarabic", encoding4); obj.Add("ecma-114", encoding4); obj.Add("iso-8859-6", encoding4); obj.Add("iso-8859-6-e", encoding4); obj.Add("iso-8859-6-i", encoding4); obj.Add("iso-ir-127", encoding4); obj.Add("iso8859-6", encoding4); obj.Add("iso88596", encoding4); obj.Add("iso_8859-6", encoding4); obj.Add("iso_8859-6:1987", encoding4); Encoding encoding5 = GetEncoding("iso-8859-7"); obj.Add("csisolatingreek", encoding5); obj.Add("ecma-118", encoding5); obj.Add("elot_928", encoding5); obj.Add("greek", encoding5); obj.Add("greek8", encoding5); obj.Add("iso-8859-7", encoding5); obj.Add("iso-ir-126", encoding5); obj.Add("iso8859-7", encoding5); obj.Add("iso88597", encoding5); obj.Add("iso_8859-7", encoding5); obj.Add("iso_8859-7:1987", encoding5); obj.Add("sun_eu_greek", encoding5); Encoding encoding6 = GetEncoding("iso-8859-8"); obj.Add("csiso88598e", encoding6); obj.Add("csisolatinhebrew", encoding6); obj.Add("hebrew", encoding6); obj.Add("iso-8859-8", encoding6); obj.Add("iso-8859-8-e", encoding6); obj.Add("iso-ir-138", encoding6); obj.Add("iso8859-8", encoding6); obj.Add("iso88598", encoding6); obj.Add("iso_8859-8", encoding6); obj.Add("iso_8859-8:1988", encoding6); obj.Add("visual", encoding6); Encoding encoding7 = GetEncoding("iso-8859-8-i"); obj.Add("csiso88598i", encoding7); obj.Add("iso-8859-8-i", encoding7); obj.Add("logical", encoding7); Encoding encoding8 = GetEncoding("iso-8859-13"); obj.Add("iso-8859-13", encoding8); obj.Add("iso8859-13", encoding8); obj.Add("iso885913", encoding8); Encoding encoding9 = GetEncoding("iso-8859-15"); obj.Add("csisolatin9", encoding9); obj.Add("iso-8859-15", encoding9); obj.Add("iso8859-15", encoding9); obj.Add("iso885915", encoding9); obj.Add("iso_8859-15", encoding9); obj.Add("l9", encoding9); Encoding encoding10 = GetEncoding("koi8-r"); obj.Add("cskoi8r", encoding10); obj.Add("koi", encoding10); obj.Add("koi8", encoding10); obj.Add("koi8-r", encoding10); obj.Add("koi8_r", encoding10); obj.Add("koi8-u", GetEncoding("koi8-u")); Encoding encoding11 = GetEncoding("GB18030", GetEncoding("x-cp20936")); obj.Add("chinese", encoding11); obj.Add("csgb2312", encoding11); obj.Add("csiso58gb231280", encoding11); obj.Add("gb2312", encoding11); obj.Add("gb_2312", encoding11); obj.Add("gb_2312-80", encoding11); obj.Add("gbk", encoding11); obj.Add("iso-ir-58", encoding11); obj.Add("x-gbk", encoding11); obj.Add("hz-gb-2312", GetEncoding("hz-gb-2312")); obj.Add("gb18030", Gb18030); Encoding encoding12 = GetEncoding("x-cp50227"); obj.Add("x-cp50227", encoding12); obj.Add("iso-22-cn", encoding12); obj.Add("big5", Big5); obj.Add("big5-hkscs", Big5); obj.Add("cn-big5", Big5); obj.Add("csbig5", Big5); obj.Add("x-x-big5", Big5); Encoding encoding13 = GetEncoding("iso-2022-jp"); obj.Add("csiso2022jp", encoding13); obj.Add("iso-2022-jp", encoding13); Encoding encoding14 = GetEncoding("iso-2022-kr"); obj.Add("csiso2022kr", encoding14); obj.Add("iso-2022-kr", encoding14); Encoding encoding15 = GetEncoding("iso-2022-cn"); obj.Add("iso-2022-cn", encoding15); obj.Add("iso-2022-cn-ext", encoding15); obj.Add("shift_jis", GetEncoding("shift_jis")); Encoding encoding16 = GetEncoding("euc-jp"); obj.Add("euc-jp", encoding16); Encoding encoding17 = GetEncoding("euc-kr"); obj.Add("euc-kr", encoding17); return obj; } } public readonly struct TextPosition : IEquatable<TextPosition>, IComparable<TextPosition> { public static readonly TextPosition Empty; private readonly ushort _line; private readonly ushort _column; private readonly int _position; public int Line => _line; public int Column => _column; public int Position => _position; public int Index => _position - 1; public TextPosition(ushort line, ushort column, int position) { _line = line; _column = column; _position = position; } public TextPosition Shift(int columns) { return new TextPosition(_line, (ushort)(_column + columns), _position + columns); } public TextPosition After(char chr) { ushort num = _line; ushort num2 = _column; if (chr == '\n') { num++; num2 = 0; } return new TextPosition(num, ++num2, _position + 1); } public TextPosition After(string str) { ushort num = _line; ushort num2 = _column; for (int i = 0; i < str.Length; i++) { if (str[i] == '\n') { num++; num2 = 0; } num2++; } return new TextPosition(num, num2, _position + str.Length); } public override string ToString() { return $"Ln {_line}, Col {_column}, Pos {_position}"; } public override int GetHashCode() { return _position ^ ((_line | _column) + _line); } public override bool Equals(object? obj) { if (obj is TextPosition other) { return Equals(other); } return false; } public bool Equals(TextPosition other) { if (_position == other._position && _column == other._column) { return _line == other._line; } return false; } public static bool operator >(TextPosition a, TextPosition b) { return a._position > b._position; } public static bool operator <(TextPosition a, TextPosition b) { return a._position < b._position; } public int CompareTo(TextPosition other) { if (!Equals(other)) { if (!(this > other)) { return -1; } return 1; } return 0; } } [DebuggerStepThrough] public readonly struct TextRange : IEquatable<TextRange>, IComparable<TextRange> { private readonly TextPosition _start; private readonly TextPosition _end; public TextPosition Start => _start; public TextPosition End => _end; public TextRange(TextPosition start, TextPosition end) { _start = start; _end = end; } public override string ToString() { return $"({_start}) -- ({_end})"; } public override int GetHashCode() { return _end.GetHashCode() ^ _start.GetHashCode(); } public override bool Equals(object? obj) { if (obj is TextRange other) { return Equals(other); } return false; } public bool Equals(TextRange other) { if (_start.Equals(other._start)) { return _end.Equals(other._end); } return false; } public static bool operator >(TextRange a, TextRange b) { return a._start > b._end; } public static bool operator <(TextRange a, TextRange b) { return a._end < b._start; } public int CompareTo(TextRange other) { if (this > other) { return 1; } if (other > this) { return -1; } return 0; } } public sealed class TextSource : ITextSource, IReadOnlyTextSource, IDisposable { private readonly WritableTextSource _writableSource; private readonly IReadOnlyTextSource _readOnlyTextSource; public string Text => _readOnlyTextSource.Text; public int Length => _readOnlyTextSource.Length; public Encoding CurrentEncoding { get { return _readOnlyTextSource.CurrentEncoding; } set { if (_writableSource != null) { _writableSource.CurrentEncoding = value; } } } public int Index { get { return _readOnlyTextSource.Index; } set { _readOnlyTextSource.Index = value; } } public char this[int index] => _readOnlyTextSource[index]; public TextSource(string source) { _writableSource = new WritableTextSource(source); _readOnlyTextSource = _writableSource; } public TextSource(Stream baseStream, Encoding encoding = null) { _writableSource = new WritableTextSource(baseStream, encoding); _readOnlyTextSource = _writableSource; } public TextSource(ReadOnlyMemoryTextSource source) { _writableSource = null; _readOnlyTextSource = source; } public TextSource(CharArrayTextSource source) { _writableSource = null; _readOnlyTextSource = source; } public TextSource(StringTextSource source) { _writableSource = null; _readOnlyTextSource = source; } public char ReadCharacter() { return _readOnlyTextSource.ReadCharacter(); } public string ReadCharacters(int characters) { return _readOnlyTextSource.ReadCharacters(characters); } public StringOrMemory ReadMemory(int characters) { return _readOnlyTextSource.ReadMemory(characters); } public Task PrefetchAsync(int length, CancellationToken cancellationToken) { return _readOnlyTextSource.PrefetchAsync(length, cancellationToken); } public Task PrefetchAllAsync(CancellationToken cancellationToken) { return _readOnlyTextSource.PrefetchAllAsync(cancellationToken); } public bool TryGetContentLength(out int length) { return _readOnlyTextSource.TryGetContentLength(out length); } public void InsertText(string content) { if (_writableSource == null) { throw new InvalidOperationException("Cannot insert text into a read-only text source."); } _writableSource.InsertText(content); } public void Dispose() { _readOnlyTextSource.Dispose(); } public IReadOnlyTextSource GetUnderlyingTextSource() { return _readOnlyTextSource; } } public class TextView { private readonly TextSource _source; private readonly TextRange _range; public TextRange Range => _range; public string Text { get { int num = Math.Max(_range.Start.Position - 1, 0); int num2 = _range.End.Position + 1 - _range.Start.Position; string text = _source.Text; if (num + num2 > text.Length) { num2 = text.Length - num; } return text.Substring(num, num2); } } public TextView(TextSource source, TextRange range) { _source = source; _range = range; } } internal sealed class WritableTextSource : ITextSource, IReadOnlyTextSource, IDisposable { private enum EncodingConfidence : byte { Tentative, Certain, Irrelevant } private const int BufferSize = 4096; private readonly Stream _baseStream; private readonly MemoryStream _raw; private readonly byte[] _buffer; private readonly char[] _chars; private StringBuilder _content; private EncodingConfidence _confidence; private bool _finished; private Encoding _encoding; private Decoder _decoder; private int _index; [MemberNotNull("_content")] public string Text { [MemberNotNull("_content")] get { return _content.ToString(); } } public char this[int index] => Replace(_content[index]); public int Length => _content.Length; public Encoding CurrentEncoding { get { return _encoding; } set { if (_confidence != 0) { return; } if (_encoding.IsUnicode()) { _confidence = EncodingConfidence.Certain; return; } if (value.IsUnicode()) { value = TextEncoding.Utf8; } if (value == _encoding) { _confidence = EncodingConfidence.Certain; return; } _encoding = value; _decoder = value.GetDecoder(); byte[] array = _raw.ToArray(); char[] array2 = new char[_encoding.GetMaxCharCount(array.Length)]; int chars = _decoder.GetChars(array, 0, array.Length, array2, 0); string text = new string(array2, 0, chars); int num = Math.Min(_index, text.Length); if (text.Substring(0, num).Is(_content.ToString(0, num))) { _confidence = EncodingConfidence.Certain; _content.Remove(num, _content.Length - num); _content.Append(text.Substring(num)); return; } _index = 0; _content.Clear().Append(text); throw new NotSupportedException(); } } public int Index { get { return _index; } set { _index = value; } } private WritableTextSource(Encoding encoding, bool allocateBuffers) { if (allocateBuffers) { _buffer = new byte[4096]; _chars = new char[4097]; } _raw = new MemoryStream(); _index = 0; _encoding = encoding ?? TextEncoding.Utf8; _decoder = _encoding.GetDecoder(); } public WritableTextSource(string source) : this(null, TextEncoding.Utf8) { _finished = true; _content.Append(source); _confidence = EncodingConfidence.Irrelevant; } public WritableTextSource(Stream baseStream, Encoding encoding = null) : this(encoding, baseStream != null) { _baseStream = baseStream; _content = StringBuilderPool.Obtain(); _confidence = EncodingConfidence.Tentative; } public void Dispose() { if (_content != null) { _raw.Dispose(); _content.Clear().ReturnToPool(); _content = null; } } public char ReadCharacter() { if (_index < _content.Length) { return Replace(_content[_index++]); } ExpandBuffer(4096L); int num = _index++; if (num >= _content.Length) { return '\uffff'; } return Replace(_content[num]); } public string ReadCharacters(int characters) { int index = _index; if (index + characters <= _content.Length) { _index += characters; return _content.ToString(index, characters); } ExpandBuffer(Math.Max(4096, characters)); _index += characters; characters = Math.Min(characters, _content.Length - index); return _content.ToString(index, characters); } public StringOrMemory ReadMemory(int characters) { return new StringOrMemory(ReadCharacters(characters)); } public Task PrefetchAsync(int length, CancellationToken cancellationToken) { return ExpandBufferAsync(length, cancellationToken); } public async Task PrefetchAllAsync(CancellationToken cancellationToken) { if (_baseStream != null && _content.Length == 0) { await DetectByteOrderMarkAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } while (!_finished) { await ReadIntoBufferAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } public bool TryGetContentLength(out int length) { length = 0; return false; } public void InsertText(string content) { if (_index >= 0 && _index < _content.Length) { _content.Insert(_index, content); } else { _content.Append(content); } _index += content.Length; } private static char Replace(char c) { if (c != '\uffff') { return c; } return '\ufffd'; } private async Task DetectByteOrderMarkAsync(CancellationToken cancellationToken) { int num = await _baseStream.ReadAsync(_buffer, 0, 4096).ConfigureAwait(continueOnCapturedContext: false); int num2 = 0; if (num > 2 && _buffer[0] == 239 && _buffer[1] == 187 && _buffer[2] == 191) { _encoding = TextEncoding.Utf8; num2 = 3; } else if (num > 3 && _buffer[0] == byte.MaxValue && _buffer[1] == 254 && _buffer[2] == 0 && _buffer[3] == 0) { _encoding = TextEncoding.Utf32Le; num2 = 4; } else if (num > 3 && _buffer[0] == 0 && _buffer[1] == 0 && _buffer[2] == 254 && _buffer[3] == byte.MaxValue) { _encoding = TextEncoding.Utf32Be; num2 = 4; } else if (num > 1 && _buffer[0] == 254 && _buffer[1] == byte.MaxValue) { _encoding = TextEncoding.Utf16Be; num2 = 2; } else if (num > 1 && _buffer[0] == byte.MaxValue && _buffer[1] == 254) { _encoding = TextEncoding.Utf16Le; num2 = 2; } else if (num > 3 && _buffer[0] == 132 && _buffer[1] == 49 && _buffer[2] == 149 && _buffer[3] == 51) { _encoding = TextEncoding.Gb18030; num2 = 4; } if (num2 > 0) { num -= num2; Array.Copy(_buffer, num2, _buffer, 0, num); _decoder = _encoding.GetDecoder(); _confidence = EncodingConfidence.Certain; } AppendContentFromBuffer(num); } private async Task ExpandBufferAsync(long size, CancellationToken cancellationToken) { if (!_finished && _content.Length == 0) { await DetectByteOrderMarkAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } while (!_finished && size + _index > _content.Length) { await ReadIntoBufferAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } private async Task ReadIntoBufferAsync(CancellationToken cancellationToken) { AppendContentFromBuffer(await _baseStream.ReadAsync(_buffer, 0, 4096, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); } private void ExpandBuffer(long size) { if (!_finished && _content.Length == 0) { DetectByteOrderMarkAsync(CancellationToken.None).Wait(); } while (!_finished && size + _index > _content.Length) { ReadIntoBuffer(); } } private void ReadIntoBuffer() { int size = _baseStream.Read(_buffer, 0, 4096); AppendContentFromBuffer(size); } private void AppendContentFromBuffer(int size) { _finished = size == 0; int chars = _decoder.GetChars(_buffer, 0, size, _chars, 0); if (_confidence != EncodingConfidence.Certain) { _raw.Write(_buffer, 0, size); } _content.Append(_chars, 0, chars); } } public static class XmlExtensions { public static bool IsPubidChar(this char c) { if (!c.IsAlphanumericAscii() && c != '-' && c != '\'' && c != '+' && c != ',' && c != '.' && c != '/' && c != ':' && c != '?' && c != '=' && c != '!' && c != '*' && c != '#' && c != '@' && c != '$' && c != '_' && c != '(' && c != ')' && c != ';' && c != '%') { return c.IsSpaceCharacter(); } return true; } public static bool IsXmlNameStart(this char c) { if (!c.IsLetter() && c != ':' && c != '_' && !c.IsInRange(192, 214) && !c.IsInRange(216, 246) && !c.IsInRange(248, 767) && !c.IsInRange(880, 893) && !c.IsInRange(895, 8191) && !c.IsInRange(8204, 8205) && !c.IsInRange(8304, 8591) && !c.IsInRange(11264, 12271) && !c.IsInRange(12289, 55295) && !c.IsInRange(63744, 64975) && !c.IsInRange(65008, 65533)) { return c.IsInRange(65536, 983039); } return true; } public static bool IsXmlName(this char c) { if (!c.IsXmlNameStart() && !c.IsDigit() && c != '-' && c != '.' && c != '·' && !c.IsInRange(768, 879)) { return c.IsInRange(8255, 8256); } return true; } public static bool IsXmlName(this string str) { return new StringOrMemory(str).IsXmlName(); } public static bool IsXmlName(this StringOrMemory str) { if (str.Length > 0 && str[0].IsXmlNameStart()) { for (int i = 1; i < str.Length; i++) { if (!str[i].IsXmlName()) { return false; } } return true; } return false; } public static bool IsQualifiedName(this string str) { return new StringOrMemory(str).IsQualifiedName(); } public static bool IsQualifiedName(this StringOrMemory str) { int num = str.Memory.Span.IndexOf(':'); if (num == -1) { return str.IsXmlName(); } if (num > 0 && str[0].IsXmlNameStart()) { for (int i = 1; i < num; i++) { if (!str[i].IsXmlName()) { return false; } } num++; } if (str.Length > num && str[num++].IsXmlNameStart()) { for (int j = num; j < str.Length; j++) { if (str[j] == ':' || !str[j].IsXmlName()) { return false; } } return true; } return false; } public static bool IsXmlChar(this char chr) { if (chr != '\t' && chr != '\n' && chr != '\r' && (chr < ' ' || chr > '\ud7ff')) { if (chr >= '\ue000') { return chr <= '\ufffd'; } return false; } return true; } public static bool IsValidAsCharRef(this int chr) { if (chr != 9 && chr != 10 && chr != 13 && (chr < 32 || chr > 55295) && (chr < 57344 || chr > 65533)) { if (chr >= 65536) { return chr <= 1114111; } return false; } return true; } } } namespace AngleSharp.Svg { internal sealed class SvgElementFactory : IElementFactory<Document, SvgElement> { private delegate SvgElement Creator(Document owner, string? prefix); private readonly Dictionary<string, Creator> creators = new Dictionary<string, Creator>(StringComparer.OrdinalIgnoreCase) { { TagNames.Svg, (Document document, string? prefix) => new SvgSvgElement(document, prefix) }, { TagNames.Circle, (Document document, string? prefix) => new SvgCircleElement(document, prefix) }, { TagNames.Desc, (Document document, string? prefix) => new SvgDescElement(document, prefix) }, { TagNames.ForeignObject, (Document document, string? prefix) => new SvgForeignObjectElement(document, prefix) }, { TagNames.Title, (Document document, string? prefix) => new SvgTitleElement(document, prefix) } }; internal static readonly SvgElementFactory Instance = new SvgElementFactory(); public SvgElement Create(Document document, string localName, string? prefix = null, NodeFlags flags = NodeFlags.None) { if (creators.TryGetValue(localName, out Creator value)) { return value(document, prefix); } return new SvgElement(document, localName, prefix, flags); } } } namespace AngleSharp.Svg.Dom { internal sealed class SvgCircleElement : SvgElement, ISvgCircleElement, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { public SvgCircleElement(Document owner, string? prefix = null) : base(owner, TagNames.Circle, prefix) { } } internal sealed class SvgDescElement : SvgElement, ISvgDescriptionElement, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { public SvgDescElement(Document owner, string? prefix = null) : base(owner, TagNames.Desc, prefix, NodeFlags.Special | NodeFlags.Scoped | NodeFlags.HtmlTip) { } } public class SvgElement : Element, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode, IConstructableSvgElement, IConstructableElement, IConstructableNode { public SvgElement(Document owner, string name, string? prefix = null, NodeFlags flags = NodeFlags.None) : base(owner, name, prefix, NamespaceNames.SvgUri, flags | NodeFlags.SvgMember) { } public override IElement ParseSubtree(string html) { return this.ParseHtmlSubtree(html); } public override Node Clone(Document owner, bool deep) { SvgElement svgElement = base.Context.GetFactory<IElementFactory<Document, SvgElement>>().Create(owner, base.LocalName, base.Prefix); CloneElement(svgElement, owner, deep); return svgElement; } } internal sealed class SvgForeignObjectElement : SvgElement, ISvgForeignObjectElement, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { public SvgForeignObjectElement(Document owner, string? prefix = null) : base(owner, TagNames.ForeignObject, prefix, NodeFlags.Special | NodeFlags.Scoped | NodeFlags.
Microsoft.Bcl.AsyncInterfaces.dll
Decompiled 2 months 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(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [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("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("8.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(); } } }
Newtonsoft.Json.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")] [assembly: CLSCompliant(true)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyFileVersion("13.0.3.27908")] [assembly: AssemblyInformationalVersion("13.0.3+0a2e291c0d9c0c7675d445703e51750363a549ef")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET .NET 4.5")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("13.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } } namespace Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } public class DefaultJsonNameTable : JsonNameTable { private class Entry { internal readonly string Value; internal readonly int HashCode; internal Entry Next; internal Entry(string value, int hashCode, Entry next) { Value = value; HashCode = hashCode; Next = next; } } private static readonly int HashCodeRandomizer; private int _count; private Entry[] _entries; private int _mask = 31; static DefaultJsonNameTable() { HashCodeRandomizer = Environment.TickCount; } public DefaultJsonNameTable() { _entries = new Entry[_mask + 1]; } public override string? Get(char[] key, int start, int length) { if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; num += (num << 7) ^ key[start]; int num2 = start + length; for (int i = start + 1; i < num2; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; int num3 = Volatile.Read(ref _mask); int num4 = num & num3; for (Entry entry = _entries[num4]; entry != null; entry = entry.Next) { if (entry.HashCode == num && TextEquals(entry.Value, key, start, length)) { return entry.Value; } } return null; } public string Add(string key) { if (key == null) { throw new ArgumentNullException("key"); } int length = key.Length; if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; for (int i = 0; i < key.Length; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal)) { return entry.Value; } } return AddEntry(key, num); } private string AddEntry(string str, int hashCode) { int num = hashCode & _mask; Entry entry = new Entry(str, hashCode, _entries[num]); _entries[num] = entry; if (_count++ == _mask) { Grow(); } return entry.Value; } private void Grow() { Entry[] entries = _entries; int num = _mask * 2 + 1; Entry[] array = new Entry[num + 1]; for (int i = 0; i < entries.Length; i++) { Entry entry = entries[i]; while (entry != null) { int num2 = entry.HashCode & num; Entry next = entry.Next; entry.Next = array[num2]; array[num2] = entry; entry = next; } } _entries = array; Volatile.Write(ref _mask, num); } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) { return false; } for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) { return false; } } return true; } } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[]? array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type? _namingStrategyType; private object[]? _namingStrategyParameters; public string? Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[]? NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy? NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings>? DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } private static string ToStringInternal(BigInteger value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (StringUtils.IndexOf(text, '.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri? value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string? value) { return ToString(value, '"'); } public static string ToString(string? value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object? value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } [DebuggerStepThrough] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } [DebuggerStepThrough] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } [DebuggerStepThrough] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (settings == null || !settings.CheckAdditionalContent) { return; } while (jsonReader.Read()) { if (jsonReader.TokenType != JsonToken.Comment) { throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object."); } } } public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); return SerializeObject(node, formatting, xmlNodeConverter); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter); } public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, omitRootObject: false); } public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter); } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } public abstract class JsonConverter<T> : JsonConverter { public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } WriteJson(writer, (T)value, serializer); } public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool flag = existingValue == null; if (!flag && !(existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer); } public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); public sealed override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[]? ConverterParameters { get; } public JsonConverterAttribute(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception? innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } public abstract class JsonNameTable { public abstract string? Get(char[] key, int start, int length); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal MissingMemberHandling? _missingMemberHandling; internal Required? _itemRequired; internal NullValueHandling? _itemNullValueHandling; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public NullValueHandling ItemNullValueHandling { get { return _itemNullValueHandling.GetValueOrDefault(); } set { _itemNullValueHandling = value; } } public Required ItemRequired { get { return _itemRequired.GetValueOrDefault(); } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; internal JsonContainerType Type; internal int Position; internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); if (writer == null) { writer = new StringWriter(sb); } JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); sb.Append("']"); } else { if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); } break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); StringWriter writer = null; char[] buffer = null; if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder, ref writer, ref buffer); } } currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get; set; } public object[]? NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public int Order { get { return _order.GetValueOrDefault(); } set { _order = value; } } public Required Required { get { return _required.GetValueOrDefault(); } set { _required = value; } } public string? PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object? _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo? _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string? _dateFormatString; private List<JsonPosition>? _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string? DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object? Value => _value; public virtual Type? ValueType => _value?.GetType(); public virtual int Depth { get { int num = _stack?.Count ?? 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync(); } public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (TokenType == JsonToken.PropertyName) { await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth) { } } } internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken) { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { throw CreateUnexpectedEndException(); } } public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean()); } public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes()); } internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) { List<byte> buffer = new List<byte>(); do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(buffer)); byte[] array = buffer.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime()); } public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset()); } public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal()); } public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(ReadAsDouble()); } public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32()); } public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString()); } internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken) { bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (flag) { flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } return flag; } internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken) { JsonToken tokenType = TokenType; if (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { return MoveToContentFromNonContentAsync(cancellationToken); } return AsyncUtils.True; } private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken) { JsonToken tokenType; do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { return false; } tokenType = TokenType; } while (tokenType == JsonToken.None || tokenType == JsonToken.Comment); return true; } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; _maxDepth = 64; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth) { return; } _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is int) { return (int)value; } int num; if (value is BigInteger bigInteger) { num = (int)bigInteger; } else { try { num = Convert.ToInt32(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Integer, num, updateIndex: false); return num; } case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string? ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken)) { object value = Value; if (value != null) { string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture)); SetToken(JsonToken.String, text, updateIndex: false); return text; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[]? ReadAsBytes() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.StartObject: { ReadIntoWrappedTypeObject(); byte[] array2 = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (Value is Guid guid) { byte[] array = guid.ToByteArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); do { if (!Read()) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(list)); byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer) { switch (TokenType) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); return false; case JsonToken.EndArray: return true; case JsonToken.Comment: return false; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is double) { return (double)value; } double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger)); SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L)); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is decimal) { return (decimal)value; } decimal num; if (value is BigInteger bigInteger) { num = (decimal)bigInteger; } else { try { num = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset dateTimeOffset) { SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: return ReadDateTimeString((string)Value); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime dateTime) { SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value != null && Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value) { SetToken(newToken, value, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { _currentState = ((!SupportMultipleContent) ? State.Finished : State.Start); } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadForType(JsonContract? contract, bool hasConverter) { if (hasConverter) { return Read(); } switch (contract?.InternalReadType ?? ReadType.Read) { case ReadType.Read: return ReadAndMoveToContent(); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: { bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long))); } return result; } case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; default: throw new ArgumentOutOfRangeException(); } return TokenType != JsonToken.None; } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, path, lineNumber, linePosition, ex); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonSerializationException(message, path, lineNumber, linePosition, ex); } } public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection? _converters; internal IContractResolver _contractResolver; internal ITraceWriter? _traceWriter; internal IEqualityComparer? _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver? _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string? _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver? ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder is SerializationBinder result) { return result; } if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter) { return serializationBinderAdapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value); } } public virtual ISerializationBinder SerializationBinder { get { return _serializationBinder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = value; } } public virtual ITraceWriter? TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer? EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling; } set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting.GetValueOrDefault(); } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling.GetValueOrDefault(); } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling.GetValueOrDefault(); } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling.GetValueOrDefault(); } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling.GetValueOrDefault(); } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent.GetValueOrDefault(); } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling.HasValue) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } [DebuggerStepThrough] public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } [DebuggerStepThrough] public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader) { return Deserialize(reader, null); } [DebuggerStepThrough] public object? Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } [DebuggerStepThrough] public T? Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader, Type? objectType) { return DeserializeInternal(reader, objectType); } internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable(); } } private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable()) { jsonTextReader.PropertyNameTable = null; } } public void Serialize(TextWriter textWriter, object? value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object? value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object? value) { SerializeInternal(jsonWriter, value, null); } private TraceJsonReader CreateTraceJsonReader(JsonReader reader) { TraceJsonReader traceJsonReader = new TraceJsonReader(reader); if (reader.TokenType != 0) { traceJsonReader.WriteCurrentToken(); } return traceJsonReader; } internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? dateTimeZoneHandling = null; if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? floatFormatHandling = null; if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling) { floatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? stringEscapeHandling = null; if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { stringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo cultureInfo = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { cultureInfo = jsonWriter.Culture; jsonWriter.Culture = _culture; } string dateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { dateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null); new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } if (formatting.HasValue) { jsonWriter.Formatting = formatting.GetValueOrDefault(); } if (dateFormatHandling.HasValue) { jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault(); } if (dateTimeZoneHandling.HasValue) { jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault(); } if (floatFormatHandling.HasValue) { jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault(); } if (stringEscapeHandling.HasValue) { jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = dateFormatString; } if (cultureInfo != null) { jsonWriter.Culture = cultureInfo; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter? GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType) { if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (jsonConverter.CanConvert(objectType)) { return jsonConverter; } } } return null; } internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e) { this.Error?.Invoke(this, e); } } public class JsonSerializerSettings { internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; internal static readonly StreamingContext DefaultContext; internal const Formatting DefaultFormatting = Formatting.None; internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple; internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; internal const int DefaultMaxDepth = 64; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; internal DateTimeZoneHandling? _dateTimeZoneHandling; internal DateParseHandling? _dateParseHandling; internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; internal CultureInfo? _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; internal string? _dateFormatString; internal bool _dateFormatStringSet; internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling; internal DefaultValueHandling? _defaultValueHandling; internal PreserveReferencesHandling? _preserveReferencesHandling; internal NullValueHandling? _nullValueHandling; internal ObjectCreationHandling? _objectCreationHandling; internal MissingMemberHandling? _missingMemberHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal StreamingContext? _context; internal ConstructorHandling? _constructorHandling; internal TypeNameHandling? _typeNameHandling; internal MetadataPropertyHandling? _metadataPropertyHandling; public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public IList<JsonConverter> Converters { get; set; } public PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling.GetValueOrDef
SoundCloudExplode.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Management; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using SoundCloudExplode.Bridge; using SoundCloudExplode.Common; using SoundCloudExplode.Exceptions; using SoundCloudExplode.Playlists; using SoundCloudExplode.Search; using SoundCloudExplode.Tracks; using SoundCloudExplode.Users; using SoundCloudExplode.Utils; using SoundCloudExplode.Utils.Extensions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.6.1", FrameworkDisplayName = ".NET Framework 4.6.1")] [assembly: AssemblyCompany("Jerro")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (C) Jerry Berry")] [assembly: AssemblyDescription("Library that provides an interface to query metadata of SoundCloud tracks and playlists, as well as to resolve and download audio.")] [assembly: AssemblyFileVersion("1.6.5.0")] [assembly: AssemblyInformationalVersion("1.6.5+67cf7466c0a737178b8374b1d5ef03f9849c8838")] [assembly: AssemblyProduct("SoundCloudExplode")] [assembly: AssemblyTitle("SoundCloudExplode")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/jerry08/SoundCloudExplode")] [assembly: AssemblyVersion("1.6.5.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class PolyfillExtensions { public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { HttpResponseMessage obj = await httpClient.GetAsync(requestUri, (HttpCompletionOption)1, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); obj.EnsureSuccessStatusCode(); return await obj.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await httpClient.GetStreamAsync(requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { HttpResponseMessage response = await httpClient.GetAsync(requestUri, (HttpCompletionOption)1, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); try { response.EnsureSuccessStatusCode(); return await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } finally { ((IDisposable)response)?.Dispose(); } } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await httpClient.GetByteArrayAsync(requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> GetStringAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { HttpResponseMessage response = await httpClient.GetAsync(requestUri, (HttpCompletionOption)1, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); try { response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } finally { ((IDisposable)response)?.Dispose(); } } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<string> GetStringAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await httpClient.GetStringAsync(requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<Stream> ReadAsStreamAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> ReadAsByteArrayAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsByteArrayAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> ReadAsStringAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken)) { TaskCompletionSource<object?> tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); try { process.EnableRaisingEvents = true; } catch when (process.HasExited) { return; } process.Exited += HandleExited; try { using (cancellationToken.Register(delegate { tcs.TrySetCanceled(cancellationToken); })) { await tcs.Task; } } finally { process.Exited -= HandleExited; } void HandleExited(object? sender, EventArgs args) { tcs.TrySetResult(null); } } public static bool IsAssignableTo(this Type type, Type? otherType) { return otherType?.IsAssignableFrom(type) ?? false; } public static string ReplaceLineEndings(this string str, string replacementText) { return Replace(Replace(Replace(str, "\r\n", "\n", StringComparison.Ordinal), "\r", "\n", StringComparison.Ordinal), "\n", replacementText, StringComparison.Ordinal); } public static string ReplaceLineEndings(this string str) { return ReplaceLineEndings(str, Environment.NewLine); } public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } } public static async Task WaitAsync(this Task task, CancellationToken cancellationToken) { await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitAsync(this Task task, TimeSpan timeout) { await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } return task.Result; } public static async Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken) { return await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout) { return await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = stream.Read(buffer, i, Math.Min(minimumBytes, buffer.Length - i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, byte[] buffer, int offset, int count) { int num; for (int i = 0; i < count; i += num) { num = stream.Read(buffer, offset + i, count - i); if (num <= 0) { throw new EndOfStreamException(); } } } public static void ReadExactly(this Stream stream, byte[] buffer) { stream.ReadExactly(buffer, 0, buffer.Length); } public static async Task<int> ReadAtLeastAsync(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int num; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += num) { num = await stream.ReadAsync(buffer, totalBytesRead, Math.Min(minimumBytes, buffer.Length - totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) { int num; for (int totalBytesRead = 0; totalBytesRead < count; totalBytesRead += num) { num = await stream.ReadAsync(buffer, offset + totalBytesRead, count - totalBytesRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { throw new EndOfStreamException(); } } } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { await stream.ReadExactlyAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, Span<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = Read(stream, buffer.Slice(i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, Span<byte> buffer) { byte[] array = buffer.ToArray(); stream.ReadExactly(array, 0, array.Length); array.CopyTo(buffer); } public static async Task<int> ReadAtLeastAsync(this Stream stream, Memory<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int num; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += num) { num = await ReadAsync(stream, buffer.Slice(totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { byte[] bufferArray = buffer.ToArray(); await stream.ReadExactlyAsync(bufferArray, 0, bufferArray.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); bufferArray.CopyTo(buffer); } public static Task CancelAsync(this CancellationTokenSource cts) { cts.Cancel(); return Task.CompletedTask; } public static void Deconstruct(this DictionaryEntry entry, out object key, out object? value) { key = entry.Key; value = entry.Value; } public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } public static IEnumerable<Match> AsEnumerable(this MatchCollection matchCollection) { return matchCollection.Cast<Match>(); } public static IEnumerator<Match> GetEnumerator(this MatchCollection matchCollection) { return matchCollection.AsEnumerable().GetEnumerator(); } public static Match[] ToArray(this MatchCollection matchCollection) { return matchCollection.AsEnumerable().ToArray(); } public static bool StartsWith(this string str, char c) { if (str.Length > 0) { return str[0] == c; } return false; } public static bool EndsWith(this string str, char c) { if (str.Length > 0) { return str[str.Length - 1] == c; } return false; } public static bool Contains(this string str, char c) { return str.IndexOf(c) >= 0; } public static string Replace(this string str, string oldValue, string? newValue, StringComparison comparison) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; int num2 = 0; while (true) { num = str.IndexOf(oldValue, num, comparison); if (num < 0) { break; } stringBuilder.Append(str, num2, num - num2); stringBuilder.Append(newValue); num += oldValue.Length; num2 = num; } stringBuilder.Append(str, num2, str.Length - num2); return stringBuilder.ToString(); } public static string Replace(this string str, string oldValue, string? newValue, bool ignoreCase, CultureInfo? culture) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; int num2 = 0; while (true) { num = (culture ?? CultureInfo.CurrentCulture).CompareInfo.IndexOf(str, oldValue, num, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); if (num < 0) { break; } stringBuilder.Append(str, num2, num - num2); stringBuilder.Append(newValue); num += oldValue.Length; num2 = num; } stringBuilder.Append(str, num2, str.Length - num2); return stringBuilder.ToString(); } public static string[] Split(this string str, char separator, int count, StringSplitOptions options = StringSplitOptions.None) { return str.Split(new char[1] { separator }, count, options); } public static string[] Split(this string str, char separator, StringSplitOptions options = StringSplitOptions.None) { return str.Split(new char[1] { separator }, options); } public static string[] Split(this string str, string? separator, int count, StringSplitOptions options = StringSplitOptions.None) { return str.Split(new string[1] { separator ?? "" }, count, options); } public static string[] Split(this string str, string? separator, StringSplitOptions options = StringSplitOptions.None) { return str.Split(new string[1] { separator ?? "" }, options); } public static void NextBytes(this Random random, Span<byte> buffer) { byte[] array = buffer.ToArray(); random.NextBytes(array); array.CopyTo(buffer); } public static int Read(this Stream stream, byte[] buffer) { return stream.Read(buffer, 0, buffer.Length); } public static void Write(this Stream stream, byte[] buffer) { stream.Write(buffer, 0, buffer.Length); } public static async Task CopyToAsync(this Stream stream, Stream destination, CancellationToken cancellationToken = default(CancellationToken)) { await stream.CopyToAsync(destination, 81920, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<int> ReadAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { return await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task WriteAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { await stream.WriteAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static int Read(this Stream stream, Span<byte> buffer) { byte[] array = buffer.ToArray(); int result = stream.Read(array, 0, array.Length); array.CopyTo(buffer); return result; } public static void Write(this Stream stream, ReadOnlySpan<byte> buffer) { byte[] array = buffer.ToArray(); stream.Write(array, 0, array.Length); } public static async Task<int> ReadAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { byte[] bufferArray = buffer.ToArray(); int result = await stream.ReadAsync(bufferArray, 0, bufferArray.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); bufferArray.CopyTo(buffer); return result; } public static async Task WriteAsync(this Stream stream, ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { byte[] array = buffer.ToArray(); await stream.WriteAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static int Read(this StreamReader reader, char[] buffer) { return reader.Read(buffer, 0, buffer.Length); } public static async Task<int> ReadAsync(this StreamReader reader, char[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(continueOnCapturedContext: false); } public static int Read(this StreamReader reader, Span<char> buffer) { char[] array = buffer.ToArray(); int result = reader.Read(array, 0, array.Length); array.CopyTo(buffer); return result; } public static async Task<int> ReadAsync(this StreamReader reader, Memory<char> buffer, CancellationToken cancellationToken = default(CancellationToken)) { char[] bufferArray = buffer.ToArray(); cancellationToken.ThrowIfCancellationRequested(); int result = await reader.ReadAsync(bufferArray, 0, bufferArray.Length).ConfigureAwait(continueOnCapturedContext: false); bufferArray.CopyTo(buffer); return result; } public static void Write(this StreamWriter writer, ReadOnlySpan<char> buffer) { char[] array = buffer.ToArray(); writer.Write(array, 0, array.Length); } public static async Task WriteAsync(this StreamWriter writer, Memory<char> buffer, CancellationToken cancellationToken = default(CancellationToken)) { char[] array = buffer.ToArray(); cancellationToken.ThrowIfCancellationRequested(); await writer.WriteAsync(array, 0, array.Length).ConfigureAwait(continueOnCapturedContext: false); } public static bool Contains(this string str, char c, StringComparison comparison) { return Contains(str, c.ToString(), comparison); } public static bool Contains(this string str, string sub, StringComparison comparison) { return str.IndexOf(sub, comparison) >= 0; } private static void KillProcessTree(int processId) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown ManagementObjectSearcher val = new ManagementObjectSearcher($"SELECT * FROM Win32_Process WHERE ParentProcessID={processId}"); try { ManagementObjectCollection val2 = val.Get(); try { try { using Process process = Process.GetProcessById(processId); if (!process.HasExited) { process.Kill(); } } catch { } foreach (ManagementObject item in ((IEnumerable)val2).Cast<ManagementObject>()) { KillProcessTree(Convert.ToInt32(((ManagementBaseObject)item)["ProcessID"])); } } finally { ((IDisposable)val2)?.Dispose(); } } finally { ((IDisposable)val)?.Dispose(); } } public static void Kill(this Process process, bool entireProcessTree) { if (!entireProcessTree) { process.Kill(); } else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { process.Kill(); } else { KillProcessTree(process.Id); } } } namespace SoundCloudExplode { public static class Constants { public const string ClientId = "wDSKS1Bp8WmdlRPkZ7NQXGs67PMXl2Nd"; public const string ResolveEndpoint = "https://api-v2.soundcloud.com/resolve"; public const string TrackEndpoint = "https://api-v2.soundcloud.com/tracks"; public const int DefaultOffset = 0; public const int DefaultLimit = 50; public const int MinLimit = 0; public const int MaxLimit = 200; } public class SoundCloudClient { private readonly HttpClient _http; private readonly SoundcloudEndpoint _endpoint; private readonly string BaseUrl = "https://soundcloud.com"; public string ClientId { get; set; } public bool IsInitialized { get; private set; } public SearchClient Search { get; } public TrackClient Tracks { get; } public PlaylistClient Playlists { get; } public UserClient Users { get; } public SoundCloudClient(string clientId, HttpClient http) { ClientId = clientId; _http = http; _endpoint = new SoundcloudEndpoint(http) { ClientId = clientId }; Search = new SearchClient(http, _endpoint); Tracks = new TrackClient(http, _endpoint); Playlists = new PlaylistClient(http, _endpoint); Users = new UserClient(http, _endpoint); } public SoundCloudClient() : this("wDSKS1Bp8WmdlRPkZ7NQXGs67PMXl2Nd", Http.Client) { } public SoundCloudClient(HttpClient http) : this("wDSKS1Bp8WmdlRPkZ7NQXGs67PMXl2Nd", http) { } public SoundCloudClient(string clientId) : this(clientId, Http.Client) { } public async Task InitializeAsync(CancellationToken cancellationToken = default(CancellationToken)) { ClientId = await GetClientIdAsync(cancellationToken); _endpoint.ClientId = ClientId; IsInitialized = true; } public async Task<string> GetClientIdAsync(CancellationToken cancellationToken = default(CancellationToken)) { string text = Regex.Matches(await _http.ExecuteGetAsync(BaseUrl, cancellationToken), "<script.*?src=\"(.*?)\"").Cast<Match>().LastOrDefault()?.Groups[1].Value; if (string.IsNullOrEmpty(text)) { return string.Empty; } return (await _http.ExecuteGetAsync(text, cancellationToken)).Split(new string[1] { ",client_id" }, StringSplitOptions.None)[1].Split(new char[1] { '"' })[1]; } public async Task<Kind> GetUrlKindAsync(string url, CancellationToken cancellationToken = default(CancellationToken)) { string obj = await _endpoint.ResolveUrlAsync(url, cancellationToken); if (string.IsNullOrWhiteSpace(obj)) { throw new SoundcloudExplodeException("Failed to resolve url."); } return JsonSerializer.Deserialize<Kind>(JsonNode.Parse(obj, (JsonNodeOptions?)null, default(JsonDocumentOptions))["kind"], SourceGenerationContext.Default.Kind); } public async ValueTask DownloadAsync(Track track, string filePath, IProgress<double>? progress = null, Dictionary<string, string>? headers = null, CancellationToken cancellationToken = default(CancellationToken)) { string text = await Tracks.GetDownloadUrlAsync(track, cancellationToken); if (text == null) { return; } string directoryName = Path.GetDirectoryName(filePath); if (directoryName == null) { return; } if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } using FileStream destination = File.Create(filePath); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, text); if (headers != null) { foreach (var (text4, text5) in headers) { ((HttpHeaders)request.Headers).TryAddWithoutValidation(text4, text5); } } HttpResponseMessage val = await _http.SendAsync(request, (HttpCompletionOption)1, cancellationToken); if (!val.IsSuccessStatusCode) { throw new HttpRequestException($"Response status code does not indicate success: {(int)val.StatusCode} ({val.StatusCode})." + Environment.NewLine + "Request:" + Environment.NewLine + (object)request); } await StreamExtensions.CopyToAsync(totalLength: val.Content.Headers.ContentLength.GetValueOrDefault(), source: await val.Content.ReadAsStreamAsync(cancellationToken), destination: destination, progress: progress, bufferSize: 4096, cancellationToken: cancellationToken); } } [JsonSourceGenerationOptions(UseStringEnumConverter = true)] [JsonSerializable(typeof(Track))] [JsonSerializable(typeof(Playlist))] [JsonSerializable(typeof(User))] [JsonSerializable(typeof(List<Track>))] [JsonSerializable(typeof(List<Playlist>))] [JsonSerializable(typeof(TrackSearchResult))] [JsonSerializable(typeof(PlaylistSearchResult))] [JsonSerializable(typeof(UserSearchResult))] [GeneratedCode("System.Text.Json.SourceGeneration", "8.0.10.31311")] internal class SourceGenerationContext : JsonSerializerContext, IJsonTypeInfoResolver { private JsonTypeInfo<bool>? _Boolean; private JsonTypeInfo<Kind>? _Kind; private JsonTypeInfo<CreatorSubscription>? _CreatorSubscription; private JsonTypeInfo<Playlist>? _Playlist; private JsonTypeInfo<Product>? _Product; private JsonTypeInfo<Visual>? _Visual; private JsonTypeInfo<Visuals>? _Visuals; private JsonTypeInfo<PlaylistSearchResult>? _PlaylistSearchResult; private JsonTypeInfo<TrackSearchResult>? _TrackSearchResult; private JsonTypeInfo<UserSearchResult>? _UserSearchResult; private JsonTypeInfo<Format>? _Format; private JsonTypeInfo<Media>? _Media; private JsonTypeInfo<PublisherMetadata>? _PublisherMetadata; private JsonTypeInfo<Track>? _Track; private JsonTypeInfo<Transcoding>? _Transcoding; private JsonTypeInfo<Badges>? _Badges; private JsonTypeInfo<PlaylistUser>? _PlaylistUser; private JsonTypeInfo<User>? _User; private JsonTypeInfo<List<CreatorSubscription>>? _ListCreatorSubscription; private JsonTypeInfo<List<Playlist>>? _ListPlaylist; private JsonTypeInfo<List<Visual>>? _ListVisual; private JsonTypeInfo<List<Track>>? _ListTrack; private JsonTypeInfo<List<Transcoding>>? _ListTranscoding; private JsonTypeInfo<DateTimeOffset>? _DateTimeOffset; private JsonTypeInfo<DateTimeOffset?>? _NullableDateTimeOffset; private JsonTypeInfo<Uri>? _Uri; private JsonTypeInfo<long>? _Int64; private JsonTypeInfo<long?>? _NullableInt64; private JsonTypeInfo<object>? _Object; private JsonTypeInfo<string>? _String; private static readonly JsonSerializerOptions s_defaultOptions = new JsonSerializerOptions(); private static readonly JsonEncodedText PropName_product = JsonEncodedText.Encode("product", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_id = JsonEncodedText.Encode("id", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_urn = JsonEncodedText.Encode("urn", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_entry_time = JsonEncodedText.Encode("entry_time", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_visual_url = JsonEncodedText.Encode("visual_url", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_Url = JsonEncodedText.Encode("Url", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_Title = JsonEncodedText.Encode("Title", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_avatar_url = JsonEncodedText.Encode("avatar_url", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_first_name = JsonEncodedText.Encode("first_name", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_full_name = JsonEncodedText.Encode("full_name", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_kind = JsonEncodedText.Encode("kind", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_last_modified = JsonEncodedText.Encode("last_modified", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_last_name = JsonEncodedText.Encode("last_name", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_permalink = JsonEncodedText.Encode("permalink", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_permalink_url = JsonEncodedText.Encode("permalink_url", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_uri = JsonEncodedText.Encode("uri", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_username = JsonEncodedText.Encode("username", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_verified = JsonEncodedText.Encode("verified", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_city = JsonEncodedText.Encode("city", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_country_code = JsonEncodedText.Encode("country_code", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_badges = JsonEncodedText.Encode("badges", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_protocol = JsonEncodedText.Encode("protocol", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_mime_type = JsonEncodedText.Encode("mime_type", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_transcodings = JsonEncodedText.Encode("transcodings", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_artist = JsonEncodedText.Encode("artist", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_contains_music = JsonEncodedText.Encode("contains_music", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_url = JsonEncodedText.Encode("url", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_preset = JsonEncodedText.Encode("preset", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_duration = JsonEncodedText.Encode("duration", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_snipped = JsonEncodedText.Encode("snipped", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_format = JsonEncodedText.Encode("format", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_quality = JsonEncodedText.Encode("quality", (JavaScriptEncoder)null); private static readonly JsonEncodedText PropName_pro_unlimited = JsonEncodedText.Encode("pro_unlimited", (JavaScriptEncoder)null); public JsonTypeInfo<bool> Boolean => _Boolean ?? (_Boolean = (JsonTypeInfo<bool>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(bool))); public JsonTypeInfo<Kind> Kind => _Kind ?? (_Kind = (JsonTypeInfo<Kind>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Kind))); public JsonTypeInfo<CreatorSubscription> CreatorSubscription => _CreatorSubscription ?? (_CreatorSubscription = (JsonTypeInfo<CreatorSubscription>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(CreatorSubscription))); public JsonTypeInfo<Playlist> Playlist => _Playlist ?? (_Playlist = (JsonTypeInfo<Playlist>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Playlist))); public JsonTypeInfo<Product> Product => _Product ?? (_Product = (JsonTypeInfo<Product>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Product))); public JsonTypeInfo<Visual> Visual => _Visual ?? (_Visual = (JsonTypeInfo<Visual>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Visual))); public JsonTypeInfo<Visuals> Visuals => _Visuals ?? (_Visuals = (JsonTypeInfo<Visuals>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Visuals))); public JsonTypeInfo<PlaylistSearchResult> PlaylistSearchResult => _PlaylistSearchResult ?? (_PlaylistSearchResult = (JsonTypeInfo<PlaylistSearchResult>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(PlaylistSearchResult))); public JsonTypeInfo<TrackSearchResult> TrackSearchResult => _TrackSearchResult ?? (_TrackSearchResult = (JsonTypeInfo<TrackSearchResult>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(TrackSearchResult))); public JsonTypeInfo<UserSearchResult> UserSearchResult => _UserSearchResult ?? (_UserSearchResult = (JsonTypeInfo<UserSearchResult>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(UserSearchResult))); public JsonTypeInfo<Format> Format => _Format ?? (_Format = (JsonTypeInfo<Format>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Format))); public JsonTypeInfo<Media> Media => _Media ?? (_Media = (JsonTypeInfo<Media>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Media))); public JsonTypeInfo<PublisherMetadata> PublisherMetadata => _PublisherMetadata ?? (_PublisherMetadata = (JsonTypeInfo<PublisherMetadata>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(PublisherMetadata))); public JsonTypeInfo<Track> Track => _Track ?? (_Track = (JsonTypeInfo<Track>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Track))); public JsonTypeInfo<Transcoding> Transcoding => _Transcoding ?? (_Transcoding = (JsonTypeInfo<Transcoding>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Transcoding))); public JsonTypeInfo<Badges> Badges => _Badges ?? (_Badges = (JsonTypeInfo<Badges>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Badges))); public JsonTypeInfo<PlaylistUser> PlaylistUser => _PlaylistUser ?? (_PlaylistUser = (JsonTypeInfo<PlaylistUser>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(PlaylistUser))); public JsonTypeInfo<User> User => _User ?? (_User = (JsonTypeInfo<User>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(User))); public JsonTypeInfo<List<CreatorSubscription>> ListCreatorSubscription => _ListCreatorSubscription ?? (_ListCreatorSubscription = (JsonTypeInfo<List<CreatorSubscription>>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(List<CreatorSubscription>))); public JsonTypeInfo<List<Playlist>> ListPlaylist => _ListPlaylist ?? (_ListPlaylist = (JsonTypeInfo<List<Playlist>>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(List<Playlist>))); public JsonTypeInfo<List<Visual>> ListVisual => _ListVisual ?? (_ListVisual = (JsonTypeInfo<List<Visual>>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(List<Visual>))); public JsonTypeInfo<List<Track>> ListTrack => _ListTrack ?? (_ListTrack = (JsonTypeInfo<List<Track>>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(List<Track>))); public JsonTypeInfo<List<Transcoding>> ListTranscoding => _ListTranscoding ?? (_ListTranscoding = (JsonTypeInfo<List<Transcoding>>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(List<Transcoding>))); public JsonTypeInfo<DateTimeOffset> DateTimeOffset => _DateTimeOffset ?? (_DateTimeOffset = (JsonTypeInfo<DateTimeOffset>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(DateTimeOffset))); public JsonTypeInfo<DateTimeOffset?> NullableDateTimeOffset => _NullableDateTimeOffset ?? (_NullableDateTimeOffset = (JsonTypeInfo<DateTimeOffset?>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(DateTimeOffset?))); public JsonTypeInfo<Uri> Uri => _Uri ?? (_Uri = (JsonTypeInfo<Uri>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(Uri))); public JsonTypeInfo<long> Int64 => _Int64 ?? (_Int64 = (JsonTypeInfo<long>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(long))); public JsonTypeInfo<long?> NullableInt64 => _NullableInt64 ?? (_NullableInt64 = (JsonTypeInfo<long?>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(long?))); public JsonTypeInfo<object> Object => _Object ?? (_Object = (JsonTypeInfo<object>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(object))); public JsonTypeInfo<string> String => _String ?? (_String = (JsonTypeInfo<string>)(object)((JsonSerializerContext)this).Options.GetTypeInfo(typeof(string))); public static SourceGenerationContext Default { get; } = new SourceGenerationContext(new JsonSerializerOptions(s_defaultOptions)); protected override JsonSerializerOptions? GeneratedSerializerOptions { get; } = s_defaultOptions; private JsonTypeInfo<bool> Create_Boolean(JsonSerializerOptions options) { if (!TryGetTypeInfoForRuntimeCustomConverter<bool>(options, out JsonTypeInfo<bool> jsonTypeInfo)) { jsonTypeInfo = JsonMetadataServices.CreateValueInfo<bool>(options, (JsonConverter)(object)JsonMetadataServices.BooleanConverter); } ((JsonTypeInfo)jsonTypeInfo).OriginatingResolver = (IJsonTypeInfoResolver)(object)this; return jsonTypeInfo; } private JsonTypeInfo<Kind> Create_Kind(JsonSerializerOptions options) { if (!TryGetTypeInfoForRuntimeCustomConverter<Kind>(options, out JsonTypeInfo<Kind> jsonTypeInfo)) { JsonConverter val = ExpandConverter(typeof(Kind), (JsonConverter)(object)new JsonStringEnumConverter<Kind>(), options); jsonTypeInfo = JsonMetadataServices.CreateValueInfo<Kind>(options, val); } ((JsonTypeInfo)jsonTypeInfo).OriginatingResolver = (IJsonTypeInfoResolver)(object)this; return jsonTypeInfo; } private JsonTypeInfo<CreatorSubscription> Create_CreatorSubscription(JsonSerializerOptions options) { JsonSerializerOptions options2 = options; if (!TryGetTypeInfoForRuntimeCustomConverter<CreatorSubscription>(options2, out JsonTypeInfo<CreatorSubscription> jsonTypeInfo)) { JsonObjectInfoValues<CreatorSubscription> obj = new JsonObjectInfoValues<CreatorSubscription>(); obj.set_ObjectCreator((Func<CreatorSubscription>)(() => new CreatorSubscription())); obj.set_ObjectWithParameterizedConstructorCreator((Func<object[], CreatorSubscription>)null); obj.set_PropertyMetadataInitializer((Func<JsonSerializerContext, JsonPropertyInfo[]>)((JsonSerializerContext _) => CreatorSubscriptionPropInit(options2))); obj.set_ConstructorParameterMetadataInitializer((Func<JsonParameterInfoValues[]>)null); obj.set_SerializeHandler((Action<Utf8JsonWriter, CreatorSubscription>)CreatorSubscriptionSerializeHandler); JsonObjectInfoValues<CreatorSubscription> val = obj; jsonTypeInfo = JsonMetadataServices.CreateObjectInfo<CreatorSubscription>(options2, val); ((JsonTypeInfo)jsonTypeInfo).NumberHandling = null; } ((JsonTypeInfo)jsonTypeInfo).OriginatingResolver = (IJsonTypeInfoResolver)(object)this; return jsonTypeInfo; } private static JsonPropertyInfo[] CreatorSubscriptionPropInit(JsonSerializerOptions options) { JsonPropertyInfo[] array = new JsonPropertyInfo[1]; JsonPropertyInfoValues<Product> obj2 = new JsonPropertyInfoValues<Product>(); obj2.set_IsProperty(true); obj2.set_IsPublic(true); obj2.set_IsVirtual(false); obj2.set_DeclaringType(typeof(CreatorSubscription)); obj2.set_Converter((JsonConverter<Product>)null); obj2.set_Getter((Func<object, Product>)((object obj) => ((CreatorSubscription)obj).Product)); obj2.set_Setter((Action<object, Product>)delegate(object obj, Product? value) { ((CreatorSubscription)obj).Product = value; }); obj2.set_IgnoreCondition((JsonIgnoreCondition?)null); obj2.set_HasJsonInclude(false); obj2.set_IsExtensionData(false); obj2.set_NumberHandling((JsonNumberHandling?)null); obj2.set_PropertyName("Product"); obj2.set_JsonPropertyName("product"); JsonPropertyInfoValues<Product> val = obj2; array[0] = JsonMetadataServices.CreatePropertyInfo<Product>(options, val); return (JsonPropertyInfo[])(object)array; } private void CreatorSubscriptionSerializeHandler(Utf8JsonWriter writer, CreatorSubscription? value) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartObject(); writer.WritePropertyName(PropName_product); ProductSerializeHandler(writer, value.Product); writer.WriteEndObject(); } private JsonTypeInfo<Playlist> Create_Playlist(JsonSerializerOptions options) { JsonSerializerOptions options2 = options; if (!TryGetTypeInfoForRuntimeCustomConverter<Playlist>(options2, out JsonTypeInfo<Playlist> jsonTypeInfo)) { JsonObjectInfoValues<Playlist> obj = new JsonObjectInfoValues<Playlist>(); obj.set_ObjectCreator((Func<Playlist>)(() => new Playlist())); obj.set_ObjectWithParameterizedConstructorCreator((Func<object[], Playlist>)null); obj.set_PropertyMetadataInitializer((Func<JsonSerializerContext, JsonPropertyInfo[]>)((JsonSerializerContext _) => PlaylistPropInit(options2))); obj.set_ConstructorParameterMetadataInitializer((Func<JsonParameterInfoValues[]>)null); obj.set_SerializeHandler((Action<Utf8JsonWriter, Playlist>)null); JsonObjectInfoValues<Playlist> val = obj; jsonTypeInfo = JsonMetadataServices.CreateObjectInfo<Playlist>(options2, val); ((JsonTypeInfo)jsonTypeInfo).NumberHandling = null; } ((JsonTypeInfo)jsonTypeInfo).OriginatingResolver = (IJsonTypeInfoResolver)(object)this; return jsonTypeInfo; } private static JsonPropertyInfo[] PlaylistPropInit(JsonSerializerOptions options) { JsonPropertyInfo[] array = new JsonPropertyInfo[33]; JsonPropertyInfoValues<Uri> obj2 = new JsonPropertyInfoValues<Uri>(); obj2.set_IsProperty(true); obj2.set_IsPublic(true); obj2.set_IsVirtual(false); obj2.set_DeclaringType(typeof(Playlist)); obj2.set_Converter((JsonConverter<Uri>)null); obj2.set_Getter((Func<object, Uri>)((object obj) => ((Playlist)obj).ArtworkUrl)); obj2.set_Setter((Action<object, Uri>)delegate(object obj, Uri? value) { ((Playlist)obj).ArtworkUrl = value; }); obj2.set_IgnoreCondition((JsonIgnoreCondition?)null); obj2.set_HasJsonInclude(false); obj2.set_IsExtensionData(false); obj2.set_NumberHandling((JsonNumberHandling?)null); obj2.set_PropertyName("ArtworkUrl"); obj2.set_JsonPropertyName("artwork_url"); JsonPropertyInfoValues<Uri> val = obj2; array[0] = JsonMetadataServices.CreatePropertyInfo<Uri>(options, val); JsonPropertyInfoValues<DateTimeOffset> obj3 = new JsonPropertyInfoValues<DateTimeOffset>(); obj3.set_IsProperty(true); obj3.set_IsPublic(true); obj3.set_IsVirtual(false); obj3.set_DeclaringType(typeof(Playlist)); obj3.set_Converter((JsonConverter<DateTimeOffset>)null); obj3.set_Getter((Func<object, DateTimeOffset>)((object obj) => ((Playlist)obj).CreatedAt)); obj3.set_Setter((Action<object, DateTimeOffset>)delegate(object obj, DateTimeOffset value) { ((Playlist)obj).CreatedAt = value; }); obj3.set_IgnoreCondition((JsonIgnoreCondition?)null); obj3.set_HasJsonInclude(false); obj3.set_IsExtensionData(false); obj3.set_NumberHandling((JsonNumberHandling?)null); obj3.set_PropertyName("CreatedAt"); obj3.set_JsonPropertyName("created_at"); JsonPropertyInfoValues<DateTimeOffset> val2 = obj3; array[1] = JsonMetadataServices.CreatePropertyInfo<DateTimeOffset>(options, val2); JsonPropertyInfoValues<string> obj4 = new JsonPropertyInfoValues<string>(); obj4.set_IsProperty(true); obj4.set_IsPublic(true); obj4.set_IsVirtual(false); obj4.set_DeclaringType(typeof(Playlist)); obj4.set_Converter((JsonConverter<string>)null); obj4.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).Description)); obj4.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).Description = value; }); obj4.set_IgnoreCondition((JsonIgnoreCondition?)null); obj4.set_HasJsonInclude(false); obj4.set_IsExtensionData(false); obj4.set_NumberHandling((JsonNumberHandling?)null); obj4.set_PropertyName("Description"); obj4.set_JsonPropertyName("description"); JsonPropertyInfoValues<string> val3 = obj4; array[2] = JsonMetadataServices.CreatePropertyInfo<string>(options, val3); JsonPropertyInfoValues<long> obj5 = new JsonPropertyInfoValues<long>(); obj5.set_IsProperty(true); obj5.set_IsPublic(true); obj5.set_IsVirtual(false); obj5.set_DeclaringType(typeof(Playlist)); obj5.set_Converter((JsonConverter<long>)null); obj5.set_Getter((Func<object, long>)((object obj) => ((Playlist)obj).Duration)); obj5.set_Setter((Action<object, long>)delegate(object obj, long value) { ((Playlist)obj).Duration = value; }); obj5.set_IgnoreCondition((JsonIgnoreCondition?)null); obj5.set_HasJsonInclude(false); obj5.set_IsExtensionData(false); obj5.set_NumberHandling((JsonNumberHandling?)null); obj5.set_PropertyName("Duration"); obj5.set_JsonPropertyName("duration"); JsonPropertyInfoValues<long> val4 = obj5; array[3] = JsonMetadataServices.CreatePropertyInfo<long>(options, val4); JsonPropertyInfoValues<string> obj6 = new JsonPropertyInfoValues<string>(); obj6.set_IsProperty(true); obj6.set_IsPublic(true); obj6.set_IsVirtual(false); obj6.set_DeclaringType(typeof(Playlist)); obj6.set_Converter((JsonConverter<string>)null); obj6.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).EmbeddableBy)); obj6.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).EmbeddableBy = value; }); obj6.set_IgnoreCondition((JsonIgnoreCondition?)null); obj6.set_HasJsonInclude(false); obj6.set_IsExtensionData(false); obj6.set_NumberHandling((JsonNumberHandling?)null); obj6.set_PropertyName("EmbeddableBy"); obj6.set_JsonPropertyName("embeddable_by"); JsonPropertyInfoValues<string> val5 = obj6; array[4] = JsonMetadataServices.CreatePropertyInfo<string>(options, val5); JsonPropertyInfoValues<string> obj7 = new JsonPropertyInfoValues<string>(); obj7.set_IsProperty(true); obj7.set_IsPublic(true); obj7.set_IsVirtual(false); obj7.set_DeclaringType(typeof(Playlist)); obj7.set_Converter((JsonConverter<string>)null); obj7.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).Genre)); obj7.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).Genre = value; }); obj7.set_IgnoreCondition((JsonIgnoreCondition?)null); obj7.set_HasJsonInclude(false); obj7.set_IsExtensionData(false); obj7.set_NumberHandling((JsonNumberHandling?)null); obj7.set_PropertyName("Genre"); obj7.set_JsonPropertyName("genre"); JsonPropertyInfoValues<string> val6 = obj7; array[5] = JsonMetadataServices.CreatePropertyInfo<string>(options, val6); JsonPropertyInfoValues<long?> obj8 = new JsonPropertyInfoValues<long?>(); obj8.set_IsProperty(true); obj8.set_IsPublic(true); obj8.set_IsVirtual(false); obj8.set_DeclaringType(typeof(Playlist)); obj8.set_Converter((JsonConverter<long?>)null); obj8.set_Getter((Func<object, long?>)((object obj) => ((Playlist)obj).Id)); obj8.set_Setter((Action<object, long?>)delegate(object obj, long? value) { ((Playlist)obj).Id = value; }); obj8.set_IgnoreCondition((JsonIgnoreCondition?)null); obj8.set_HasJsonInclude(false); obj8.set_IsExtensionData(false); obj8.set_NumberHandling((JsonNumberHandling?)null); obj8.set_PropertyName("Id"); obj8.set_JsonPropertyName("id"); JsonPropertyInfoValues<long?> val7 = obj8; array[6] = JsonMetadataServices.CreatePropertyInfo<long?>(options, val7); JsonPropertyInfoValues<Kind> obj9 = new JsonPropertyInfoValues<Kind>(); obj9.set_IsProperty(true); obj9.set_IsPublic(true); obj9.set_IsVirtual(false); obj9.set_DeclaringType(typeof(Playlist)); obj9.set_Converter((JsonConverter<Kind>)null); obj9.set_Getter((Func<object, Kind>)((object obj) => ((Playlist)obj).Kind)); obj9.set_Setter((Action<object, Kind>)delegate(object obj, Kind value) { ((Playlist)obj).Kind = value; }); obj9.set_IgnoreCondition((JsonIgnoreCondition?)null); obj9.set_HasJsonInclude(false); obj9.set_IsExtensionData(false); obj9.set_NumberHandling((JsonNumberHandling?)null); obj9.set_PropertyName("Kind"); obj9.set_JsonPropertyName("kind"); JsonPropertyInfoValues<Kind> val8 = obj9; array[7] = JsonMetadataServices.CreatePropertyInfo<Kind>(options, val8); JsonPropertyInfoValues<string> obj10 = new JsonPropertyInfoValues<string>(); obj10.set_IsProperty(true); obj10.set_IsPublic(true); obj10.set_IsVirtual(false); obj10.set_DeclaringType(typeof(Playlist)); obj10.set_Converter((JsonConverter<string>)null); obj10.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).LabelName)); obj10.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).LabelName = value; }); obj10.set_IgnoreCondition((JsonIgnoreCondition?)null); obj10.set_HasJsonInclude(false); obj10.set_IsExtensionData(false); obj10.set_NumberHandling((JsonNumberHandling?)null); obj10.set_PropertyName("LabelName"); obj10.set_JsonPropertyName("label_name"); JsonPropertyInfoValues<string> val9 = obj10; array[8] = JsonMetadataServices.CreatePropertyInfo<string>(options, val9); JsonPropertyInfoValues<DateTimeOffset> obj11 = new JsonPropertyInfoValues<DateTimeOffset>(); obj11.set_IsProperty(true); obj11.set_IsPublic(true); obj11.set_IsVirtual(false); obj11.set_DeclaringType(typeof(Playlist)); obj11.set_Converter((JsonConverter<DateTimeOffset>)null); obj11.set_Getter((Func<object, DateTimeOffset>)((object obj) => ((Playlist)obj).LastModified)); obj11.set_Setter((Action<object, DateTimeOffset>)delegate(object obj, DateTimeOffset value) { ((Playlist)obj).LastModified = value; }); obj11.set_IgnoreCondition((JsonIgnoreCondition?)null); obj11.set_HasJsonInclude(false); obj11.set_IsExtensionData(false); obj11.set_NumberHandling((JsonNumberHandling?)null); obj11.set_PropertyName("LastModified"); obj11.set_JsonPropertyName("last_modified"); JsonPropertyInfoValues<DateTimeOffset> val10 = obj11; array[9] = JsonMetadataServices.CreatePropertyInfo<DateTimeOffset>(options, val10); JsonPropertyInfoValues<string> obj12 = new JsonPropertyInfoValues<string>(); obj12.set_IsProperty(true); obj12.set_IsPublic(true); obj12.set_IsVirtual(false); obj12.set_DeclaringType(typeof(Playlist)); obj12.set_Converter((JsonConverter<string>)null); obj12.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).License)); obj12.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).License = value; }); obj12.set_IgnoreCondition((JsonIgnoreCondition?)null); obj12.set_HasJsonInclude(false); obj12.set_IsExtensionData(false); obj12.set_NumberHandling((JsonNumberHandling?)null); obj12.set_PropertyName("License"); obj12.set_JsonPropertyName("license"); JsonPropertyInfoValues<string> val11 = obj12; array[10] = JsonMetadataServices.CreatePropertyInfo<string>(options, val11); JsonPropertyInfoValues<long> obj13 = new JsonPropertyInfoValues<long>(); obj13.set_IsProperty(true); obj13.set_IsPublic(true); obj13.set_IsVirtual(false); obj13.set_DeclaringType(typeof(Playlist)); obj13.set_Converter((JsonConverter<long>)null); obj13.set_Getter((Func<object, long>)((object obj) => ((Playlist)obj).LikesCount)); obj13.set_Setter((Action<object, long>)delegate(object obj, long value) { ((Playlist)obj).LikesCount = value; }); obj13.set_IgnoreCondition((JsonIgnoreCondition?)null); obj13.set_HasJsonInclude(false); obj13.set_IsExtensionData(false); obj13.set_NumberHandling((JsonNumberHandling?)null); obj13.set_PropertyName("LikesCount"); obj13.set_JsonPropertyName("likes_count"); JsonPropertyInfoValues<long> val12 = obj13; array[11] = JsonMetadataServices.CreatePropertyInfo<long>(options, val12); JsonPropertyInfoValues<bool> obj14 = new JsonPropertyInfoValues<bool>(); obj14.set_IsProperty(true); obj14.set_IsPublic(true); obj14.set_IsVirtual(false); obj14.set_DeclaringType(typeof(Playlist)); obj14.set_Converter((JsonConverter<bool>)null); obj14.set_Getter((Func<object, bool>)((object obj) => ((Playlist)obj).ManagedByFeeds)); obj14.set_Setter((Action<object, bool>)delegate(object obj, bool value) { ((Playlist)obj).ManagedByFeeds = value; }); obj14.set_IgnoreCondition((JsonIgnoreCondition?)null); obj14.set_HasJsonInclude(false); obj14.set_IsExtensionData(false); obj14.set_NumberHandling((JsonNumberHandling?)null); obj14.set_PropertyName("ManagedByFeeds"); obj14.set_JsonPropertyName("managed_by_feeds"); JsonPropertyInfoValues<bool> val13 = obj14; array[12] = JsonMetadataServices.CreatePropertyInfo<bool>(options, val13); JsonPropertyInfoValues<string> obj15 = new JsonPropertyInfoValues<string>(); obj15.set_IsProperty(true); obj15.set_IsPublic(true); obj15.set_IsVirtual(false); obj15.set_DeclaringType(typeof(Playlist)); obj15.set_Converter((JsonConverter<string>)null); obj15.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).Permalink)); obj15.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).Permalink = value; }); obj15.set_IgnoreCondition((JsonIgnoreCondition?)null); obj15.set_HasJsonInclude(false); obj15.set_IsExtensionData(false); obj15.set_NumberHandling((JsonNumberHandling?)null); obj15.set_PropertyName("Permalink"); obj15.set_JsonPropertyName("permalink"); JsonPropertyInfoValues<string> val14 = obj15; array[13] = JsonMetadataServices.CreatePropertyInfo<string>(options, val14); JsonPropertyInfoValues<Uri> obj16 = new JsonPropertyInfoValues<Uri>(); obj16.set_IsProperty(true); obj16.set_IsPublic(true); obj16.set_IsVirtual(false); obj16.set_DeclaringType(typeof(Playlist)); obj16.set_Converter((JsonConverter<Uri>)null); obj16.set_Getter((Func<object, Uri>)((object obj) => ((Playlist)obj).PermalinkUrl)); obj16.set_Setter((Action<object, Uri>)delegate(object obj, Uri? value) { ((Playlist)obj).PermalinkUrl = value; }); obj16.set_IgnoreCondition((JsonIgnoreCondition?)null); obj16.set_HasJsonInclude(false); obj16.set_IsExtensionData(false); obj16.set_NumberHandling((JsonNumberHandling?)null); obj16.set_PropertyName("PermalinkUrl"); obj16.set_JsonPropertyName("permalink_url"); JsonPropertyInfoValues<Uri> val15 = obj16; array[14] = JsonMetadataServices.CreatePropertyInfo<Uri>(options, val15); JsonPropertyInfoValues<bool> obj17 = new JsonPropertyInfoValues<bool>(); obj17.set_IsProperty(true); obj17.set_IsPublic(true); obj17.set_IsVirtual(false); obj17.set_DeclaringType(typeof(Playlist)); obj17.set_Converter((JsonConverter<bool>)null); obj17.set_Getter((Func<object, bool>)((object obj) => ((Playlist)obj).Public)); obj17.set_Setter((Action<object, bool>)delegate(object obj, bool value) { ((Playlist)obj).Public = value; }); obj17.set_IgnoreCondition((JsonIgnoreCondition?)null); obj17.set_HasJsonInclude(false); obj17.set_IsExtensionData(false); obj17.set_NumberHandling((JsonNumberHandling?)null); obj17.set_PropertyName("Public"); obj17.set_JsonPropertyName("public"); JsonPropertyInfoValues<bool> val16 = obj17; array[15] = JsonMetadataServices.CreatePropertyInfo<bool>(options, val16); JsonPropertyInfoValues<string> obj18 = new JsonPropertyInfoValues<string>(); obj18.set_IsProperty(true); obj18.set_IsPublic(true); obj18.set_IsVirtual(false); obj18.set_DeclaringType(typeof(Playlist)); obj18.set_Converter((JsonConverter<string>)null); obj18.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).PurchaseTitle)); obj18.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).PurchaseTitle = value; }); obj18.set_IgnoreCondition((JsonIgnoreCondition?)null); obj18.set_HasJsonInclude(false); obj18.set_IsExtensionData(false); obj18.set_NumberHandling((JsonNumberHandling?)null); obj18.set_PropertyName("PurchaseTitle"); obj18.set_JsonPropertyName("purchase_title"); JsonPropertyInfoValues<string> val17 = obj18; array[16] = JsonMetadataServices.CreatePropertyInfo<string>(options, val17); JsonPropertyInfoValues<string> obj19 = new JsonPropertyInfoValues<string>(); obj19.set_IsProperty(true); obj19.set_IsPublic(true); obj19.set_IsVirtual(false); obj19.set_DeclaringType(typeof(Playlist)); obj19.set_Converter((JsonConverter<string>)null); obj19.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).PurchaseUrl)); obj19.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).PurchaseUrl = value; }); obj19.set_IgnoreCondition((JsonIgnoreCondition?)null); obj19.set_HasJsonInclude(false); obj19.set_IsExtensionData(false); obj19.set_NumberHandling((JsonNumberHandling?)null); obj19.set_PropertyName("PurchaseUrl"); obj19.set_JsonPropertyName("purchase_url"); JsonPropertyInfoValues<string> val18 = obj19; array[17] = JsonMetadataServices.CreatePropertyInfo<string>(options, val18); JsonPropertyInfoValues<object> obj20 = new JsonPropertyInfoValues<object>(); obj20.set_IsProperty(true); obj20.set_IsPublic(true); obj20.set_IsVirtual(false); obj20.set_DeclaringType(typeof(Playlist)); obj20.set_Converter((JsonConverter<object>)null); obj20.set_Getter((Func<object, object>)((object obj) => ((Playlist)obj).ReleaseDate)); obj20.set_Setter((Action<object, object>)delegate(object obj, object? value) { ((Playlist)obj).ReleaseDate = value; }); obj20.set_IgnoreCondition((JsonIgnoreCondition?)null); obj20.set_HasJsonInclude(false); obj20.set_IsExtensionData(false); obj20.set_NumberHandling((JsonNumberHandling?)null); obj20.set_PropertyName("ReleaseDate"); obj20.set_JsonPropertyName("release_date"); JsonPropertyInfoValues<object> val19 = obj20; array[18] = JsonMetadataServices.CreatePropertyInfo<object>(options, val19); JsonPropertyInfoValues<long> obj21 = new JsonPropertyInfoValues<long>(); obj21.set_IsProperty(true); obj21.set_IsPublic(true); obj21.set_IsVirtual(false); obj21.set_DeclaringType(typeof(Playlist)); obj21.set_Converter((JsonConverter<long>)null); obj21.set_Getter((Func<object, long>)((object obj) => ((Playlist)obj).RepostsCount)); obj21.set_Setter((Action<object, long>)delegate(object obj, long value) { ((Playlist)obj).RepostsCount = value; }); obj21.set_IgnoreCondition((JsonIgnoreCondition?)null); obj21.set_HasJsonInclude(false); obj21.set_IsExtensionData(false); obj21.set_NumberHandling((JsonNumberHandling?)null); obj21.set_PropertyName("RepostsCount"); obj21.set_JsonPropertyName("reposts_count"); JsonPropertyInfoValues<long> val20 = obj21; array[19] = JsonMetadataServices.CreatePropertyInfo<long>(options, val20); JsonPropertyInfoValues<string> obj22 = new JsonPropertyInfoValues<string>(); obj22.set_IsProperty(true); obj22.set_IsPublic(true); obj22.set_IsVirtual(false); obj22.set_DeclaringType(typeof(Playlist)); obj22.set_Converter((JsonConverter<string>)null); obj22.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).SecretToken)); obj22.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).SecretToken = value; }); obj22.set_IgnoreCondition((JsonIgnoreCondition?)null); obj22.set_HasJsonInclude(false); obj22.set_IsExtensionData(false); obj22.set_NumberHandling((JsonNumberHandling?)null); obj22.set_PropertyName("SecretToken"); obj22.set_JsonPropertyName("secret_token"); JsonPropertyInfoValues<string> val21 = obj22; array[20] = JsonMetadataServices.CreatePropertyInfo<string>(options, val21); JsonPropertyInfoValues<string> obj23 = new JsonPropertyInfoValues<string>(); obj23.set_IsProperty(true); obj23.set_IsPublic(true); obj23.set_IsVirtual(false); obj23.set_DeclaringType(typeof(Playlist)); obj23.set_Converter((JsonConverter<string>)null); obj23.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).Sharing)); obj23.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).Sharing = value; }); obj23.set_IgnoreCondition((JsonIgnoreCondition?)null); obj23.set_HasJsonInclude(false); obj23.set_IsExtensionData(false); obj23.set_NumberHandling((JsonNumberHandling?)null); obj23.set_PropertyName("Sharing"); obj23.set_JsonPropertyName("sharing"); JsonPropertyInfoValues<string> val22 = obj23; array[21] = JsonMetadataServices.CreatePropertyInfo<string>(options, val22); JsonPropertyInfoValues<string> obj24 = new JsonPropertyInfoValues<string>(); obj24.set_IsProperty(true); obj24.set_IsPublic(true); obj24.set_IsVirtual(false); obj24.set_DeclaringType(typeof(Playlist)); obj24.set_Converter((JsonConverter<string>)null); obj24.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).TagList)); obj24.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).TagList = value; }); obj24.set_IgnoreCondition((JsonIgnoreCondition?)null); obj24.set_HasJsonInclude(false); obj24.set_IsExtensionData(false); obj24.set_NumberHandling((JsonNumberHandling?)null); obj24.set_PropertyName("TagList"); obj24.set_JsonPropertyName("tag_list"); JsonPropertyInfoValues<string> val23 = obj24; array[22] = JsonMetadataServices.CreatePropertyInfo<string>(options, val23); JsonPropertyInfoValues<string> obj25 = new JsonPropertyInfoValues<string>(); obj25.set_IsProperty(true); obj25.set_IsPublic(true); obj25.set_IsVirtual(false); obj25.set_DeclaringType(typeof(Playlist)); obj25.set_Converter((JsonConverter<string>)null); obj25.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).Title)); obj25.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).Title = value; }); obj25.set_IgnoreCondition((JsonIgnoreCondition?)null); obj25.set_HasJsonInclude(false); obj25.set_IsExtensionData(false); obj25.set_NumberHandling((JsonNumberHandling?)null); obj25.set_PropertyName("Title"); obj25.set_JsonPropertyName("title"); JsonPropertyInfoValues<string> val24 = obj25; array[23] = JsonMetadataServices.CreatePropertyInfo<string>(options, val24); JsonPropertyInfoValues<Uri> obj26 = new JsonPropertyInfoValues<Uri>(); obj26.set_IsProperty(true); obj26.set_IsPublic(true); obj26.set_IsVirtual(false); obj26.set_DeclaringType(typeof(Playlist)); obj26.set_Converter((JsonConverter<Uri>)null); obj26.set_Getter((Func<object, Uri>)((object obj) => ((Playlist)obj).Uri)); obj26.set_Setter((Action<object, Uri>)delegate(object obj, Uri? value) { ((Playlist)obj).Uri = value; }); obj26.set_IgnoreCondition((JsonIgnoreCondition?)null); obj26.set_HasJsonInclude(false); obj26.set_IsExtensionData(false); obj26.set_NumberHandling((JsonNumberHandling?)null); obj26.set_PropertyName("Uri"); obj26.set_JsonPropertyName("uri"); JsonPropertyInfoValues<Uri> val25 = obj26; array[24] = JsonMetadataServices.CreatePropertyInfo<Uri>(options, val25); JsonPropertyInfoValues<long> obj27 = new JsonPropertyInfoValues<long>(); obj27.set_IsProperty(true); obj27.set_IsPublic(true); obj27.set_IsVirtual(false); obj27.set_DeclaringType(typeof(Playlist)); obj27.set_Converter((JsonConverter<long>)null); obj27.set_Getter((Func<object, long>)((object obj) => ((Playlist)obj).UserId)); obj27.set_Setter((Action<object, long>)delegate(object obj, long value) { ((Playlist)obj).UserId = value; }); obj27.set_IgnoreCondition((JsonIgnoreCondition?)null); obj27.set_HasJsonInclude(false); obj27.set_IsExtensionData(false); obj27.set_NumberHandling((JsonNumberHandling?)null); obj27.set_PropertyName("UserId"); obj27.set_JsonPropertyName("user_id"); JsonPropertyInfoValues<long> val26 = obj27; array[25] = JsonMetadataServices.CreatePropertyInfo<long>(options, val26); JsonPropertyInfoValues<string> obj28 = new JsonPropertyInfoValues<string>(); obj28.set_IsProperty(true); obj28.set_IsPublic(true); obj28.set_IsVirtual(false); obj28.set_DeclaringType(typeof(Playlist)); obj28.set_Converter((JsonConverter<string>)null); obj28.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).SetType)); obj28.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).SetType = value; }); obj28.set_IgnoreCondition((JsonIgnoreCondition?)null); obj28.set_HasJsonInclude(false); obj28.set_IsExtensionData(false); obj28.set_NumberHandling((JsonNumberHandling?)null); obj28.set_PropertyName("SetType"); obj28.set_JsonPropertyName("set_type"); JsonPropertyInfoValues<string> val27 = obj28; array[26] = JsonMetadataServices.CreatePropertyInfo<string>(options, val27); JsonPropertyInfoValues<bool> obj29 = new JsonPropertyInfoValues<bool>(); obj29.set_IsProperty(true); obj29.set_IsPublic(true); obj29.set_IsVirtual(false); obj29.set_DeclaringType(typeof(Playlist)); obj29.set_Converter((JsonConverter<bool>)null); obj29.set_Getter((Func<object, bool>)((object obj) => ((Playlist)obj).IsAlbum)); obj29.set_Setter((Action<object, bool>)delegate(object obj, bool value) { ((Playlist)obj).IsAlbum = value; }); obj29.set_IgnoreCondition((JsonIgnoreCondition?)null); obj29.set_HasJsonInclude(false); obj29.set_IsExtensionData(false); obj29.set_NumberHandling((JsonNumberHandling?)null); obj29.set_PropertyName("IsAlbum"); obj29.set_JsonPropertyName("is_album"); JsonPropertyInfoValues<bool> val28 = obj29; array[27] = JsonMetadataServices.CreatePropertyInfo<bool>(options, val28); JsonPropertyInfoValues<object> obj30 = new JsonPropertyInfoValues<object>(); obj30.set_IsProperty(true); obj30.set_IsPublic(true); obj30.set_IsVirtual(false); obj30.set_DeclaringType(typeof(Playlist)); obj30.set_Converter((JsonConverter<object>)null); obj30.set_Getter((Func<object, object>)((object obj) => ((Playlist)obj).PublishedAt)); obj30.set_Setter((Action<object, object>)delegate(object obj, object? value) { ((Playlist)obj).PublishedAt = value; }); obj30.set_IgnoreCondition((JsonIgnoreCondition?)null); obj30.set_HasJsonInclude(false); obj30.set_IsExtensionData(false); obj30.set_NumberHandling((JsonNumberHandling?)null); obj30.set_PropertyName("PublishedAt"); obj30.set_JsonPropertyName("published_at"); JsonPropertyInfoValues<object> val29 = obj30; array[28] = JsonMetadataServices.CreatePropertyInfo<object>(options, val29); JsonPropertyInfoValues<DateTimeOffset> obj31 = new JsonPropertyInfoValues<DateTimeOffset>(); obj31.set_IsProperty(true); obj31.set_IsPublic(true); obj31.set_IsVirtual(false); obj31.set_DeclaringType(typeof(Playlist)); obj31.set_Converter((JsonConverter<DateTimeOffset>)null); obj31.set_Getter((Func<object, DateTimeOffset>)((object obj) => ((Playlist)obj).DisplayDate)); obj31.set_Setter((Action<object, DateTimeOffset>)delegate(object obj, DateTimeOffset value) { ((Playlist)obj).DisplayDate = value; }); obj31.set_IgnoreCondition((JsonIgnoreCondition?)null); obj31.set_HasJsonInclude(false); obj31.set_IsExtensionData(false); obj31.set_NumberHandling((JsonNumberHandling?)null); obj31.set_PropertyName("DisplayDate"); obj31.set_JsonPropertyName("display_date"); JsonPropertyInfoValues<DateTimeOffset> val30 = obj31; array[29] = JsonMetadataServices.CreatePropertyInfo<DateTimeOffset>(options, val30); JsonPropertyInfoValues<PlaylistUser> obj32 = new JsonPropertyInfoValues<PlaylistUser>(); obj32.set_IsProperty(true); obj32.set_IsPublic(true); obj32.set_IsVirtual(false); obj32.set_DeclaringType(typeof(Playlist)); obj32.set_Converter((JsonConverter<PlaylistUser>)null); obj32.set_Getter((Func<object, PlaylistUser>)((object obj) => ((Playlist)obj).User)); obj32.set_Setter((Action<object, PlaylistUser>)delegate(object obj, PlaylistUser? value) { ((Playlist)obj).User = value; }); obj32.set_IgnoreCondition((JsonIgnoreCondition?)null); obj32.set_HasJsonInclude(false); obj32.set_IsExtensionData(false); obj32.set_NumberHandling((JsonNumberHandling?)null); obj32.set_PropertyName("User"); obj32.set_JsonPropertyName("user"); JsonPropertyInfoValues<PlaylistUser> val31 = obj32; array[30] = JsonMetadataServices.CreatePropertyInfo<PlaylistUser>(options, val31); JsonPropertyInfoValues<List<Track>> obj33 = new JsonPropertyInfoValues<List<Track>>(); obj33.set_IsProperty(true); obj33.set_IsPublic(true); obj33.set_IsVirtual(false); obj33.set_DeclaringType(typeof(Playlist)); obj33.set_Converter((JsonConverter<List<Track>>)null); obj33.set_Getter((Func<object, List<Track>>)((object obj) => ((Playlist)obj).Tracks)); obj33.set_Setter((Action<object, List<Track>>)delegate(object obj, List<Track>? value) { ((Playlist)obj).Tracks = value; }); obj33.set_IgnoreCondition((JsonIgnoreCondition?)null); obj33.set_HasJsonInclude(false); obj33.set_IsExtensionData(false); obj33.set_NumberHandling((JsonNumberHandling?)null); obj33.set_PropertyName("Tracks"); obj33.set_JsonPropertyName("tracks"); JsonPropertyInfoValues<List<Track>> val32 = obj33; array[31] = JsonMetadataServices.CreatePropertyInfo<List<Track>>(options, val32); JsonPropertyInfoValues<long?> obj34 = new JsonPropertyInfoValues<long?>(); obj34.set_IsProperty(true); obj34.set_IsPublic(true); obj34.set_IsVirtual(false); obj34.set_DeclaringType(typeof(Playlist)); obj34.set_Converter((JsonConverter<long?>)null); obj34.set_Getter((Func<object, long?>)((object obj) => ((Playlist)obj).TrackCount)); obj34.set_Setter((Action<object, long?>)delegate(object obj, long? value) { ((Playlist)obj).TrackCount = value; }); obj34.set_IgnoreCondition((JsonIgnoreCondition?)null); obj34.set_HasJsonInclude(false); obj34.set_IsExtensionData(false); obj34.set_NumberHandling((JsonNumberHandling?)null); obj34.set_PropertyName("TrackCount"); obj34.set_JsonPropertyName("track_count"); JsonPropertyInfoValues<long?> val33 = obj34; array[32] = JsonMetadataServices.CreatePropertyInfo<long?>(options, val33); return (JsonPropertyInfo[])(object)array; } private JsonTypeInfo<Product> Create_Product(JsonSerializerOptions options) { JsonSerializerOptions options2 = options; if (!TryGetTypeInfoForRuntimeCustomConverter<Product>(options2, out JsonTypeInfo<Product> jsonTypeInfo)) { JsonObjectInfoValues<Product> obj = new JsonObjectInfoValues<Product>(); obj.set_ObjectCreator((Func<Product>)(() => new Product())); obj.set_ObjectWithParameterizedConstructorCreator((Func<object[], Product>)null); obj.set_PropertyMetadataInitializer((Func<JsonSerializerContext, JsonPropertyInfo[]>)((JsonSerializerContext _) => ProductPropInit(options2))); obj.set_ConstructorParameterMetadataInitializer((Func<JsonParameterInfoValues[]>)null); obj.set_SerializeHandler((Action<Utf8JsonWriter, Product>)ProductSerializeHandler); JsonObjectInfoValues<Product> val = obj; jsonTypeInfo = JsonMetadataServices.CreateObjectInfo<Product>(options2, val); ((JsonTypeInfo)jsonTypeInfo).NumberHandling = null; } ((JsonTypeInfo)jsonTypeInfo).OriginatingResolver = (IJsonTypeInfoResolver)(object)this; return jsonTypeInfo; } private static JsonPropertyInfo[] ProductPropInit(JsonSerializerOptions options) { JsonPropertyInfo[] array = new JsonPropertyInfo[1]; JsonPropertyInfoValues<string> obj2 = new JsonPropertyInfoValues<string>(); obj2.set_IsProperty(true); obj2.set_IsPublic(true); obj2.set_IsVirtual(false); obj2.set_DeclaringType(typeof(Product)); obj2.set_Converter((JsonConverter<string>)null); obj2.set_Getter((Func<object, string>)((object obj) => ((Product)obj).Id)); obj2.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Product)obj).Id = value; }); obj2.set_IgnoreCondition((JsonIgnoreCondition?)null); obj2.set_HasJsonInclude(false); obj2.set_IsExtensionData(false); obj2.set_NumberHandling((JsonNumberHandling?)null); obj2.set_PropertyName("Id"); obj2.set_JsonPropertyName("id"); JsonPropertyInfoValues<string> val = obj2; array[0] = JsonMetadataServices.CreatePropertyInfo<string>(options, val); return (JsonPropertyInfo[])(object)array; } private void ProductSerializeHandler(Utf8JsonWriter writer, Product? value) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartObject(); writer.WriteString(PropName_id, value.Id); writer.WriteEndObject(); } private JsonTypeInfo<Visual> Create_Visual(JsonSerializerOptions options) { JsonSerializerOptions options2 = options; if (!TryGetTypeInfoForRuntimeCustomConverter<Visual>(options2, out JsonTypeInfo<Visual> jsonTypeInfo)) { JsonObjectInfoValues<Visual> obj = new JsonObjectInfoValues<Visual>(); obj.set_ObjectCreator((Func<Visual>)(() => new Visual())); obj.set_ObjectWithParameterizedConstructorCreator((Func<object[], Visual>)null); obj.set_PropertyMetadataInitializer((Func<JsonSerializerContext, JsonPropertyInfo[]>)((JsonSerializerContext _) => VisualPropInit(options2))); obj.set_ConstructorParameterMetadataInitializer((Func<JsonParameterInfoValues[]>)null); obj.set_SerializeHandler((Action<Utf8JsonWriter, Visual>)VisualSerializeHandler); JsonObjectInfoValues<Visual> val = obj; jsonTypeInfo = JsonMetadataServices.CreateObjectInfo<Visual>(options2, val); ((JsonTypeInfo)jsonTypeInfo).NumberHandling = null; } ((JsonTypeInfo)jsonTypeInfo).OriginatingResolver = (IJsonTypeInfoResolver)(object)this; return jsonTypeInfo; } private static JsonPropertyInfo[] VisualPropInit(JsonSerializerOptions options) { JsonPropertyInfo[] array = new JsonPropertyInfo[3]; JsonPropertyInfoValues<string> obj2 = new JsonPropertyInfoValues<string>(); obj2.set_IsProperty(true); obj2.set_IsPublic(true); obj2.set_IsVirtual(false); obj2.set_DeclaringType(typeof(Visual)); obj2.set_Converter((JsonConverter<string>)null); obj2.set_Getter((Func<object, string>)((object obj) => ((Visual)obj).Urn)); obj2.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Visual)obj).Urn = value; }); obj2.set_IgnoreCondition((JsonIgnoreCondition?)null); obj2.set_HasJsonInclude(false); obj2.set_IsExtensionData(false); obj2.set_NumberHandling((JsonNumberHandling?)null); obj2.set_PropertyName("Urn"); obj2.set_JsonPropertyName("urn"); JsonPropertyInfoValues<string> val = obj2; array[0] = JsonMetadataServices.CreatePropertyInfo<string>(options, val); JsonPropertyInfoValues<long?> obj3 = new JsonPropertyInfoValues<long?>(); obj3.set_IsProperty(true); obj3.set_IsPublic(true); obj3.set_IsVirtual(false); obj3.set_DeclaringType(typeof(Visual)); obj3.set_Converter((JsonConverter<long?>)null); obj3.set_Getter((Func<object, long?>)((object obj) => ((Visual)obj).EntryTime)); obj3.set_Setter((Action<object, long?>)delegate(object obj, long? value) { ((Visual)obj).EntryTime = value; }); obj3.set_IgnoreCondition((JsonIgnoreCondition?)null); obj3.set_HasJsonInclude(false); obj3.set_IsExtensionData(false); obj3.set_NumberHandling((JsonNumberHandling?)null); obj3.set_PropertyName("EntryTime"); obj3.set_JsonPropertyName("entry_time"); JsonPropertyInfoValues<long?> val2 = obj3; array[1] = JsonMetadataServices.CreatePropertyInfo<long?>(options, val2); JsonPropertyInfoValues<Uri> obj4 = new JsonPropertyInfoValues<Uri>(); obj4.set_IsProperty(true); obj4.set_IsPublic(true); obj4.set_IsVirtual(false); obj4.set_DeclaringType(typeof(Visual)); obj4.set_Converter((JsonConverter<Uri>)null); obj4.set_Getter((Func<object, Uri>)((object obj) => ((Visual)obj).VisualUrl)); obj4.set_Setter((Action<object, Uri>)delegate(object obj, Uri? value) { ((Visual)obj).VisualUrl = value; }); obj4.set_IgnoreCondition((JsonIgnoreCondition?)null); obj4.set_HasJsonInclude(false); obj4.set_IsExtensionData(false); obj4.set_NumberHandling((JsonNumberHandling?)null); obj4.set_PropertyName("VisualUrl"); obj4.set_JsonPropertyName("visual_url"); JsonPropertyInfoValues<Uri> val3 = obj4; array[2] = JsonMetadataServices.CreatePropertyInfo<Uri>(options, val3); return (JsonPropertyInfo[])(object)array; } private void VisualSerializeHandler(Utf8JsonWriter writer, Visual? value) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartObject(); writer.WriteString(PropName_urn, value.Urn); writer.WritePropertyName(PropName_entry_time); JsonSerializer.Serialize<long?>(writer, value.EntryTime, NullableInt64); writer.WritePropertyName(PropName_visual_url); JsonSerializer.Serialize<Uri>(writer, value.VisualUrl, Uri); writer.WriteEndObject(); } private JsonTypeInfo<Visuals> Create_Visuals(JsonSerializerOptions options) { JsonSerializerOptions options2 = options; if (!TryGetTypeInfoForRuntimeCustomConverter<Visuals>(options2, out JsonTypeInfo<Visuals> jsonTypeInfo)) { JsonObjectInfoValues<Visuals> obj = new JsonObjectInfoValues<Visuals>(); obj.set_ObjectCreator((Func<Visuals>)(() => new Visuals())); obj.set_ObjectWithParameterizedConstructorCreator((Func<object[], Visuals>)null); obj.set_PropertyMetadataInitializer((Func<JsonSerializerContext, JsonPropertyInfo[]>)((JsonSerializerContext _) => VisualsPropInit(options2))); obj.set_ConstructorParameterMetadataInitializer((Func<JsonParameterInfoValues[]>)null); obj.set_SerializeHandler((Action<Utf8JsonWriter, Visuals>)null); JsonObjectInfoValues<Visuals> val = obj; jsonTypeInfo = JsonMetadataServices.CreateObjectInfo<Visuals>(options2, val); ((JsonTypeInfo)jsonTypeInfo).NumberHandling = null; } ((JsonTypeInfo)jsonTypeInfo).OriginatingResolver = (IJsonTypeInfoResolver)(object)this; return jsonTypeInfo; } private static JsonPropertyInfo[] VisualsPropInit(JsonSerializerOptions options) { JsonPropertyInfo[] array = new JsonPropertyInfo[4]; JsonPropertyInfoValues<string> obj2 = new JsonPropertyInfoValues<string>(); obj2.set_IsProperty(true); obj2.set_IsPublic(true); obj2.set_IsVirtual(false); obj2.set_DeclaringType(typeof(Visuals)); obj2.set_Converter((JsonConverter<string>)null); obj2.set_Getter((Func<object, string>)((object obj) => ((Visuals)obj).Urn)); obj2.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Visuals)obj).Urn = value; }); obj2.set_IgnoreCondition((JsonIgnoreCondition?)null); obj2.set_HasJsonInclude(false); obj2.set_IsExtensionData(false); obj2.set_NumberHandling((JsonNumberHandling?)null); obj2.set_PropertyName("Urn"); obj2.set_JsonPropertyName("urn"); JsonPropertyInfoValues<string> val = obj2; array[0] = JsonMetadataServices.CreatePropertyInfo<string>(options, val); JsonPropertyInfoValues<bool> obj3 = new JsonPropertyInfoValues<bool>(); obj3.set_IsProperty(true); obj3.set_IsPublic(true); obj3.set_IsVirtual(false); obj3.set_DeclaringType(typeof(Visuals)); obj3.set_Converter((JsonConverter<bool>)null); obj3.set_Getter((Func<object, bool>)((object obj) => ((Visuals)obj).Enabled)); obj3.set_Setter((Action<object, bool>)delegate(object obj, bool value) { ((Visuals)obj).Enabled = value; }); obj3.set_IgnoreCondition((JsonIgnoreCondition?)null); obj3.set_HasJsonInclude(false); obj3.set_IsExtensionData(false); obj3.set_NumberHandling((JsonNumberHandling?)null); obj3.set_PropertyName("Enabled"); obj3.set_JsonPropertyName("enabled"); JsonPropertyInfoValues<bool> val2 = obj3; array[1] = JsonMetadataServices.CreatePropertyInfo<bool>(options, val2); JsonPropertyInfoValues<List<Visual>> obj4 = new JsonPropertyInfoValues<List<Visual>>(); obj4.set_IsProperty(true); obj4.set_IsPublic(true); obj4.set_IsVirtual(false); obj4.set_DeclaringType(typeof(Visuals)); obj4.set_Converter((JsonConverter<List<Visual>>)null); obj4.set_Getter((Func<object, List<Visual>>)((object obj) => ((Visuals)obj).Items)); obj4.set_Setter((Action<object, List<Visual>>)delegate(object obj, List<Visual>? value) { ((Visuals)obj).Items = value; }); obj4.set_IgnoreCondition((JsonIgnoreCondition?)null); obj4.set_HasJsonInclude(false); obj4.set_IsExtensionData(false); obj4.set_NumberHandling((JsonNumberHandling?)null); obj4.set_PropertyName("Items"); obj4.set_JsonPropertyName("visuals"); JsonPropertyInfoValues<List<Visual>> val3 = obj4; array[2] = JsonMetadataServices.CreatePropertyInfo<List<Visual>>(options, val3); JsonPropertyInfoValues<object> obj5 = new JsonPropertyInfoValues<object>(); obj5.set_IsProperty(true); obj5.set_IsPublic(true); obj5.set_IsVirtual(false); obj5.set_DeclaringType(typeof(Visuals)); obj5.set_Converter((JsonConverter<object>)null); obj5.set_Getter((Func<object, object>)((object obj) => ((Visuals)obj).Tracking)); obj5.set_Setter((Action<object, object>)delegate(object obj, object? value) { ((Visuals)obj).Tracking = value; }); obj5.set_IgnoreCondition((JsonIgnoreCondition?)null); obj5.set_HasJsonInclude(false); obj5.set_IsExtensionData(false); obj5.set_NumberHandling((JsonNumberHandling?)null); obj5.set_PropertyName("Tracking"); obj5.set_JsonPropertyName("tracking"); JsonPropertyInfoValues<object> val4 = obj5; array[3] = JsonMetadataServices.CreatePropertyInfo<object>(options, val4); return (JsonPropertyInfo[])(object)array; } private JsonTypeInfo<PlaylistSearchResult> Create_PlaylistSearchResult(JsonSerializerOptions options) { JsonSerializerOptions options2 = options; if (!TryGetTypeInfoForRuntimeCustomConverter<PlaylistSearchResult>(options2, out JsonTypeInfo<PlaylistSearchResult> jsonTypeInfo)) { JsonObjectInfoValues<PlaylistSearchResult> obj = new JsonObjectInfoValues<PlaylistSearchResult>(); obj.set_ObjectCreator((Func<PlaylistSearchResult>)(() => new PlaylistSearchResult())); obj.set_ObjectWithParameterizedConstructorCreator((Func<object[], PlaylistSearchResult>)null); obj.set_PropertyMetadataInitializer((Func<JsonSerializerContext, JsonPropertyInfo[]>)((JsonSerializerContext _) => PlaylistSearchResultPropInit(options2))); obj.set_ConstructorParameterMetadataInitializer((Func<JsonParameterInfoValues[]>)null); obj.set_SerializeHandler((Action<Utf8JsonWriter, PlaylistSearchResult>)null); JsonObjectInfoValues<PlaylistSearchResult> val = obj; jsonTypeInfo = JsonMetadataServices.CreateObjectInfo<PlaylistSearchResult>(options2, val); ((JsonTypeInfo)jsonTypeInfo).NumberHandling = null; } ((JsonTypeInfo)jsonTypeInfo).OriginatingResolver = (IJsonTypeInfoResolver)(object)this; return jsonTypeInfo; } private static JsonPropertyInfo[] PlaylistSearchResultPropInit(JsonSerializerOptions options) { JsonPropertyInfo[] array = new JsonPropertyInfo[34]; JsonPropertyInfoValues<string> obj2 = new JsonPropertyInfoValues<string>(); obj2.set_IsProperty(true); obj2.set_IsPublic(true); obj2.set_IsVirtual(false); obj2.set_DeclaringType(typeof(PlaylistSearchResult)); obj2.set_Converter((JsonConverter<string>)null); obj2.set_Getter((Func<object, string>)((object obj) => ((PlaylistSearchResult)obj).Url)); obj2.set_Setter((Action<object, string>)null); obj2.set_IgnoreCondition((JsonIgnoreCondition?)null); obj2.set_HasJsonInclude(false); obj2.set_IsExtensionData(false); obj2.set_NumberHandling((JsonNumberHandling?)null); obj2.set_PropertyName("Url"); obj2.set_JsonPropertyName((string)null); JsonPropertyInfoValues<string> val = obj2; array[0] = JsonMetadataServices.CreatePropertyInfo<string>(options, val); JsonPropertyInfoValues<Uri> obj3 = new JsonPropertyInfoValues<Uri>(); obj3.set_IsProperty(true); obj3.set_IsPublic(true); obj3.set_IsVirtual(false); obj3.set_DeclaringType(typeof(Playlist)); obj3.set_Converter((JsonConverter<Uri>)null); obj3.set_Getter((Func<object, Uri>)((object obj) => ((Playlist)obj).ArtworkUrl)); obj3.set_Setter((Action<object, Uri>)delegate(object obj, Uri? value) { ((Playlist)obj).ArtworkUrl = value; }); obj3.set_IgnoreCondition((JsonIgnoreCondition?)null); obj3.set_HasJsonInclude(false); obj3.set_IsExtensionData(false); obj3.set_NumberHandling((JsonNumberHandling?)null); obj3.set_PropertyName("ArtworkUrl"); obj3.set_JsonPropertyName("artwork_url"); JsonPropertyInfoValues<Uri> val2 = obj3; array[1] = JsonMetadataServices.CreatePropertyInfo<Uri>(options, val2); JsonPropertyInfoValues<DateTimeOffset> obj4 = new JsonPropertyInfoValues<DateTimeOffset>(); obj4.set_IsProperty(true); obj4.set_IsPublic(true); obj4.set_IsVirtual(false); obj4.set_DeclaringType(typeof(Playlist)); obj4.set_Converter((JsonConverter<DateTimeOffset>)null); obj4.set_Getter((Func<object, DateTimeOffset>)((object obj) => ((Playlist)obj).CreatedAt)); obj4.set_Setter((Action<object, DateTimeOffset>)delegate(object obj, DateTimeOffset value) { ((Playlist)obj).CreatedAt = value; }); obj4.set_IgnoreCondition((JsonIgnoreCondition?)null); obj4.set_HasJsonInclude(false); obj4.set_IsExtensionData(false); obj4.set_NumberHandling((JsonNumberHandling?)null); obj4.set_PropertyName("CreatedAt"); obj4.set_JsonPropertyName("created_at"); JsonPropertyInfoValues<DateTimeOffset> val3 = obj4; array[2] = JsonMetadataServices.CreatePropertyInfo<DateTimeOffset>(options, val3); JsonPropertyInfoValues<string> obj5 = new JsonPropertyInfoValues<string>(); obj5.set_IsProperty(true); obj5.set_IsPublic(true); obj5.set_IsVirtual(false); obj5.set_DeclaringType(typeof(Playlist)); obj5.set_Converter((JsonConverter<string>)null); obj5.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).Description)); obj5.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).Description = value; }); obj5.set_IgnoreCondition((JsonIgnoreCondition?)null); obj5.set_HasJsonInclude(false); obj5.set_IsExtensionData(false); obj5.set_NumberHandling((JsonNumberHandling?)null); obj5.set_PropertyName("Description"); obj5.set_JsonPropertyName("description"); JsonPropertyInfoValues<string> val4 = obj5; array[3] = JsonMetadataServices.CreatePropertyInfo<string>(options, val4); JsonPropertyInfoValues<long> obj6 = new JsonPropertyInfoValues<long>(); obj6.set_IsProperty(true); obj6.set_IsPublic(true); obj6.set_IsVirtual(false); obj6.set_DeclaringType(typeof(Playlist)); obj6.set_Converter((JsonConverter<long>)null); obj6.set_Getter((Func<object, long>)((object obj) => ((Playlist)obj).Duration)); obj6.set_Setter((Action<object, long>)delegate(object obj, long value) { ((Playlist)obj).Duration = value; }); obj6.set_IgnoreCondition((JsonIgnoreCondition?)null); obj6.set_HasJsonInclude(false); obj6.set_IsExtensionData(false); obj6.set_NumberHandling((JsonNumberHandling?)null); obj6.set_PropertyName("Duration"); obj6.set_JsonPropertyName("duration"); JsonPropertyInfoValues<long> val5 = obj6; array[4] = JsonMetadataServices.CreatePropertyInfo<long>(options, val5); JsonPropertyInfoValues<string> obj7 = new JsonPropertyInfoValues<string>(); obj7.set_IsProperty(true); obj7.set_IsPublic(true); obj7.set_IsVirtual(false); obj7.set_DeclaringType(typeof(Playlist)); obj7.set_Converter((JsonConverter<string>)null); obj7.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).EmbeddableBy)); obj7.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).EmbeddableBy = value; }); obj7.set_IgnoreCondition((JsonIgnoreCondition?)null); obj7.set_HasJsonInclude(false); obj7.set_IsExtensionData(false); obj7.set_NumberHandling((JsonNumberHandling?)null); obj7.set_PropertyName("EmbeddableBy"); obj7.set_JsonPropertyName("embeddable_by"); JsonPropertyInfoValues<string> val6 = obj7; array[5] = JsonMetadataServices.CreatePropertyInfo<string>(options, val6); JsonPropertyInfoValues<string> obj8 = new JsonPropertyInfoValues<string>(); obj8.set_IsProperty(true); obj8.set_IsPublic(true); obj8.set_IsVirtual(false); obj8.set_DeclaringType(typeof(Playlist)); obj8.set_Converter((JsonConverter<string>)null); obj8.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).Genre)); obj8.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).Genre = value; }); obj8.set_IgnoreCondition((JsonIgnoreCondition?)null); obj8.set_HasJsonInclude(false); obj8.set_IsExtensionData(false); obj8.set_NumberHandling((JsonNumberHandling?)null); obj8.set_PropertyName("Genre"); obj8.set_JsonPropertyName("genre"); JsonPropertyInfoValues<string> val7 = obj8; array[6] = JsonMetadataServices.CreatePropertyInfo<string>(options, val7); JsonPropertyInfoValues<long?> obj9 = new JsonPropertyInfoValues<long?>(); obj9.set_IsProperty(true); obj9.set_IsPublic(true); obj9.set_IsVirtual(false); obj9.set_DeclaringType(typeof(Playlist)); obj9.set_Converter((JsonConverter<long?>)null); obj9.set_Getter((Func<object, long?>)((object obj) => ((Playlist)obj).Id)); obj9.set_Setter((Action<object, long?>)delegate(object obj, long? value) { ((Playlist)obj).Id = value; }); obj9.set_IgnoreCondition((JsonIgnoreCondition?)null); obj9.set_HasJsonInclude(false); obj9.set_IsExtensionData(false); obj9.set_NumberHandling((JsonNumberHandling?)null); obj9.set_PropertyName("Id"); obj9.set_JsonPropertyName("id"); JsonPropertyInfoValues<long?> val8 = obj9; array[7] = JsonMetadataServices.CreatePropertyInfo<long?>(options, val8); JsonPropertyInfoValues<Kind> obj10 = new JsonPropertyInfoValues<Kind>(); obj10.set_IsProperty(true); obj10.set_IsPublic(true); obj10.set_IsVirtual(false); obj10.set_DeclaringType(typeof(Playlist)); obj10.set_Converter((JsonConverter<Kind>)null); obj10.set_Getter((Func<object, Kind>)((object obj) => ((Playlist)obj).Kind)); obj10.set_Setter((Action<object, Kind>)delegate(object obj, Kind value) { ((Playlist)obj).Kind = value; }); obj10.set_IgnoreCondition((JsonIgnoreCondition?)null); obj10.set_HasJsonInclude(false); obj10.set_IsExtensionData(false); obj10.set_NumberHandling((JsonNumberHandling?)null); obj10.set_PropertyName("Kind"); obj10.set_JsonPropertyName("kind"); JsonPropertyInfoValues<Kind> val9 = obj10; array[8] = JsonMetadataServices.CreatePropertyInfo<Kind>(options, val9); JsonPropertyInfoValues<string> obj11 = new JsonPropertyInfoValues<string>(); obj11.set_IsProperty(true); obj11.set_IsPublic(true); obj11.set_IsVirtual(false); obj11.set_DeclaringType(typeof(Playlist)); obj11.set_Converter((JsonConverter<string>)null); obj11.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).LabelName)); obj11.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).LabelName = value; }); obj11.set_IgnoreCondition((JsonIgnoreCondition?)null); obj11.set_HasJsonInclude(false); obj11.set_IsExtensionData(false); obj11.set_NumberHandling((JsonNumberHandling?)null); obj11.set_PropertyName("LabelName"); obj11.set_JsonPropertyName("label_name"); JsonPropertyInfoValues<string> val10 = obj11; array[9] = JsonMetadataServices.CreatePropertyInfo<string>(options, val10); JsonPropertyInfoValues<DateTimeOffset> obj12 = new JsonPropertyInfoValues<DateTimeOffset>(); obj12.set_IsProperty(true); obj12.set_IsPublic(true); obj12.set_IsVirtual(false); obj12.set_DeclaringType(typeof(Playlist)); obj12.set_Converter((JsonConverter<DateTimeOffset>)null); obj12.set_Getter((Func<object, DateTimeOffset>)((object obj) => ((Playlist)obj).LastModified)); obj12.set_Setter((Action<object, DateTimeOffset>)delegate(object obj, DateTimeOffset value) { ((Playlist)obj).LastModified = value; }); obj12.set_IgnoreCondition((JsonIgnoreCondition?)null); obj12.set_HasJsonInclude(false); obj12.set_IsExtensionData(false); obj12.set_NumberHandling((JsonNumberHandling?)null); obj12.set_PropertyName("LastModified"); obj12.set_JsonPropertyName("last_modified"); JsonPropertyInfoValues<DateTimeOffset> val11 = obj12; array[10] = JsonMetadataServices.CreatePropertyInfo<DateTimeOffset>(options, val11); JsonPropertyInfoValues<string> obj13 = new JsonPropertyInfoValues<string>(); obj13.set_IsProperty(true); obj13.set_IsPublic(true); obj13.set_IsVirtual(false); obj13.set_DeclaringType(typeof(Playlist)); obj13.set_Converter((JsonConverter<string>)null); obj13.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).License)); obj13.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).License = value; }); obj13.set_IgnoreCondition((JsonIgnoreCondition?)null); obj13.set_HasJsonInclude(false); obj13.set_IsExtensionData(false); obj13.set_NumberHandling((JsonNumberHandling?)null); obj13.set_PropertyName("License"); obj13.set_JsonPropertyName("license"); JsonPropertyInfoValues<string> val12 = obj13; array[11] = JsonMetadataServices.CreatePropertyInfo<string>(options, val12); JsonPropertyInfoValues<long> obj14 = new JsonPropertyInfoValues<long>(); obj14.set_IsProperty(true); obj14.set_IsPublic(true); obj14.set_IsVirtual(false); obj14.set_DeclaringType(typeof(Playlist)); obj14.set_Converter((JsonConverter<long>)null); obj14.set_Getter((Func<object, long>)((object obj) => ((Playlist)obj).LikesCount)); obj14.set_Setter((Action<object, long>)delegate(object obj, long value) { ((Playlist)obj).LikesCount = value; }); obj14.set_IgnoreCondition((JsonIgnoreCondition?)null); obj14.set_HasJsonInclude(false); obj14.set_IsExtensionData(false); obj14.set_NumberHandling((JsonNumberHandling?)null); obj14.set_PropertyName("LikesCount"); obj14.set_JsonPropertyName("likes_count"); JsonPropertyInfoValues<long> val13 = obj14; array[12] = JsonMetadataServices.CreatePropertyInfo<long>(options, val13); JsonPropertyInfoValues<bool> obj15 = new JsonPropertyInfoValues<bool>(); obj15.set_IsProperty(true); obj15.set_IsPublic(true); obj15.set_IsVirtual(false); obj15.set_DeclaringType(typeof(Playlist)); obj15.set_Converter((JsonConverter<bool>)null); obj15.set_Getter((Func<object, bool>)((object obj) => ((Playlist)obj).ManagedByFeeds)); obj15.set_Setter((Action<object, bool>)delegate(object obj, bool value) { ((Playlist)obj).ManagedByFeeds = value; }); obj15.set_IgnoreCondition((JsonIgnoreCondition?)null); obj15.set_HasJsonInclude(false); obj15.set_IsExtensionData(false); obj15.set_NumberHandling((JsonNumberHandling?)null); obj15.set_PropertyName("ManagedByFeeds"); obj15.set_JsonPropertyName("managed_by_feeds"); JsonPropertyInfoValues<bool> val14 = obj15; array[13] = JsonMetadataServices.CreatePropertyInfo<bool>(options, val14); JsonPropertyInfoValues<string> obj16 = new JsonPropertyInfoValues<string>(); obj16.set_IsProperty(true); obj16.set_IsPublic(true); obj16.set_IsVirtual(false); obj16.set_DeclaringType(typeof(Playlist)); obj16.set_Converter((JsonConverter<string>)null); obj16.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).Permalink)); obj16.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).Permalink = value; }); obj16.set_IgnoreCondition((JsonIgnoreCondition?)null); obj16.set_HasJsonInclude(false); obj16.set_IsExtensionData(false); obj16.set_NumberHandling((JsonNumberHandling?)null); obj16.set_PropertyName("Permalink"); obj16.set_JsonPropertyName("permalink"); JsonPropertyInfoValues<string> val15 = obj16; array[14] = JsonMetadataServices.CreatePropertyInfo<string>(options, val15); JsonPropertyInfoValues<Uri> obj17 = new JsonPropertyInfoValues<Uri>(); obj17.set_IsProperty(true); obj17.set_IsPublic(true); obj17.set_IsVirtual(false); obj17.set_DeclaringType(typeof(Playlist)); obj17.set_Converter((JsonConverter<Uri>)null); obj17.set_Getter((Func<object, Uri>)((object obj) => ((Playlist)obj).PermalinkUrl)); obj17.set_Setter((Action<object, Uri>)delegate(object obj, Uri? value) { ((Playlist)obj).PermalinkUrl = value; }); obj17.set_IgnoreCondition((JsonIgnoreCondition?)null); obj17.set_HasJsonInclude(false); obj17.set_IsExtensionData(false); obj17.set_NumberHandling((JsonNumberHandling?)null); obj17.set_PropertyName("PermalinkUrl"); obj17.set_JsonPropertyName("permalink_url"); JsonPropertyInfoValues<Uri> val16 = obj17; array[15] = JsonMetadataServices.CreatePropertyInfo<Uri>(options, val16); JsonPropertyInfoValues<bool> obj18 = new JsonPropertyInfoValues<bool>(); obj18.set_IsProperty(true); obj18.set_IsPublic(true); obj18.set_IsVirtual(false); obj18.set_DeclaringType(typeof(Playlist)); obj18.set_Converter((JsonConverter<bool>)null); obj18.set_Getter((Func<object, bool>)((object obj) => ((Playlist)obj).Public)); obj18.set_Setter((Action<object, bool>)delegate(object obj, bool value) { ((Playlist)obj).Public = value; }); obj18.set_IgnoreCondition((JsonIgnoreCondition?)null); obj18.set_HasJsonInclude(false); obj18.set_IsExtensionData(false); obj18.set_NumberHandling((JsonNumberHandling?)null); obj18.set_PropertyName("Public"); obj18.set_JsonPropertyName("public"); JsonPropertyInfoValues<bool> val17 = obj18; array[16] = JsonMetadataServices.CreatePropertyInfo<bool>(options, val17); JsonPropertyInfoValues<string> obj19 = new JsonPropertyInfoValues<string>(); obj19.set_IsProperty(true); obj19.set_IsPublic(true); obj19.set_IsVirtual(false); obj19.set_DeclaringType(typeof(Playlist)); obj19.set_Converter((JsonConverter<string>)null); obj19.set_Getter((Func<object, string>)((object obj) => ((Playlist)obj).PurchaseTitle)); obj19.set_Setter((Action<object, string>)delegate(object obj, string? value) { ((Playlist)obj).PurchaseTitle = value; }); obj19.set_Ign
System.Numerics.Vectors.dll
Decompiled 2 months 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; 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")] [assembly: TypeForwardedTo(typeof(Matrix3x2))] [assembly: TypeForwardedTo(typeof(Matrix4x4))] [assembly: TypeForwardedTo(typeof(Plane))] [assembly: TypeForwardedTo(typeof(Quaternion))] [assembly: TypeForwardedTo(typeof(Vector2))] [assembly: TypeForwardedTo(typeof(Vector3))] [assembly: TypeForwardedTo(typeof(Vector4))] [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 { } } 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.Compile
System.Runtime.CompilerServices.Unsafe.dll
Decompiled 2 months 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 { } }
System.Text.Encodings.Web.dll
Decompiled 2 months 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(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [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("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [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("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.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; return (long)(num2 & num3) < 0L; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string TextEncoderDoesNotImplementMaxOutputCharsPerInputChar => GetResourceString("TextEncoderDoesNotImplementMaxOutputCharsPerInputChar"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Numerics { internal static class BitOperations { private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32] { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Log2(uint value) { return Log2SoftwareFallback(value | 1u); } private static int Log2SoftwareFallback(uint value) { value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref MemoryMarshal.GetReference(Log2DeBruijn), (IntPtr)(nint)(value * 130329821 >> 27)); } } } namespace System.Text { internal static class UnicodeDebug { [Conditional("DEBUG")] internal static void AssertIsBmpCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsBmpCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsHighSurrogateCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsHighSurrogateCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsLowSurrogateCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsLowSurrogateCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsValidCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsValidCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsValidScalar(uint scalarValue) { System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue); } [Conditional("DEBUG")] internal static void AssertIsValidSupplementaryPlaneScalar(uint scalarValue) { if (System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue)) { System.Text.UnicodeUtility.IsBmpCodePoint(scalarValue); } } private static string ToHexString(uint codePoint) { return FormattableString.Invariant($"U+{codePoint:X4}"); } } internal static class UnicodeUtility { public const uint ReplacementChar = 65533u; public static int GetPlane(uint codePoint) { return (int)(codePoint >> 16); } public static uint GetScalarFromUtf16SurrogatePair(uint highSurrogateCodePoint, uint lowSurrogateCodePoint) { return (highSurrogateCodePoint << 10) + lowSurrogateCodePoint - 56613888; } public static int GetUtf16SequenceLength(uint value) { value -= 65536; value += 33554432; value >>= 24; return (int)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void GetUtf16SurrogatesFromSupplementaryPlaneScalar(uint value, out char highSurrogateCodePoint, out char lowSurrogateCodePoint) { highSurrogateCodePoint = (char)(value + 56557568 >> 10); lowSurrogateCodePoint = (char)((value & 0x3FF) + 56320); } public static int GetUtf8SequenceLength(uint value) { int num = (int)(value - 2048) >> 31; value ^= 0xF800u; value -= 63616; value += 67108864; value >>= 24; return (int)value + num * 2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAsciiCodePoint(uint value) { return value <= 127; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsBmpCodePoint(uint value) { return value <= 65535; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHighSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 55296u, 56319u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound) { return value - lowerBound <= upperBound - lowerBound; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLowSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 56320u, 57343u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 55296u, 57343u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidCodePoint(uint codePoint) { return codePoint <= 1114111; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidUnicodeScalar(uint value) { return ((value - 1114112) ^ 0xD800) >= 4293855232u; } } internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => ref _chars[index]; public Span<char> RawChars => _chars; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public void EnsureCapacity(int capacity) { if ((uint)capacity > (uint)_chars.Length) { Grow(capacity - _pos); } } public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public override string ToString() { string result = _chars.Slice(0, _pos).ToString(); Dispose(); return result; } public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } charsWritten = 0; Dispose(); return false; } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int length = _pos - index; _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string s) { if (s != null) { int length = s.Length; if (_pos > _chars.Length - length) { Grow(length); } int length2 = _pos - index; _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); s.AsSpan().CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; Span<char> chars = _chars; if ((uint)pos < (uint)chars.Length) { chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string s) { if (s != null) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.AsSpan().CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span<char> span = _chars.Slice(_pos, count); for (int i = 0; i < span.Length; i++) { span[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { 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 _) { _value = scalarValue; } public static bool operator ==(Rune left, Rune right) { return left._value == right._value; } public static bool operator !=(Rune left, Rune right) { return left._value != right._value; } public static bool IsControl(Rune value) { return ((value._value + 1) & 0xFFFFFF7Fu) <= 32; } public static OperationStatus DecodeFromUtf16(ReadOnlySpan<char> source, out Rune result, out int charsConsumed) { if (!source.IsEmpty) { char c = source[0]; if (TryCreate(c, out result)) { charsConsumed = 1; return OperationStatus.Done; } if (1u < (uint)source.Length) { char lowSurrogate = source[1]; if (TryCreate(c, lowSurrogate, out result)) { charsConsumed = 2; return OperationStatus.Done; } } else if (char.IsHighSurrogate(c)) { goto IL_004c; } charsConsumed = 1; result = ReplacementChar; return OperationStatus.InvalidData; } goto IL_004c; IL_004c: charsConsumed = source.Length; result = ReplacementChar; return OperationStatus.NeedMoreData; } public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> source, out Rune result, out int bytesConsumed) { int num = 0; uint num2; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Text.UnicodeUtility.IsAsciiCodePoint(num2)) { goto IL_0021; } if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 194u, 244u)) { num2 = num2 - 194 << 6; num++; if ((uint)num >= (uint)source.Length) { goto IL_0163; } int num3 = (sbyte)source[num]; if (num3 < -64) { num2 += (uint)num3; num2 += 128; num2 += 128; if (num2 < 2048) { goto IL_0021; } if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2080u, 3343u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2912u, 2943u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 3072u, 3087u)) { num++; if ((uint)num >= (uint)source.Length) { goto IL_0163; } num3 = (sbyte)source[num]; if (num3 < -64) { num2 <<= 6; num2 += (uint)num3; num2 += 128; num2 -= 131072; if (num2 > 65535) { num++; if ((uint)num >= (uint)source.Length) { goto IL_0163; } num3 = (sbyte)source[num]; if (num3 >= -64) { goto IL_0153; } num2 <<= 6; num2 += (uint)num3; num2 += 128; num2 -= 4194304; } goto IL_0021; } } } } else { num = 1; } goto IL_0153; } goto IL_0163; IL_0021: bytesConsumed = num + 1; result = UnsafeCreate(num2); return OperationStatus.Done; IL_0153: bytesConsumed = num; result = ReplacementChar; return OperationStatus.InvalidData; IL_0163: bytesConsumed = num; result = ReplacementChar; return OperationStatus.NeedMoreData; } public override bool Equals([NotNullWhen(true)] object obj) { if (obj is Rune other) { return Equals(other); } return false; } public bool Equals(Rune other) { return this == other; } public override int GetHashCode() { return Value; } public static bool TryCreate(char ch, out Rune result) { if (!System.Text.UnicodeUtility.IsSurrogateCodePoint(ch)) { result = UnsafeCreate(ch); return true; } result = default(Rune); return false; } public static bool TryCreate(char highSurrogate, char lowSurrogate, out Rune result) { uint num = (uint)(highSurrogate - 55296); uint num2 = (uint)(lowSurrogate - 56320); if ((num | num2) <= 1023) { result = UnsafeCreate((uint)((int)(num << 10) + (lowSurrogate - 56320) + 65536)); return true; } result = default(Rune); return false; } public bool TryEncodeToUtf16(Span<char> destination, out int charsWritten) { if (destination.Length >= 1) { if (IsBmp) { destination[0] = (char)_value; charsWritten = 1; return true; } if (destination.Length >= 2) { System.Text.UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out destination[0], out destination[1]); charsWritten = 2; return true; } } charsWritten = 0; return false; } public bool TryEncodeToUtf8(Span<byte> destination, out int bytesWritten) { if (destination.Length >= 1) { if (IsAscii) { destination[0] = (byte)_value; bytesWritten = 1; return true; } if (destination.Length >= 2) { if (_value <= 2047) { destination[0] = (byte)(_value + 12288 >> 6); destination[1] = (byte)((_value & 0x3F) + 128); bytesWritten = 2; return true; } if (destination.Length >= 3) { if (_value <= 65535) { destination[0] = (byte)(_value + 917504 >> 12); destination[1] = (byte)(((_value & 0xFC0) >> 6) + 128); destination[2] = (byte)((_value & 0x3F) + 128); bytesWritten = 3; return true; } if (destination.Length >= 4) { destination[0] = (byte)(_value + 62914560 >> 18); destination[1] = (byte)(((_value & 0x3F000) >> 12) + 128); destination[2] = (byte)(((_value & 0xFC0) >> 6) + 128); destination[3] = (byte)((_value & 0x3F) + 128); bytesWritten = 4; return true; } } } } bytesWritten = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Rune UnsafeCreate(uint scalarValue) { return new Rune(scalarValue, _: false); } } } namespace System.Text.Unicode { internal static class UnicodeHelpers { internal const int UNICODE_LAST_CODEPOINT = 1114111; private static ReadOnlySpan<byte> DefinedCharsBitmapSpan => new byte[8192] { 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, 0, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 240, 215, 255, 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 127, 254, 255, 255, 255, 255, 255, 231, 254, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 135, 31, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 255, 255, 63, 255, 127, 255, 255, 255, 79, 255, 7, 255, 255, 255, 127, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 239, 159, 249, 255, 255, 253, 197, 243, 159, 121, 128, 176, 207, 255, 255, 127, 238, 135, 249, 255, 255, 253, 109, 211, 135, 57, 2, 94, 192, 255, 127, 0, 238, 191, 251, 255, 255, 253, 237, 243, 191, 59, 1, 0, 207, 255, 3, 254, 238, 159, 249, 255, 255, 253, 237, 243, 159, 57, 224, 176, 207, 255, 255, 0, 236, 199, 61, 214, 24, 199, 255, 195, 199, 61, 129, 0, 192, 255, 255, 7, 255, 223, 253, 255, 255, 253, 255, 243, 223, 61, 96, 39, 207, 255, 128, 255, 255, 223, 253, 255, 255, 253, 239, 243, 223, 61, 96, 96, 207, 255, 14, 0, 255, 223, 253, 255, 255, 255, 255, 255, 223, 253, 240, 255, 207, 255, 255, 255, 238, 255, 127, 252, 255, 255, 251, 47, 127, 132, 95, 255, 192, 255, 28, 0, 254, 255, 255, 255, 255, 255, 255, 135, 255, 255, 255, 15, 0, 0, 0, 0, 214, 247, 255, 255, 175, 255, 255, 63, 95, 127, 255, 243, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 31, 254, 255, 255, 255, 255, 254, 255, 255, 255, 223, 255, 223, 255, 7, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 32, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 61, 127, 61, 255, 255, 255, 255, 255, 61, 255, 255, 255, 255, 61, 127, 61, 255, 127, 255, 255, 255, 255, 255, 255, 255, 61, 255, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 31, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 63, 128, 255, 255, 127, 0, 255, 255, 15, 0, 255, 223, 13, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 3, 255, 3, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 255, 255, 7, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 255, 255, 255, 127, 255, 15, 255, 15, 241, 255, 255, 255, 255, 63, 31, 0, 255, 255, 255, 255, 255, 15, 255, 255, 255, 3, 255, 199, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 255, 255, 255, 255, 127, 255, 255, 255, 159, 255, 3, 255, 3, 255, 63, 255, 255, 255, 127, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 240, 255, 255, 255, 255, 255, 255, 255, 248, 255, 227, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 255, 255, 231, 255, 0, 255, 255, 255, 255, 255, 7, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 63, 255, 255, 255, 255, 63, 63, 255, 170, 255, 255, 255, 63, 255, 255, 255, 255, 255, 255, 223, 255, 223, 255, 207, 239, 255, 255, 220, 127, 0, 248, 255, 255, 255, 124, 255, 255, 255, 255, 255, 127, 223, 255, 243, 255, 255, 127, 255, 31, 255, 255, 255, 255, 1, 0, 255, 255, 255, 255, 1, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, 255, 7, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 254, 255, 255, 255, 255, 191, 32, 255, 255, 255, 255, 255, 255, 255, 128, 1, 128, 255, 255, 127, 0, 127, 127, 127, 127, 127, 127, 127, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 0, 0, 0, 255, 255, 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 0, 0, 255, 15, 254, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 224, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 127, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 235, 3, 0, 0, 252, 255, 255, 255, 255, 255, 255, 31, 255, 3, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, 63, 192, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 128, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 195, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 127, 0, 255, 63, 255, 243, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 0, 0, 248, 255, 255, 127, 0, 126, 126, 126, 0, 127, 127, 255, 255, 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 127, 248, 255, 255, 255, 255, 255, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 0, 0, 0, 127, 0, 248, 224, 255, 255, 127, 95, 219, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 0, 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 128, 0, 0, 0, 0, 255, 255, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 247, 255, 127, 15, 223, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 252, 252, 252, 28, 127, 127, 0, 62 }; internal static ReadOnlySpan<byte> GetDefinedBmpCodePointsBitmapLittleEndian() { return DefinedCharsBitmapSpan; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void GetUtf16SurrogatePairFromAstralScalarValue(uint scalar, out char highSurrogate, out char lowSurrogate) { highSurrogate = (char)(scalar + 56557568 >> 10); lowSurrogate = (char)((scalar & 0x3FF) + 56320); } internal static int GetUtf8RepresentationForScalarValue(uint scalar) { if (scalar <= 127) { return (byte)scalar; } if (scalar <= 2047) { byte b = (byte)(0xC0u | (scalar >> 6)); 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 false; } [MethodImpl(MethodI
System.Text.Json.dll
Decompiled 2 months 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.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Pipelines; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Reflection; using System.Text.Json.Schema; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Converters; using System.Text.Json.Serialization.Metadata; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using FxResources.System.Text.Json; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Text.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.\r\n\r\nThe System.Text.Json library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] [assembly: AssemblyFileVersion("9.0.24.52809")] [assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Text.Json")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("9.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class RequiresLocationAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class ParamCollectionAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Text.Json { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { ToCharsBuffer(readOnlySpan[i], buffer, num, casing); num += 2; } return buffer.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { return TryDecodeFromUtf16_Scalar(chars, bytes, out charsProcessed); } private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { if (IntPtr.Size == 8) { ulong num = (uint)(c - 48); long num2 = -17875860044349952L << (int)num; ulong num3 = num - 64; return (long)((ulong)num2 & num3) < 0L; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class Obsoletions { internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; internal const string ThreadAbortDiagId = "SYSLIB0006"; internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; internal const string AuthenticationManagerMessage = "AuthenticationManager is not supported. Methods will no-op or throw PlatformNotSupportedException."; internal const string AuthenticationManagerDiagId = "SYSLIB0009"; internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; internal const string RemotingApisDiagId = "SYSLIB0010"; internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; internal const string BinaryFormatterDiagId = "SYSLIB0011"; internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; internal const string CodeBaseDiagId = "SYSLIB0012"; internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; internal const string EscapeUriStringDiagId = "SYSLIB0013"; internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; internal const string WebRequestDiagId = "SYSLIB0014"; internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; internal const string GetContextInfoDiagId = "SYSLIB0016"; internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; internal const string RijndaelDiagId = "SYSLIB0022"; internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use X509CertificateLoader to create a new certificate."; internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; internal const string UseManagedSha1DiagId = "SYSLIB0030"; internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead."; internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; internal const string TlsVersion10and11DiagId = "SYSLIB0039"; internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code."; internal const string EncryptionPolicyDiagId = "SYSLIB0040"; internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations."; internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041"; internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys."; internal const string EccXmlExportImportDiagId = "SYSLIB0042"; internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead."; internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043"; internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."; internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044"; internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead."; internal const string CryptoStringFactoryDiagId = "SYSLIB0045"; internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code."; internal const string ControlledExecutionRunDiagId = "SYSLIB0046"; internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution."; internal const string XmlSecureResolverDiagId = "SYSLIB0047"; internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead."; internal const string RsaEncryptDecryptDiagId = "SYSLIB0048"; internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties."; internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049"; internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used."; internal const string LegacyFormatterDiagId = "SYSLIB0050"; internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code."; internal const string LegacyFormatterImplDiagId = "SYSLIB0051"; internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported."; internal const string RegexExtensibilityDiagId = "SYSLIB0052"; internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size."; internal const string AesGcmTagConstructorDiagId = "SYSLIB0053"; internal const string ThreadVolatileReadWriteMessage = "Thread.VolatileRead and Thread.VolatileWrite are obsolete. Use Volatile.Read or Volatile.Write respectively instead."; internal const string ThreadVolatileReadWriteDiagId = "SYSLIB0054"; internal const string ArmIntrinsicPerformsUnsignedOperationMessage = "The underlying hardware instruction does not perform a signed saturate narrowing operation, and it always returns an unsigned result. Use the unsigned overload instead."; internal const string ArmIntrinsicPerformsUnsignedOperationDiagId = "SYSLIB0055"; internal const string LoadFromHashAlgorithmMessage = "LoadFrom with a custom AssemblyHashAlgorithm is obsolete. Use overloads without an AssemblyHashAlgorithm."; internal const string LoadFromHashAlgorithmDiagId = "SYSLIB0056"; internal const string X509CtorCertDataObsoleteMessage = "Loading certificate data through the constructor or Import is obsolete. Use X509CertificateLoader instead to load certificates."; internal const string X509CtorCertDataObsoleteDiagId = "SYSLIB0057"; } internal static class SR { private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue(); private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge"); internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss"); internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16"); internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16"); internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose"); internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty"); internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8"); internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64"); internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16"); internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16"); internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8"); internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray"); internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty"); internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose"); internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject"); internal static string DepthTooLarge => GetResourceString("DepthTooLarge"); internal static string DestinationTooShort => GetResourceString("DestinationTooShort"); internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid"); internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound"); internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound"); internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson"); internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound"); internal static string ExpectedFalse => GetResourceString("ExpectedFalse"); internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens"); internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken"); internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound"); internal static string ExpectedNull => GetResourceString("ExpectedNull"); internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound"); internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound"); internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound"); internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound"); internal static string ExpectedTrue => GetResourceString("ExpectedTrue"); internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound"); internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan"); internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter"); internal static string InvalidCast => GetResourceString("InvalidCast"); internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString"); internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString"); internal static string UnsupportedEnumIdentifier => GetResourceString("UnsupportedEnumIdentifier"); internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive"); internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString"); internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments"); internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType"); internal static string JsonElementDeepEqualsInsufficientExecutionStack => GetResourceString("JsonElementDeepEqualsInsufficientExecutionStack"); internal static string JsonNumberExponentTooLarge => GetResourceString("JsonNumberExponentTooLarge"); internal static string DefaultTypeInfoResolverImmutable => GetResourceString("DefaultTypeInfoResolverImmutable"); internal static string TypeInfoResolverChainImmutable => GetResourceString("TypeInfoResolverChainImmutable"); internal static string TypeInfoImmutable => GetResourceString("TypeInfoImmutable"); internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive"); internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid"); internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray"); internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty"); internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge"); internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge"); internal static string FormatDecimal => GetResourceString("FormatDecimal"); internal static string FormatDouble => GetResourceString("FormatDouble"); internal static string FormatInt32 => GetResourceString("FormatInt32"); internal static string FormatInt64 => GetResourceString("FormatInt64"); internal static string FormatSingle => GetResourceString("FormatSingle"); internal static string FormatUInt32 => GetResourceString("FormatUInt32"); internal static string FormatUInt64 => GetResourceString("FormatUInt64"); internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal"); internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign"); internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData"); internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported"); internal static string ValueTooLarge => GetResourceString("ValueTooLarge"); internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd"); internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue"); internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType"); internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize"); internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar"); internal static string InvalidComparison => GetResourceString("InvalidComparison"); internal static string UnsupportedFormat => GetResourceString("UnsupportedFormat"); internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment"); internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd"); internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd"); internal static string SerializerOptionsReadOnly => GetResourceString("SerializerOptionsReadOnly"); internal static string SerializerOptions_InvalidChainedResolver => GetResourceString("SerializerOptions_InvalidChainedResolver"); internal static string StreamNotWritable => GetResourceString("StreamNotWritable"); internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter"); internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict"); internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull"); internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid"); internal static string PropertyTypeNotNullable => GetResourceString("PropertyTypeNotNullable"); internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute"); internal static string ExtensionDataConflictsWithUnmappedMemberHandling => GetResourceString("ExtensionDataConflictsWithUnmappedMemberHandling"); internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType"); internal static string TypeRequiresAsyncSerialization => GetResourceString("TypeRequiresAsyncSerialization"); internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment"); internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment"); internal static string CannotSkip => GetResourceString("CannotSkip"); internal static string NotEnoughData => GetResourceString("NotEnoughData"); internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator"); internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments"); internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor"); internal static string DeserializeInterfaceOrAbstractType => GetResourceString("DeserializeInterfaceOrAbstractType"); internal static string DeserializationMustSpecifyTypeDiscriminator => GetResourceString("DeserializationMustSpecifyTypeDiscriminator"); internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible"); internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid"); internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead"); internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible"); internal static string ResolverTypeNotCompatible => GetResourceString("ResolverTypeNotCompatible"); internal static string ResolverTypeInfoOptionsNotCompatible => GetResourceString("ResolverTypeInfoOptionsNotCompatible"); internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite"); internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull"); internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute"); internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize"); internal static string FormatByte => GetResourceString("FormatByte"); internal static string FormatInt16 => GetResourceString("FormatInt16"); internal static string FormatSByte => GetResourceString("FormatSByte"); internal static string FormatUInt16 => GetResourceString("FormatUInt16"); internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected"); internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber"); internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable"); internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound"); internal static string MetadataIdCannotBeCombinedWithRef => GetResourceString("MetadataIdCannotBeCombinedWithRef"); internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType"); internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues"); internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed"); internal static string MetadataInvalidPropertyInArrayMetadata => GetResourceString("MetadataInvalidPropertyInArrayMetadata"); internal static string MetadataStandaloneValuesProperty => GetResourceString("MetadataStandaloneValuesProperty"); internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties"); internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound"); internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString"); internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign"); internal static string MetadataUnexpectedProperty => GetResourceString("MetadataUnexpectedProperty"); internal static string UnmappedJsonProperty => GetResourceString("UnmappedJsonProperty"); internal static string DuplicateMetadataProperty => GetResourceString("DuplicateMetadataProperty"); internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter"); internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding"); internal static string ObjectWithParameterizedCtorRefMetadataNotSupported => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotSupported"); internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull"); internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType"); internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam"); internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded"); internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType"); internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported"); internal static string JsonIncludeOnInaccessibleProperty => GetResourceString("JsonIncludeOnInaccessibleProperty"); internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember"); internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection"); internal static string ConstructorContainsNullParameterNames => GetResourceString("ConstructorContainsNullParameterNames"); internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified"); internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid"); internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported"); internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid"); internal static string NumberHandlingOnPropertyInvalid => GetResourceString("NumberHandlingOnPropertyInvalid"); internal static string ConverterCanConvertMultipleTypes => GetResourceString("ConverterCanConvertMultipleTypes"); internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType"); internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue"); internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull"); internal static string SerializerConverterFactoryReturnsJsonConverterFactory => GetResourceString("SerializerConverterFactoryReturnsJsonConverterFactory"); internal static string SerializerConverterFactoryInvalidArgument => GetResourceString("SerializerConverterFactoryInvalidArgument"); internal static string NodeElementWrongType => GetResourceString("NodeElementWrongType"); internal static string NodeElementCannotBeObjectOrArray => GetResourceString("NodeElementCannotBeObjectOrArray"); internal static string NodeAlreadyHasParent => GetResourceString("NodeAlreadyHasParent"); internal static string NodeCycleDetected => GetResourceString("NodeCycleDetected"); internal static string NodeUnableToConvert => GetResourceString("NodeUnableToConvert"); internal static string NodeUnableToConvertElement => GetResourceString("NodeUnableToConvertElement"); internal static string NodeValueNotAllowed => GetResourceString("NodeValueNotAllowed"); internal static string NodeWrongType => GetResourceString("NodeWrongType"); internal static string NodeParentWrongType => GetResourceString("NodeParentWrongType"); internal static string NodeDuplicateKey => GetResourceString("NodeDuplicateKey"); internal static string SerializerContextOptionsReadOnly => GetResourceString("SerializerContextOptionsReadOnly"); internal static string ConverterForPropertyMustBeValid => GetResourceString("ConverterForPropertyMustBeValid"); internal static string NoMetadataForType => GetResourceString("NoMetadataForType"); internal static string AmbiguousMetadataForType => GetResourceString("AmbiguousMetadataForType"); internal static string CollectionIsReadOnly => GetResourceString("CollectionIsReadOnly"); internal static string ArrayIndexNegative => GetResourceString("ArrayIndexNegative"); internal static string ArrayTooSmall => GetResourceString("ArrayTooSmall"); internal static string NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty => GetResourceString("NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty"); internal static string NoMetadataForTypeProperties => GetResourceString("NoMetadataForTypeProperties"); internal static string FieldCannotBeVirtual => GetResourceString("FieldCannotBeVirtual"); internal static string MissingFSharpCoreMember => GetResourceString("MissingFSharpCoreMember"); internal static string FSharpDiscriminatedUnionsNotSupported => GetResourceString("FSharpDiscriminatedUnionsNotSupported"); internal static string Polymorphism_BaseConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_BaseConverterDoesNotSupportMetadata"); internal static string Polymorphism_DerivedConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_DerivedConverterDoesNotSupportMetadata"); internal static string Polymorphism_TypeDoesNotSupportPolymorphism => GetResourceString("Polymorphism_TypeDoesNotSupportPolymorphism"); internal static string Polymorphism_DerivedTypeIsNotSupported => GetResourceString("Polymorphism_DerivedTypeIsNotSupported"); internal static string Polymorphism_DerivedTypeIsAlreadySpecified => GetResourceString("Polymorphism_DerivedTypeIsAlreadySpecified"); internal static string Polymorphism_TypeDicriminatorIdIsAlreadySpecified => GetResourceString("Polymorphism_TypeDicriminatorIdIsAlreadySpecified"); internal static string Polymorphism_InvalidCustomTypeDiscriminatorPropertyName => GetResourceString("Polymorphism_InvalidCustomTypeDiscriminatorPropertyName"); internal static string Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes => GetResourceString("Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes"); internal static string Polymorphism_UnrecognizedTypeDiscriminator => GetResourceString("Polymorphism_UnrecognizedTypeDiscriminator"); internal static string Polymorphism_RuntimeTypeNotSupported => GetResourceString("Polymorphism_RuntimeTypeNotSupported"); internal static string Polymorphism_RuntimeTypeDiamondAmbiguity => GetResourceString("Polymorphism_RuntimeTypeDiamondAmbiguity"); internal static string InvalidJsonTypeInfoOperationForKind => GetResourceString("InvalidJsonTypeInfoOperationForKind"); internal static string OnDeserializingCallbacksNotSupported => GetResourceString("OnDeserializingCallbacksNotSupported"); internal static string CreateObjectConverterNotCompatible => GetResourceString("CreateObjectConverterNotCompatible"); internal static string JsonPropertyInfoBoundToDifferentParent => GetResourceString("JsonPropertyInfoBoundToDifferentParent"); internal static string JsonSerializerOptionsNoTypeInfoResolverSpecified => GetResourceString("JsonSerializerOptionsNoTypeInfoResolverSpecified"); internal static string JsonSerializerIsReflectionDisabled => GetResourceString("JsonSerializerIsReflectionDisabled"); internal static string JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo => GetResourceString("JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo"); internal static string JsonPropertyRequiredAndNotDeserializable => GetResourceString("JsonPropertyRequiredAndNotDeserializable"); internal static string JsonPropertyRequiredAndExtensionData => GetResourceString("JsonPropertyRequiredAndExtensionData"); internal static string JsonRequiredPropertiesMissing => GetResourceString("JsonRequiredPropertiesMissing"); internal static string ObjectCreationHandlingPopulateNotSupportedByConverter => GetResourceString("ObjectCreationHandlingPopulateNotSupportedByConverter"); internal static string ObjectCreationHandlingPropertyMustHaveAGetter => GetResourceString("ObjectCreationHandlingPropertyMustHaveAGetter"); internal static string ObjectCreationHandlingPropertyValueTypeMustHaveASetter => GetResourceString("ObjectCreationHandlingPropertyValueTypeMustHaveASetter"); internal static string ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization => GetResourceString("ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization"); internal static string ObjectCreationHandlingPropertyCannotAllowReadOnlyMember => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReadOnlyMember"); internal static string ObjectCreationHandlingPropertyCannotAllowReferenceHandling => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReferenceHandling"); internal static string ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors => GetResourceString("ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors"); internal static string FormatInt128 => GetResourceString("FormatInt128"); internal static string FormatUInt128 => GetResourceString("FormatUInt128"); internal static string FormatHalf => GetResourceString("FormatHalf"); internal static string InvalidIndentCharacter => GetResourceString("InvalidIndentCharacter"); internal static string InvalidIndentSize => GetResourceString("InvalidIndentSize"); internal static string PipeWriterCanceled => GetResourceString("PipeWriterCanceled"); internal static string PipeWriter_DoesNotImplementUnflushedBytes => GetResourceString("PipeWriter_DoesNotImplementUnflushedBytes"); internal static string InvalidNewLine => GetResourceString("InvalidNewLine"); internal static string PropertyGetterDisallowNull => GetResourceString("PropertyGetterDisallowNull"); internal static string PropertySetterDisallowNull => GetResourceString("PropertySetterDisallowNull"); internal static string ConstructorParameterDisallowNull => GetResourceString("ConstructorParameterDisallowNull"); internal static string JsonSchemaExporter_ReferenceHandlerPreserve_NotSupported => GetResourceString("JsonSchemaExporter_ReferenceHandlerPreserve_NotSupported"); internal static string JsonSchemaExporter_DepthTooLarge => GetResourceString("JsonSchemaExporter_DepthTooLarge"); internal static string Arg_WrongType => GetResourceString("Arg_WrongType"); internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall"); internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported"); internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound"); internal static string Argument_IncompatibleArrayType => GetResourceString("Argument_IncompatibleArrayType"); internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey"); internal static string Argument_AddingDuplicate => GetResourceString("Argument_AddingDuplicate"); internal static string InvalidOperation_ConcurrentOperationsNotSupported => GetResourceString("InvalidOperation_ConcurrentOperationsNotSupported"); internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion"); internal static string ArgumentOutOfRange_Generic_MustBeNonNegative => GetResourceString("ArgumentOutOfRange_Generic_MustBeNonNegative"); internal static string ArgumentOutOfRange_Generic_MustBeGreaterOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeGreaterOrEqual"); internal static string ArgumentOutOfRange_Generic_MustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeLessOrEqual"); internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow"); private static bool GetUsingResourceKeysSwitchValue() { if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled)) { return false; } return isEnabled; } internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class ObsoleteAttribute : Attribute { public string Message { get; } public bool IsError { get; } public string DiagnosticId { get; set; } public string UrlFormat { get; set; } public ObsoleteAttribute() { } public ObsoleteAttribute(string message) { Message = message; } public ObsoleteAttribute(string message, bool error) { Message = message; IsError = error; } } } namespace System.Reflection { internal sealed class NullabilityInfo { public Type Type { get; } public NullabilityState ReadState { get; internal set; } public NullabilityState WriteState { get; internal set; } public NullabilityInfo ElementType { get; } public NullabilityInfo[] GenericTypeArguments { get; } internal NullabilityInfo(Type type, NullabilityState readState, NullabilityState writeState, NullabilityInfo elementType, NullabilityInfo[] typeArguments) { Type = type; ReadState = readState; WriteState = writeState; ElementType = elementType; GenericTypeArguments = typeArguments; } } internal enum NullabilityState { Unknown, NotNull, Nullable } internal sealed class NullabilityInfoContext { [Flags] private enum NotAnnotatedStatus { None = 0, Private = 1, Internal = 2 } private readonly struct NullableAttributeStateParser { private static readonly object UnknownByte = (byte)0; private readonly object _nullableAttributeArgument; public static NullableAttributeStateParser Unknown => new NullableAttributeStateParser(UnknownByte); public NullableAttributeStateParser(object nullableAttributeArgument) { _nullableAttributeArgument = nullableAttributeArgument; } public bool ParseNullableState(int index, ref NullabilityState state) { object nullableAttributeArgument = _nullableAttributeArgument; if (!(nullableAttributeArgument is byte b)) { if (nullableAttributeArgument is ReadOnlyCollection<CustomAttributeTypedArgument> readOnlyCollection) { ReadOnlyCollection<CustomAttributeTypedArgument> readOnlyCollection2 = readOnlyCollection; if (index < readOnlyCollection2.Count && readOnlyCollection2[index].Value is byte b2) { state = TranslateByte(b2); return true; } } return false; } byte b3 = b; state = TranslateByte(b3); return true; } } private const string CompilerServicesNameSpace = "System.Runtime.CompilerServices"; private readonly Dictionary<Module, NotAnnotatedStatus> _publicOnlyModules = new Dictionary<Module, NotAnnotatedStatus>(); private readonly Dictionary<MemberInfo, NullabilityState> _context = new Dictionary<MemberInfo, NullabilityState>(); private NullabilityState? GetNullableContext(MemberInfo memberInfo) { while (memberInfo != null) { if (_context.TryGetValue(memberInfo, out var value)) { return value; } foreach (CustomAttributeData customAttributesDatum in memberInfo.GetCustomAttributesData()) { if (customAttributesDatum.AttributeType.Name == "NullableContextAttribute" && customAttributesDatum.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttributesDatum.ConstructorArguments.Count == 1) { value = TranslateByte(customAttributesDatum.ConstructorArguments[0].Value); _context.Add(memberInfo, value); return value; } } memberInfo = memberInfo.DeclaringType; } return null; } public NullabilityInfo Create(ParameterInfo parameterInfo) { NetstandardHelpers.ThrowIfNull(parameterInfo, "parameterInfo"); IList<CustomAttributeData> customAttributesData = parameterInfo.GetCustomAttributesData(); NullableAttributeStateParser parser = ((parameterInfo.Member is MethodBase method && IsPrivateOrInternalMethodAndAnnotationDisabled(method)) ? NullableAttributeStateParser.Unknown : CreateParser(customAttributesData)); NullabilityInfo nullabilityInfo = GetNullabilityInfo(parameterInfo.Member, parameterInfo.ParameterType, parser); if (nullabilityInfo.ReadState != 0) { CheckParameterMetadataType(parameterInfo, nullabilityInfo); } CheckNullabilityAttributes(nullabilityInfo, customAttributesData); return nullabilityInfo; } private void CheckParameterMetadataType(ParameterInfo parameter, NullabilityInfo nullability) { MemberInfo member = parameter.Member; MemberInfo metaMember; ParameterInfo parameterInfo; if (!(member is ConstructorInfo member2)) { if (!(member is MethodInfo method)) { return; } MethodInfo methodMetadataDefinition = GetMethodMetadataDefinition(method); metaMember = methodMetadataDefinition; parameterInfo = (string.IsNullOrEmpty(parameter.Name) ? methodMetadataDefinition.ReturnParameter : GetMetaParameter(methodMetadataDefinition, parameter)); } else { parameterInfo = GetMetaParameter((MethodBase)(metaMember = (ConstructorInfo)GetMemberMetadataDefinition(member2)), parameter); } if (parameterInfo != null) { CheckGenericParameters(nullability, metaMember, parameterInfo.ParameterType, parameter.Member.ReflectedType); } } private static ParameterInfo GetMetaParameter(MethodBase metaMethod, ParameterInfo parameter) { ReadOnlySpan<ParameterInfo> parametersAsSpan = metaMethod.GetParametersAsSpan(); for (int i = 0; i < parametersAsSpan.Length; i++) { if (parameter.Position == i && parameter.Name == parametersAsSpan[i].Name) { return parametersAsSpan[i]; } } return null; } private static MethodInfo GetMethodMetadataDefinition(MethodInfo method) { if (method.IsGenericMethod && !method.IsGenericMethodDefinition) { method = method.GetGenericMethodDefinition(); } return (MethodInfo)GetMemberMetadataDefinition(method); } private static void CheckNullabilityAttributes(NullabilityInfo nullability, IList<CustomAttributeData> attributes) { NullabilityState nullabilityState = NullabilityState.Unknown; NullabilityState nullabilityState2 = NullabilityState.Unknown; foreach (CustomAttributeData attribute in attributes) { if (attribute.AttributeType.Namespace == "System.Diagnostics.CodeAnalysis") { if (attribute.AttributeType.Name == "NotNullAttribute") { nullabilityState = NullabilityState.NotNull; } else if ((attribute.AttributeType.Name == "MaybeNullAttribute" || attribute.AttributeType.Name == "MaybeNullWhenAttribute") && nullabilityState == NullabilityState.Unknown && !IsValueTypeOrValueTypeByRef(nullability.Type)) { nullabilityState = NullabilityState.Nullable; } else if (attribute.AttributeType.Name == "DisallowNullAttribute") { nullabilityState2 = NullabilityState.NotNull; } else if (attribute.AttributeType.Name == "AllowNullAttribute" && nullabilityState2 == NullabilityState.Unknown && !IsValueTypeOrValueTypeByRef(nullability.Type)) { nullabilityState2 = NullabilityState.Nullable; } } } if (nullabilityState != 0) { nullability.ReadState = nullabilityState; } if (nullabilityState2 != 0) { nullability.WriteState = nullabilityState2; } } public NullabilityInfo Create(PropertyInfo propertyInfo) { NetstandardHelpers.ThrowIfNull(propertyInfo, "propertyInfo"); MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true); MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true); NullableAttributeStateParser parser = (((getMethod == null || IsPrivateOrInternalMethodAndAnnotationDisabled(getMethod)) && (setMethod == null || IsPrivateOrInternalMethodAndAnnotationDisabled(setMethod))) ? NullableAttributeStateParser.Unknown : CreateParser(propertyInfo.GetCustomAttributesData())); NullabilityInfo nullabilityInfo = GetNullabilityInfo(propertyInfo, propertyInfo.PropertyType, parser); if (getMethod != null) { CheckNullabilityAttributes(nullabilityInfo, getMethod.ReturnParameter.GetCustomAttributesData()); } else { nullabilityInfo.ReadState = NullabilityState.Unknown; } if (setMethod != null) { ReadOnlySpan<ParameterInfo> parametersAsSpan = setMethod.GetParametersAsSpan(); ParameterInfo parameterInfo = parametersAsSpan[parametersAsSpan.Length - 1]; CheckNullabilityAttributes(nullabilityInfo, parameterInfo.GetCustomAttributesData()); } else { nullabilityInfo.WriteState = NullabilityState.Unknown; } return nullabilityInfo; } private bool IsPrivateOrInternalMethodAndAnnotationDisabled(MethodBase method) { if ((method.IsPrivate || method.IsFamilyAndAssembly || method.IsAssembly) && IsPublicOnly(method.IsPrivate, method.IsFamilyAndAssembly, method.IsAssembly, method.Module)) { return true; } return false; } public NullabilityInfo Create(EventInfo eventInfo) { NetstandardHelpers.ThrowIfNull(eventInfo, "eventInfo"); return GetNullabilityInfo(eventInfo, eventInfo.EventHandlerType, CreateParser(eventInfo.GetCustomAttributesData())); } public NullabilityInfo Create(FieldInfo fieldInfo) { NetstandardHelpers.ThrowIfNull(fieldInfo, "fieldInfo"); IList<CustomAttributeData> customAttributesData = fieldInfo.GetCustomAttributesData(); NullableAttributeStateParser parser = (IsPrivateOrInternalFieldAndAnnotationDisabled(fieldInfo) ? NullableAttributeStateParser.Unknown : CreateParser(customAttributesData)); NullabilityInfo nullabilityInfo = GetNullabilityInfo(fieldInfo, fieldInfo.FieldType, parser); CheckNullabilityAttributes(nullabilityInfo, customAttributesData); return nullabilityInfo; } private bool IsPrivateOrInternalFieldAndAnnotationDisabled(FieldInfo fieldInfo) { if ((fieldInfo.IsPrivate || fieldInfo.IsFamilyAndAssembly || fieldInfo.IsAssembly) && IsPublicOnly(fieldInfo.IsPrivate, fieldInfo.IsFamilyAndAssembly, fieldInfo.IsAssembly, fieldInfo.Module)) { return true; } return false; } private bool IsPublicOnly(bool isPrivate, bool isFamilyAndAssembly, bool isAssembly, Module module) { if (!_publicOnlyModules.TryGetValue(module, out var value)) { value = PopulateAnnotationInfo(module.GetCustomAttributesData()); _publicOnlyModules.Add(module, value); } if (value == NotAnnotatedStatus.None) { return false; } if (((isPrivate || isFamilyAndAssembly) && value.HasFlag(NotAnnotatedStatus.Private)) || (isAssembly && value.HasFlag(NotAnnotatedStatus.Internal))) { return true; } return false; } private static NotAnnotatedStatus PopulateAnnotationInfo(IList<CustomAttributeData> customAttributes) { bool flag = default(bool); foreach (CustomAttributeData customAttribute in customAttributes) { if (customAttribute.AttributeType.Name == "NullablePublicOnlyAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttribute.ConstructorArguments.Count == 1) { object value = customAttribute.ConstructorArguments[0].Value; int num; if (value is bool) { flag = (bool)value; num = 1; } else { num = 0; } if (((uint)num & (flag ? 1u : 0u)) != 0) { return NotAnnotatedStatus.Private | NotAnnotatedStatus.Internal; } return NotAnnotatedStatus.Private; } } return NotAnnotatedStatus.None; } private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser) { int index = 0; NullabilityInfo nullabilityInfo = GetNullabilityInfo(memberInfo, type, parser, ref index); if (nullabilityInfo.ReadState != 0) { TryLoadGenericMetaTypeNullability(memberInfo, nullabilityInfo); } return nullabilityInfo; } private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser, ref int index) { NullabilityState state = NullabilityState.Unknown; NullabilityInfo elementType = null; NullabilityInfo[] array = Array.Empty<NullabilityInfo>(); Type type2 = type; if (type2.IsByRef || type2.IsPointer) { type2 = type2.GetElementType(); } if (type2.IsValueType) { Type underlyingType = Nullable.GetUnderlyingType(type2); if ((object)underlyingType != null) { type2 = underlyingType; state = NullabilityState.Nullable; } else { state = NullabilityState.NotNull; } if (type2.IsGenericType) { index++; } } else { if (!parser.ParseNullableState(index++, ref state)) { NullabilityState? nullableContext = GetNullableContext(memberInfo); if (nullableContext.HasValue) { NullabilityState valueOrDefault = nullableContext.GetValueOrDefault(); state = valueOrDefault; } } if (type2.IsArray) { elementType = GetNullabilityInfo(memberInfo, type2.GetElementType(), parser, ref index); } } if (type2.IsGenericType) { Type[] genericArguments = type2.GetGenericArguments(); array = new NullabilityInfo[genericArguments.Length]; for (int i = 0; i < genericArguments.Length; i++) { array[i] = GetNullabilityInfo(memberInfo, genericArguments[i], parser, ref index); } } return new NullabilityInfo(type, state, state, elementType, array); } private static NullableAttributeStateParser CreateParser(IList<CustomAttributeData> customAttributes) { foreach (CustomAttributeData customAttribute in customAttributes) { if (customAttribute.AttributeType.Name == "NullableAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttribute.ConstructorArguments.Count == 1) { return new NullableAttributeStateParser(customAttribute.ConstructorArguments[0].Value); } } return new NullableAttributeStateParser(null); } private void TryLoadGenericMetaTypeNullability(MemberInfo memberInfo, NullabilityInfo nullability) { MemberInfo memberMetadataDefinition = GetMemberMetadataDefinition(memberInfo); Type type = null; if (memberMetadataDefinition is FieldInfo fieldInfo) { type = fieldInfo.FieldType; } else if (memberMetadataDefinition is PropertyInfo property) { type = GetPropertyMetaType(property); } if (type != null) { CheckGenericParameters(nullability, memberMetadataDefinition, type, memberInfo.ReflectedType); } } private static MemberInfo GetMemberMetadataDefinition(MemberInfo member) { Type declaringType = member.DeclaringType; if (declaringType != null && declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition) { return NetstandardHelpers.GetMemberWithSameMetadataDefinitionAs(declaringType.GetGenericTypeDefinition(), member); } return member; } private static Type GetPropertyMetaType(PropertyInfo property) { MethodInfo getMethod = property.GetGetMethod(nonPublic: true); if ((object)getMethod != null) { return getMethod.ReturnType; } return property.GetSetMethod(nonPublic: true).GetParametersAsSpan()[0].ParameterType; } private void CheckGenericParameters(NullabilityInfo nullability, MemberInfo metaMember, Type metaType, Type reflectedType) { if (metaType.IsGenericParameter) { if (nullability.ReadState == NullabilityState.NotNull) { TryUpdateGenericParameterNullability(nullability, metaType, reflectedType); } } else { if (!metaType.ContainsGenericParameters) { return; } if (nullability.GenericTypeArguments.Length != 0) { Type[] genericArguments = metaType.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { CheckGenericParameters(nullability.GenericTypeArguments[i], metaMember, genericArguments[i], reflectedType); } return; } NullabilityInfo elementType = nullability.ElementType; if (elementType != null && metaType.IsArray) { CheckGenericParameters(elementType, metaMember, metaType.GetElementType(), reflectedType); } else if (metaType.IsByRef) { CheckGenericParameters(nullability, metaMember, metaType.GetElementType(), reflectedType); } } } private bool TryUpdateGenericParameterNullability(NullabilityInfo nullability, Type genericParameter, Type reflectedType) { if ((object)reflectedType != null && !genericParameter.IsGenericMethodParameter() && TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, reflectedType, reflectedType)) { return true; } if (IsValueTypeOrValueTypeByRef(nullability.Type)) { return true; } NullabilityState state = NullabilityState.Unknown; if (CreateParser(genericParameter.GetCustomAttributesData()).ParseNullableState(0, ref state)) { nullability.ReadState = state; nullability.WriteState = state; return true; } NullabilityState? nullableContext = GetNullableContext(genericParameter); if (nullableContext.HasValue) { NullabilityState writeState = (nullability.ReadState = nullableContext.GetValueOrDefault()); nullability.WriteState = writeState; return true; } return false; } private bool TryUpdateGenericTypeParameterNullabilityFromReflectedType(NullabilityInfo nullability, Type genericParameter, Type context, Type reflectedType) { Type type2 = ((context.IsGenericType && !context.IsGenericTypeDefinition) ? context.GetGenericTypeDefinition() : context); if (genericParameter.DeclaringType == type2) { return false; } Type baseType = type2.BaseType; if ((object)baseType == null) { return false; } if (!baseType.IsGenericType || (baseType.IsGenericTypeDefinition ? baseType : baseType.GetGenericTypeDefinition()) != genericParameter.DeclaringType) { return TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, baseType, reflectedType); } Type[] genericArguments = baseType.GetGenericArguments(); Type type3 = genericArguments[genericParameter.GenericParameterPosition]; if (type3.IsGenericParameter) { return TryUpdateGenericParameterNullability(nullability, type3, reflectedType); } NullableAttributeStateParser parser = CreateParser(type2.GetCustomAttributesData()); int index = 1; for (int i = 0; i < genericParameter.GenericParameterPosition; i++) { index += CountNullabilityStates(genericArguments[i]); } return TryPopulateNullabilityInfo(nullability, parser, ref index); static int CountNullabilityStates(Type type) { Type type4 = Nullable.GetUnderlyingType(type) ?? type; if (type4.IsGenericType) { int num = 1; Type[] genericArguments2 = type4.GetGenericArguments(); foreach (Type type5 in genericArguments2) { num += CountNullabilityStates(type5); } return num; } if (type4.HasElementType) { return (type4.IsArray ? 1 : 0) + CountNullabilityStates(type4.GetElementType()); } return (!type.IsValueType) ? 1 : 0; } } private static bool TryPopulateNullabilityInfo(NullabilityInfo nullability, NullableAttributeStateParser parser, ref int index) { bool flag = IsValueTypeOrValueTypeByRef(nullability.Type); if (!flag) { NullabilityState state = NullabilityState.Unknown; if (!parser.ParseNullableState(index, ref state)) { return false; } nullability.ReadState = state; nullability.WriteState = state; } if (!flag || (Nullable.GetUnderlyingType(nullability.Type) ?? nullability.Type).IsGenericType) { index++; } if (nullability.GenericTypeArguments.Length != 0) { NullabilityInfo[] genericTypeArguments = nullability.GenericTypeArguments; for (int i = 0; i < genericTypeArguments.Length; i++) { TryPopulateNullabilityInfo(genericTypeArguments[i], parser, ref index); } } else { NullabilityInfo elementType = nullability.ElementType; if (elementType != null) { TryPopulateNullabilityInfo(elementType, parser, ref index); } } return true; } private static NullabilityState TranslateByte(object value) { if (!(value is byte b)) { return NullabilityState.Unknown; } return TranslateByte(b); } private static NullabilityState TranslateByte(byte b) { return b switch { 1 => NullabilityState.NotNull, 2 => NullabilityState.Nullable, _ => NullabilityState.Unknown, }; } private static bool IsValueTypeOrValueTypeByRef(Type type) { if (!type.IsValueType) { if (type.IsByRef || type.IsPointer) { return type.GetElementType().IsValueType; } return false; } return true; } } internal static class NetstandardHelpers { public static void ThrowIfNull(object argument, string paramName) { if (argument == null) { Throw(paramName); } static void Throw(string paramName) { throw new ArgumentNullException(paramName); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This is finding the MemberInfo with the same MetadataToken as specified MemberInfo. If the specified MemberInfo exists and wasn't trimmed, then the current Type's MemberInfo couldn't have been trimmed.")] public static MemberInfo GetMemberWithSameMetadataDefinitionAs(this Type type, MemberInfo member) { ThrowIfNull(member, "member"); MemberInfo[] members = type.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MemberInfo memberInfo in members) { if (HasSameMetadataDefinitionAs(memberInfo, member)) { return memberInfo; } } throw new MissingMemberException(type.FullName, member.Name); } private static bool HasSameMetadataDefinitionAs(this MemberInfo info, MemberInfo other) { if (info.MetadataToken != other.MetadataToken) { return false; } if (!info.Module.Equals(other.Module)) { return false; } return true; } public static bool IsGenericMethodParameter(this Type type) { if (type.IsGenericParameter) { return (object)type.DeclaringMethod != null; } return false; } public static ReadOnlySpan<ParameterInfo> GetParametersAsSpan(this MethodBase metaMethod) { return metaMethod.GetParameters(); } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class DynamicDependencyAttribute : Attribute { public string MemberSignature { get; } public DynamicallyAccessedMemberTypes MemberTypes { get; } public Type Type { get; } public string TypeName { get; } public string AssemblyName { get; } public string Condition { get; set; } public DynamicDependencyAttribute(string memberSignature) { MemberSignature = memberSignature; } public DynamicDependencyAttribute(string memberSignature, Type type) { MemberSignature = memberSignature; Type = type; } public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) { MemberSignature = memberSignature; TypeName = typeName; AssemblyName = assemblyName; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) { MemberTypes = memberTypes; Type = type; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) { MemberTypes = memberTypes; TypeName = typeName; AssemblyName = assemblyName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string Scope { get; set; } public string Target { get; set; } public string MessageId { get; set; } public string Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = Array.Empty<object>(); } public StringSyntaxAttribute(string syntax, params object[] arguments) { Syntax = syntax; Arguments = arguments; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Collections { internal static class HashHelpers { public const uint HashCollisionThreshold = 100u; public const int MaxPrimeArrayLength = 2147483587; public const int HashPrime = 101; internal static ReadOnlySpan<int> Primes { get { object obj = global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6; if (obj == null) { obj = new int[72] { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6 = (int[])obj; } return new ReadOnlySpan<int>((int[]?)obj); } } public static bool IsPrime(int candidate) { if (((uint)candidate & (true ? 1u : 0u)) != 0) { int num = (int)Math.Sqrt(candidate); for (int i = 3; i <= num; i += 2) { if (candidate % i == 0) { return false; } } return true; } return candidate == 2; } public static int GetPrime(int min) { if (min < 0) { throw new ArgumentException(System.SR.Arg_HTCapacityOverflow); } ReadOnlySpan<int> primes = Primes; for (int i = 0; i < primes.Length; i++) { int num = primes[i]; if (num >= min) { return num; } } for (int j = min | 1; j < int.MaxValue; j += 2) { if (IsPrime(j) && (j - 1) % 101 != 0) { return j; } } return min; } public static int ExpandPrime(int oldSize) { int num = 2 * oldSize; if ((uint)num > 2147483587u && 2147483587 > oldSize) { return 2147483587; } return GetPrime(num); } public static ulong GetFastModMultiplier(uint divisor) { return ulong.MaxValue / (ulong)divisor + 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint FastMod(uint value, uint divisor, ulong multiplier) { return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32); } } internal static class ThrowHelper { [DoesNotReturn] internal static void ThrowKeyNotFound<TKey>(TKey key) { throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key)); } [DoesNotReturn] internal static void ThrowDuplicateKey<TKey>(TKey key) { throw new ArgumentException(System.SR.Format(System.SR.Argument_AddingDuplicate, key), "key"); } [DoesNotReturn] internal static void ThrowConcurrentOperation() { throw new InvalidOperationException(System.SR.InvalidOperation_ConcurrentOperationsNotSupported); } [DoesNotReturn] internal static void ThrowIndexArgumentOutOfRange() { throw new ArgumentOutOfRangeException("index"); } [DoesNotReturn] internal static void ThrowVersionCheckFailed() { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { ThrowNull(paramName); } } public static void ThrowIfNegative(int value, [CallerArgumentExpression("value")] string paramName = null) { if (value < 0) { ThrowNegative(value, paramName); } } public static void ThrowIfGreaterThan<T>(T value, T other, [CallerArgumentExpression("value")] string paramName = null) where T : IComparable<T> { if (value.CompareTo(other) > 0) { ThrowGreater(value, other, paramName); } } public static void ThrowIfLessThan<T>(T value, T other, [CallerArgumentExpression("value")] string paramName = null) where T : IComparable<T> { if (value.CompareTo(other) < 0) { ThrowLess(value, other, paramName); } } [DoesNotReturn] private static void ThrowNull(string paramName) { throw new ArgumentNullException(paramName); } [DoesNotReturn] private static void ThrowNegative(int value, string paramName) { throw new ArgumentOutOfRangeException(paramName, value, System.SR.Format(System.SR.ArgumentOutOfRange_Generic_MustBeNonNegative, paramName, value)); } [DoesNotReturn] private static void ThrowGreater<T>(T value, T other, string paramName) { throw new ArgumentOutOfRangeException(paramName, value, System.SR.Format(System.SR.ArgumentOutOfRange_Generic_MustBeLessOrEqual, paramName, value, other)); } [DoesNotReturn] private static void ThrowLess<T>(T value, T other, string paramName) { throw new ArgumentOutOfRangeException(paramName, value, System.SR.Format(System.SR.ArgumentOutOfRange_Generic_MustBeGreaterOrEqual, paramName, value, other)); } } } namespace System.Collections.ObjectModel { internal static class CollectionHelpers { internal static void ValidateCopyToArguments(int sourceCount, Array array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(System.SR.Arg_RankMultiDimNotSupported, "array"); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(System.SR.Arg_NonZeroLowerBound, "array"); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException("index"); } if (array.Length - index < sourceCount) { throw new ArgumentException(System.SR.Arg_ArrayPlusOffTooSmall); } } internal static void CopyTo<T>(ICollection<T> collection, Array array, int index) { ValidateCopyToArguments(collection.Count, array, index); if (collection is ICollection collection2) { collection2.CopyTo(array, index); return; } if (array is T[] array2) { collection.CopyTo(array2, index); return; } if (!(array is object[] array3)) { throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array"); } try { foreach (T item in collection) { array3[index++] = item; } } catch (ArrayTypeMismatchException) { throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array"); } } } } namespace System.Collections.Generic { internal sealed class ReferenceEqualityComparer : IEqualityComparer<object>, IEqualityComparer { public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer(); private ReferenceEqualityComparer() { } public new bool Equals(object x, object y) { return x == y; } public int GetHashCode(object obj) { return RuntimeHelpers.GetHashCode(obj); } } [DebuggerDisplay("{Value}", Name = "[{Key}]")] internal readonly struct DebugViewDictionaryItem<TKey, TValue> { [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public TKey Key { get; } [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public TValue Value { get; } public DebugViewDictionaryItem(TKey key, TValue value) { Key = key; Value = value; } public DebugViewDictionaryItem(KeyValuePair<TKey, TValue> keyValue) { Key = keyValue.Key; Value = keyValue.Value; } } internal sealed class ICollectionDebugView<T> { private readonly ICollection<T> _collection; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { T[] array = new T[_collection.Count]; _collection.CopyTo(array, 0); return array; } } public ICollectionDebugView(ICollection<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } _collection = collection; } } internal sealed class IDictionaryDebugView<TKey, TValue> { private readonly IDictionary<TKey, TValue> _dict; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public DebugViewDictionaryItem<TKey, TValue>[] Items { get { KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[_dict.Count]; _dict.CopyTo(array, 0); DebugViewDictionaryItem<TKey, TValue>[] array2 = new DebugViewDictionaryItem<TKey, TValue>[array.Length]; for (int i = 0; i < array2.Length; i++) { array2[i] = new DebugViewDictionaryItem<TKey, TValue>(array[i]); } return array2; } } public IDictionaryDebugView(IDictionary<TKey, TValue> dictionary) { _dict = dictionary ?? throw new ArgumentNullException("dictionary"); } } internal sealed class DictionaryKeyCollectionDebugView<TKey, TValue> { private readonly ICollection<TKey> _collection; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public TKey[] Items { get { TKey[] array = new TKey[_collection.Count]; _collection.CopyTo(array, 0); return array; } } public DictionaryKeyCollectionDebugView(ICollection<TKey> collection) { _collection = collection ?? throw new ArgumentNullException("collection"); } } internal sealed class DictionaryValueCollectionDebugView<TKey, TValue> { private readonly ICollection<TValue> _collection; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public TValue[] Items { get { TValue[] array = new TValue[_collection.Count]; _collection.CopyTo(array, 0); return array; } } public DictionaryValueCollectionDebugView(ICollection<TValue> collection) { _collection = collection ?? throw new ArgumentNullException("collection"); } } internal static class EnumerableHelpers { internal static void Reset<T>(ref T enumerator) where T : IEnumerator { enumerator.Reset(); } internal static IEnumerator<T> GetEmptyEnumerator<T>() { return ((IEnumerable<T>)Array.Empty<T>()).GetEnumerator(); } internal static T[] ToArray<T>(IEnumerable<T> source, out int length) { if (source is ICollection<T> collection) { int count = collection.Count; if (count != 0) { T[] array = new T[count]; collection.CopyTo(array, 0); length = count; return array; } } else { using IEnumerator<T> enumerator = source.GetEnumerator(); if (enumerator.MoveNext()) { T[] array2 = new T[4] { enumerator.Current, default(T), default(T), default(T) }; int num = 1; while (enumerator.MoveNext()) { if (num == array2.Length) { int num2 = num << 1; if ((uint)num2 > 2147483591u) { num2 = ((2147483591 <= num) ? (num + 1) : 2147483591); } Array.Resize(ref array2, num2); } array2[num++] = enumerator.Current; } length = num; return array2; } } length = 0; return Array.Empty<T>(); } } [DebuggerTypeProxy(typeof(System.Collections.Generic.IDictionaryDebugView<, >))] [DebuggerDisplay("Count = {Count}")] internal sealed class OrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IList<KeyValuePair<TKey, TValue>>, IReadOnlyList<KeyValuePair<TKey, TValue>>, IList { private struct Entry { public int Next; public uint HashCode; public TKey Key; public TValue Value; } [StructLayout(LayoutKind.Auto)] public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, IEnumerator, IDictionaryEnumerator { private readonly OrderedDictionary<TKey, TValue> _dictionary; private readonly int _version; private readonly bool _useDictionaryEntry; private int _index; public KeyValuePair<TKey, TValue> Current { get; private set; } readonly object IEnumerator.Current { get { if (!_useDictionaryEntry) { return Current; } return new DictionaryEntry(Current.Key, Current.Value); } } readonly DictionaryEntry IDictionaryEnumerator.Entry => new DictionaryEntry(Current.Key, Current.Value); readonly object IDictionaryEnumerator.Key => Current.Key; readonly object IDictionaryEnumerator.Value => Current.Value; internal Enumerator(OrderedDictionary<TKey, TValue> dictionary, bool useDictionaryEntry) { _index = 0; Current = default(KeyValuePair<TKey, TValue>); _dictionary = dictionary; _version = _dictionary._version; _useDictionaryEntry = useDictionaryEntry; } public bool MoveNext() { OrderedDictionary<TKey, TValue> dictionary = _dictionary; if (_version != dictionary._version) { ThrowHelper.ThrowVersionCheckFailed(); } if (_index < dictionary._count) { ref Entry reference = ref dictionary._entries[_index]; Current = new KeyValuePair<TKey, TValue>(reference.Key, reference.Value); _index++; return true; } Current = default(KeyValuePair<TKey, TValue>); return false; } void IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowVersionCheckFailed(); } _index = 0; Current = default(KeyValuePair<TKey, TValue>); } readonly void IDisposable.Dispose() { } } [DebuggerTypeProxy(typeof(System.Collections.Generic.ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection : IList<TKey>, ICollection<TKey>, IEnumerable<TKey>, IEnumerable, IReadOnlyList<TKey>, IReadOnlyCollection<TKey>, IList, ICollection { public struct Enumerator : IEnumerator<TKey>, IDisposable, IEnumerator { private OrderedDictionary<TKey, TValue>.Enumerator _enumerator; public TKey Current => _enumerator.Current.Key; object IEnumerator.Current => Current; internal Enumerator(OrderedDictionary<TKey, TValue> dictionary) { _enumerator = dictionary.GetEnumerator(); } public bool MoveNext() { return _enumerator.MoveNext(); } void IEnumerator.Reset() { System.Collections.Generic.EnumerableHelpers.Reset(ref _enumerator); } readonly void IDisposable.Dispose() { } } private readonly OrderedDictionary<TKey, TValue> _dictionary; public int Count => _dictionary.Count; bool ICollection<TKey>.IsReadOnly => true; bool IList.IsReadOnly => true; bool IList.IsFixedSize => false; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; TKey IList<TKey>.this[int index] { get { return _dictionary.GetAt(index).Key; } set { throw new NotSupportedException(); } } object IList.this[int index] { get { return _dictionary.GetAt(index).Key; } set { throw new NotSupportedException(); } } TKey IReadOnlyList<TKey>.this[int index] => _dictionary.GetAt(index).Key; internal KeyCollection(OrderedDictionary<TKey, TValue> dictionary) { _dictionary = dictionary; } public bool Contains(TKey key) { return _dictionary.ContainsKey(key); } bool IList.Contains(object value) { if (value is TKey key) { return Contains(key); } return false; } public void CopyTo(TKey[] array, int arrayIndex) { ThrowHelper.ThrowIfNull(array, "array"); ThrowHelper.ThrowIfNegative(arrayIndex, "arrayIndex"); OrderedDictionary<TKey, TValue> dictionary = _dictionary; int count = dictionary._count; if (array.Length - arrayIndex < count) { throw new ArgumentException(System.SR.Arg_ArrayPlusOffTooSmall, "array"); } Entry[] entries = dictionary._entries; for (int i = 0; i < count; i++) { array[arrayIndex++] = entries[i].Key; } } void ICollection.CopyTo(Array array, int index) { ThrowHelper.ThrowIfNull(array, "array"); if (array.Rank != 1) { throw new ArgumentException(System.SR.Arg_RankMultiDimNotSupported, "array"); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(System.SR.Arg_NonZeroLowerBound, "array"); } ThrowHelper.ThrowIfNegative(index, "index"); if (array.Length - index < _dictionary.Count) { throw new ArgumentException(System.SR.Arg_ArrayPlusOffTooSmall); } if (array is TKey[] array2) { CopyTo(array2, index); return; } try { if (!(array is object[] array3)) { throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array"); } using Enumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { TKey current = enumerator.Current; array3[index++] = current; } } catch (ArrayTypeMismatchException) { throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array"); } } public Enumerator GetEnumerator() { return new Enumerator(_dictionary); } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { if (Count != 0) { return GetEnumerator(); } return System.Collections.Generic.EnumerableHelpers.GetEmptyEnumerator<TKey>(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TKey>)this).GetEnumerator(); } int IList<TKey>.IndexOf(TKey item) { return _dictionary.IndexOf(item); } void ICollection<TKey>.Add(TKey item) { throw new NotSupportedException(); } void ICollection<TKey>.Clear() { throw new NotSupportedExcepti
System.Threading.Tasks.Extensions.dll
Decompiled 2 months 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 System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.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(System.Runtime.CompilerServices.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 { System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.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 System.Runtime.CompilerServices.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(System.Runtime.CompilerServices.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) { System.Runtime.CompilerServices.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) { System.Runtime.CompilerServices.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) { System.Runtime.CompilerServices.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) { System.Runtime.CompilerServices.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) { System.Runtime.CompilerServices.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) { System.Runtime.CompilerServices.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) { System.Runtime.CompilerServices.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) { System.Runtime.CompilerServices.Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation); } } } } namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class StackTraceHiddenAttribute : Attribute { } }
System.ValueTuple.dll
Decompiled 2 months agousing System; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using FxResources.System.ValueTuple; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.ValueTuple")] [assembly: AssemblyDescription("System.ValueTuple")] [assembly: AssemblyDefaultAlias("System.ValueTuple")] [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: AssemblyVersion("4.0.3.0")] [assembly: TypeForwardedTo(typeof(TupleElementNamesAttribute))] [assembly: TypeForwardedTo(typeof(TupleExtensions))] [assembly: TypeForwardedTo(typeof(ValueTuple))] [assembly: TypeForwardedTo(typeof(ValueTuple<>))] [assembly: TypeForwardedTo(typeof(ValueTuple<, >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , , >))] namespace FxResources.System.ValueTuple { 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_ValueTupleIncorrectType => GetResourceString("ArgumentException_ValueTupleIncorrectType", null); internal static string ArgumentException_ValueTupleLastArgumentNotAValueTuple => GetResourceString("ArgumentException_ValueTupleLastArgumentNotAValueTuple", 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); } } }
YoutubeDLSharp.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using YoutubeDLSharp.Converters; using YoutubeDLSharp.Helpers; using YoutubeDLSharp.Metadata; using YoutubeDLSharp.Options; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("Bluegrams")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© 2020-2024 Bluegrams")] [assembly: AssemblyDescription("\r\n\t\tA simple .NET wrapper library for youtube-dl and yt-dlp.\r\n\r\nNote: Package versions >= 1.0 are optimized to work with yt-dlp.\r\nPackage versions 0.x retain support for the original youtube-dl.\r\n\t")] [assembly: AssemblyFileVersion("1.1.1.24210")] [assembly: AssemblyInformationalVersion("1.1.1+fde6d23c93bcc097f8b191c2b4199b2459ea3095")] [assembly: AssemblyProduct("YoutubeDLSharp")] [assembly: AssemblyTitle("YoutubeDLSharp")] [assembly: AssemblyVersion("1.1.1.24210")] namespace YoutubeDLSharp { public enum DownloadState { None, PreProcessing, Downloading, PostProcessing, Error, Success } public class DownloadProgress { public DownloadState State { get; } public float Progress { get; } public string TotalDownloadSize { get; } public string DownloadSpeed { get; } public string ETA { get; } public int VideoIndex { get; } public string Data { get; } public DownloadProgress(DownloadState status, float progress = 0f, string totalDownloadSize = null, string downloadSpeed = null, string eta = null, int index = 1, string data = null) { State = status; Progress = progress; TotalDownloadSize = totalDownloadSize; DownloadSpeed = downloadSpeed; ETA = eta; VideoIndex = index; Data = data; } } public class RunResult<T> { public bool Success { get; } public string[] ErrorOutput { get; } public T Data { get; } public RunResult(bool success, string[] error, T result) { Success = success; ErrorOutput = error; Data = result; } } public static class Utils { internal class FFmpegApi { public class Root { [JsonProperty("version")] public string Version { get; set; } [JsonProperty("permalink")] public string Permalink { get; set; } [JsonProperty("bin")] public Bin Bin { get; set; } } public class Bin { [JsonProperty("windows-64")] public OsBinVersion Windows64 { get; set; } [JsonProperty("linux-64")] public OsBinVersion Linux64 { get; set; } [JsonProperty("osx-64")] public OsBinVersion Osx64 { get; set; } } public class OsBinVersion { [JsonProperty("ffmpeg")] public string Ffmpeg { get; set; } [JsonProperty("ffprobe")] public string Ffprobe { get; set; } } public enum BinaryType { [EnumMember(Value = "ffmpeg")] FFmpeg, [EnumMember(Value = "ffprobe")] FFprobe } } private static readonly HttpClient _client = new HttpClient(); private static readonly Regex rgxTimestamp = new Regex("[0-9]+(?::[0-9]+)+", RegexOptions.Compiled); private static readonly Dictionary<char, string> accentChars = "ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ".Zip(new string[68] { "A", "A", "A", "A", "A", "A", "AE", "C", "E", "E", "E", "E", "I", "I", "I", "I", "D", "N", "O", "O", "O", "O", "O", "O", "O", "OE", "U", "U", "U", "U", "U", "Y", "P", "ss", "a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i", "o", "n", "o", "o", "o", "o", "o", "o", "o", "oe", "u", "u", "u", "u", "u", "y", "p", "y" }, (char c, string s) => new { Key = c, Val = s }).ToDictionary(o => o.Key, o => o.Val); public static string YtDlpBinaryName => GetYtDlpBinaryName(); public static string FfmpegBinaryName => GetFfmpegBinaryName(); public static string FfprobeBinaryName => GetFfprobeBinaryName(); public static string Sanitize(string s, bool restricted = false) { rgxTimestamp.Replace(s, (Match m) => m.Groups[0].Value.Replace(':', '_')); string text = string.Join("", s.Select((char c) => sanitizeChar(c, restricted))); text = text.Replace("__", "_").Trim(new char[1] { '_' }); if (restricted && text.StartsWith("-_")) { text = text.Substring(2); } if (text.StartsWith("-")) { text = "_" + text.Substring(1); } text = text.TrimStart(new char[1] { '.' }); if (string.IsNullOrWhiteSpace(text)) { text = "_"; } return text; } private static string sanitizeChar(char c, bool restricted) { if (restricted && accentChars.ContainsKey(c)) { return accentChars[c]; } if (c != '?' && c >= ' ') { switch (c) { case '\u007f': break; case '"': if (!restricted) { return "'"; } return ""; case ':': if (!restricted) { return " -"; } return "_-"; default: if (Enumerable.Contains("\\/|*<>", c)) { return "_"; } if (restricted && Enumerable.Contains("!&'()[]{}$;`^,# ", c)) { return "_"; } if (restricted && c > '\u007f') { return "_"; } return c.ToString(); } } return ""; } public static string GetFullPath(string fileName) { if (File.Exists(fileName)) { return Path.GetFullPath(fileName); } string[] array = Environment.GetEnvironmentVariable("PATH").Split(new char[1] { Path.PathSeparator }); for (int i = 0; i < array.Length; i++) { string text = Path.Combine(array[i], fileName); if (File.Exists(text)) { return text; } } return null; } public static async Task DownloadBinaries(bool skipExisting = true, string directoryPath = "") { if (skipExisting) { if (!File.Exists(Path.Combine(directoryPath, GetYtDlpBinaryName()))) { await DownloadYtDlp(directoryPath); } if (!File.Exists(Path.Combine(directoryPath, GetFfmpegBinaryName()))) { await DownloadFFmpeg(directoryPath); } if (!File.Exists(Path.Combine(directoryPath, GetFfprobeBinaryName()))) { await DownloadFFprobe(directoryPath); } } else { await DownloadYtDlp(directoryPath); await DownloadFFmpeg(directoryPath); await DownloadFFprobe(directoryPath); } } private static string GetYtDlpDownloadUrl() { return OSHelper.GetOSVersion() switch { OSVersion.Windows => "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe", OSVersion.OSX => "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos", OSVersion.Linux => "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp", _ => throw new Exception("Your OS isn't supported"), }; } private static string GetYtDlpBinaryName() { return Path.GetFileName(GetYtDlpDownloadUrl()); } private static string GetFfmpegBinaryName() { switch (OSHelper.GetOSVersion()) { case OSVersion.Windows: return "ffmpeg.exe"; case OSVersion.OSX: case OSVersion.Linux: return "ffmpeg"; default: throw new Exception("Your OS isn't supported"); } } private static string GetFfprobeBinaryName() { switch (OSHelper.GetOSVersion()) { case OSVersion.Windows: return "ffprobe.exe"; case OSVersion.OSX: case OSVersion.Linux: return "ffprobe"; default: throw new Exception("Your OS isn't supported"); } } public static async Task DownloadYtDlp(string directoryPath = "") { string ytDlpDownloadUrl = GetYtDlpDownloadUrl(); if (string.IsNullOrEmpty(directoryPath)) { directoryPath = Directory.GetCurrentDirectory(); } string downloadLocation = Path.Combine(directoryPath, Path.GetFileName(ytDlpDownloadUrl)); File.WriteAllBytes(downloadLocation, await DownloadFileBytesAsync(ytDlpDownloadUrl)); } public static async Task DownloadFFmpeg(string directoryPath = "") { await FFDownloader(directoryPath); } public static async Task DownloadFFprobe(string directoryPath = "") { await FFDownloader(directoryPath, FFmpegApi.BinaryType.FFprobe); } private static async Task FFDownloader(string directoryPath = "", FFmpegApi.BinaryType binary = FFmpegApi.BinaryType.FFmpeg) { if (string.IsNullOrEmpty(directoryPath)) { directoryPath = Directory.GetCurrentDirectory(); } FFmpegApi.Root root = JsonConvert.DeserializeObject<FFmpegApi.Root>(await (await _client.GetAsync("https://ffbinaries.com/api/v1/version/latest")).Content.ReadAsStringAsync()); FFmpegApi.OsBinVersion osBinVersion = OSHelper.GetOSVersion() switch { OSVersion.Windows => root?.Bin.Windows64, OSVersion.OSX => root?.Bin.Osx64, OSVersion.Linux => root?.Bin.Linux64, _ => throw new NotImplementedException("Your OS isn't supported"), }; using MemoryStream stream = new MemoryStream(await DownloadFileBytesAsync((binary == FFmpegApi.BinaryType.FFmpeg) ? osBinVersion.Ffmpeg : osBinVersion.Ffprobe)); using ZipArchive zipArchive = new ZipArchive(stream, ZipArchiveMode.Read); if (zipArchive.Entries.Count > 0) { zipArchive.Entries[0].ExtractToFile(Path.Combine(directoryPath, zipArchive.Entries[0].FullName), overwrite: true); } } private static async Task<byte[]> DownloadFileBytesAsync(string uri) { if (!Uri.TryCreate(uri, UriKind.Absolute, out Uri _)) { throw new InvalidOperationException("URI is invalid."); } return await _client.GetByteArrayAsync(uri); } public static void EnsureSuccess<T>(this RunResult<T> runResult) { if (!runResult.Success) { throw new Exception("Download failed:\n" + string.Join("\n", runResult.ErrorOutput)); } } } public class YoutubeDL { private static readonly Regex rgxFile = new Regex("^outfile:\\s\\\"?(.*)\\\"?", RegexOptions.Compiled); private static Regex rgxFilePostProc = new Regex("\\[download\\] Destination: [a-zA-Z]:\\\\\\S+\\.\\S{3,}", RegexOptions.Compiled); protected ProcessRunner runner; public string YoutubeDLPath { get; set; } = Utils.YtDlpBinaryName; public string FFmpegPath { get; set; } = Utils.FfmpegBinaryName; public string OutputFolder { get; set; } = Environment.CurrentDirectory; public string OutputFileTemplate { get; set; } = "%(title)s [%(id)s].%(ext)s"; public bool RestrictFilenames { get; set; } public bool OverwriteFiles { get; set; } = true; public bool IgnoreDownloadErrors { get; set; } = true; public string PythonInterpreterPath { get; set; } public string Version => FileVersionInfo.GetVersionInfo(Utils.GetFullPath(YoutubeDLPath)).FileVersion; public YoutubeDL(byte maxNumberOfProcesses = 4) { runner = new ProcessRunner(maxNumberOfProcesses); } public async Task SetMaxNumberOfProcesses(byte count) { await runner.SetTotalCount(count); } public async Task<RunResult<string[]>> RunWithOptions(string[] urls, OptionSet options, CancellationToken ct) { List<string> output = new List<string>(); YoutubeDLProcess youtubeDLProcess = CreateYoutubeDLProcess(); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { output.Add(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, urls, options, ct); return new RunResult<string[]>(num == 0, error, output.ToArray()); } public async Task<RunResult<string>> RunWithOptions(string url, OptionSet options, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, bool showArgs = true) { string outFile = string.Empty; YoutubeDLProcess youtubeDLProcess = CreateYoutubeDLProcess(); if (showArgs) { output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, options) + "\n"); } else { output?.Report("Starting Download: " + url); } youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFilePostProc.Match(e.Data); if (match.Success) { outFile = match.Groups[0].ToString().Replace("[download] Destination:", "").Replace(" ", ""); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outFile)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, options, ct, progress); return new RunResult<string>(num == 0, error, outFile); } public async Task<string> RunUpdate() { string output = string.Empty; YoutubeDLProcess youtubeDLProcess = CreateYoutubeDLProcess(); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { output = e.Data; }; await youtubeDLProcess.RunAsync(null, new OptionSet { Update = true }); return output; } public async Task<RunResult<VideoData>> RunVideoDataFetch(string url, CancellationToken ct = default(CancellationToken), bool flat = true, bool fetchComments = false, OptionSet overrideOptions = null) { OptionSet optionSet = GetDownloadOptions(); optionSet.DumpSingleJson = true; optionSet.FlatPlaylist = flat; optionSet.WriteComments = fetchComments; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } VideoData videoData = null; YoutubeDLProcess process = CreateYoutubeDLProcess(); process.OutputReceived += delegate(object o, DataReceivedEventArgs e) { try { videoData = JsonConvert.DeserializeObject<VideoData>(e.Data); } catch (JsonSerializationException) { process.RedirectToError(e); } }; var (num, error) = await runner.RunThrottled(process, new string[1] { url }, optionSet, ct); return new RunResult<VideoData>(num == 0, error, videoData); } public async Task<RunResult<string>> RunVideoDownload(string url, string format = "bestvideo+bestaudio/best", DownloadMergeFormat mergeFormat = DownloadMergeFormat.Unspecified, VideoRecodeFormat recodeFormat = VideoRecodeFormat.None, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null) { OptionSet optionSet = GetDownloadOptions(); optionSet.Format = format; optionSet.MergeOutputFormat = mergeFormat; optionSet.RecodeVideo = recodeFormat; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } string outputFile = string.Empty; YoutubeDLProcess youtubeDLProcess = CreateYoutubeDLProcess(); output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n"); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFile.Match(e.Data); if (match.Success) { outputFile = match.Groups[1].ToString().Trim(new char[1] { '"' }); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outputFile)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress); return new RunResult<string>(num == 0, error, outputFile); } public async Task<RunResult<string[]>> RunVideoPlaylistDownload(string url, int? start = 1, int? end = null, int[] items = null, string format = "bestvideo+bestaudio/best", VideoRecodeFormat recodeFormat = VideoRecodeFormat.None, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null) { OptionSet optionSet = GetDownloadOptions(); optionSet.NoPlaylist = false; optionSet.PlaylistStart = start; optionSet.PlaylistEnd = end; if (items != null) { optionSet.PlaylistItems = string.Join(",", items); } optionSet.Format = format; optionSet.RecodeVideo = recodeFormat; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } List<string> outputFiles = new List<string>(); YoutubeDLProcess youtubeDLProcess = CreateYoutubeDLProcess(); output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n"); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFile.Match(e.Data); if (match.Success) { string text = match.Groups[1].ToString().Trim(new char[1] { '"' }); outputFiles.Add(text); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, text)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress); return new RunResult<string[]>(num == 0, error, outputFiles.ToArray()); } public async Task<RunResult<string>> RunAudioDownload(string url, AudioConversionFormat format = AudioConversionFormat.Best, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null) { OptionSet optionSet = GetDownloadOptions(); optionSet.Format = "bestaudio/best"; optionSet.ExtractAudio = true; optionSet.AudioFormat = format; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } string outputFile = string.Empty; new List<string>(); YoutubeDLProcess youtubeDLProcess = CreateYoutubeDLProcess(); output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n"); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFile.Match(e.Data); if (match.Success) { outputFile = match.Groups[1].ToString().Trim(new char[1] { '"' }); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outputFile)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress); return new RunResult<string>(num == 0, error, outputFile); } public async Task<RunResult<string[]>> RunAudioPlaylistDownload(string url, int? start = 1, int? end = null, int[] items = null, AudioConversionFormat format = AudioConversionFormat.Best, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null) { List<string> outputFiles = new List<string>(); OptionSet optionSet = GetDownloadOptions(); optionSet.NoPlaylist = false; optionSet.PlaylistStart = start; optionSet.PlaylistEnd = end; if (items != null) { optionSet.PlaylistItems = string.Join(",", items); } optionSet.Format = "bestaudio/best"; optionSet.ExtractAudio = true; optionSet.AudioFormat = format; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } YoutubeDLProcess youtubeDLProcess = CreateYoutubeDLProcess(); output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n"); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFile.Match(e.Data); if (match.Success) { string text = match.Groups[1].ToString().Trim(new char[1] { '"' }); outputFiles.Add(text); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, text)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress); return new RunResult<string[]>(num == 0, error, outputFiles.ToArray()); } protected virtual OptionSet GetDownloadOptions() { return new OptionSet { IgnoreErrors = IgnoreDownloadErrors, IgnoreConfig = true, NoPlaylist = true, Downloader = "m3u8:native", DownloaderArgs = "ffmpeg:-nostats -loglevel 0", Output = Path.Combine(OutputFolder, OutputFileTemplate), RestrictFilenames = RestrictFilenames, ForceOverwrites = OverwriteFiles, NoOverwrites = !OverwriteFiles, NoPart = true, FfmpegLocation = Utils.GetFullPath(FFmpegPath), Exec = "echo outfile: {}" }; } private YoutubeDLProcess CreateYoutubeDLProcess() { return new YoutubeDLProcess(YoutubeDLPath) { PythonPath = PythonInterpreterPath }; } } public class YoutubeDLProcess { private static readonly Regex rgxPlaylist = new Regex("Downloading video (\\d+) of (\\d+)", RegexOptions.Compiled); private static readonly Regex rgxProgress = new Regex("\\[download\\]\\s+(?:(?<percent>[\\d\\.]+)%(?:\\s+of\\s+\\~?\\s*(?<total>[\\d\\.\\w]+))?\\s+at\\s+(?:(?<speed>[\\d\\.\\w]+\\/s)|[\\w\\s]+)\\s+ETA\\s(?<eta>[\\d\\:]+))?", RegexOptions.Compiled); private static readonly Regex rgxPost = new Regex("\\[(\\w+)\\]\\s+", RegexOptions.Compiled); public string PythonPath { get; set; } public string ExecutablePath { get; set; } public bool UseWindowsEncodingWorkaround { get; set; } = true; public event EventHandler<DataReceivedEventArgs> OutputReceived; public event EventHandler<DataReceivedEventArgs> ErrorReceived; public YoutubeDLProcess(string executablePath = "yt-dlp.exe") { ExecutablePath = executablePath; } internal string ConvertToArgs(string[] urls, OptionSet options) { return options.ToString() + " -- " + ((urls != null) ? string.Join(" ", urls.Select((string s) => "\"" + s + "\"")) : string.Empty); } internal void RedirectToError(DataReceivedEventArgs e) { this.ErrorReceived?.Invoke(this, e); } public async Task<int> RunAsync(string[] urls, OptionSet options) { return await RunAsync(urls, options, CancellationToken.None); } public async Task<int> RunAsync(string[] urls, OptionSet options, CancellationToken ct, IProgress<DownloadProgress> progress = null) { TaskCompletionSource<int> tcs = new TaskCompletionSource<int>(); Process process = new Process(); ProcessStartInfo processStartInfo = new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8 }; if (OSHelper.IsWindows && UseWindowsEncodingWorkaround) { processStartInfo.FileName = "cmd.exe"; string text = (string.IsNullOrEmpty(PythonPath) ? ("\"" + ExecutablePath + "\" " + ConvertToArgs(urls, options)) : ("\"" + PythonPath + "\" \"" + ExecutablePath + "\" " + ConvertToArgs(urls, options))); processStartInfo.Arguments = "/C chcp 65001 >nul 2>&1 && " + text; } else if (!string.IsNullOrEmpty(PythonPath)) { processStartInfo.FileName = PythonPath; processStartInfo.Arguments = "\"" + ExecutablePath + "\" " + ConvertToArgs(urls, options); } else { processStartInfo.FileName = ExecutablePath; processStartInfo.Arguments = ConvertToArgs(urls, options); } process.EnableRaisingEvents = true; process.StartInfo = processStartInfo; TaskCompletionSource<bool> tcsOut = new TaskCompletionSource<bool>(); bool isDownloading = false; process.OutputDataReceived += delegate(object o, DataReceivedEventArgs e) { if (e.Data == null) { tcsOut.SetResult(result: true); } else { Match match; if ((match = rgxProgress.Match(e.Data)).Success) { if (match.Groups.Count > 1 && match.Groups[1].Length > 0) { float progress2 = float.Parse(match.Groups[1].ToString(), CultureInfo.InvariantCulture) / 100f; Group group = match.Groups["total"]; string totalDownloadSize = (group.Success ? group.Value : null); Group group2 = match.Groups["speed"]; string downloadSpeed = (group2.Success ? group2.Value : null); Group group3 = match.Groups["eta"]; string eta = (group3.Success ? group3.Value : null); progress?.Report(new DownloadProgress(DownloadState.Downloading, progress2, totalDownloadSize, downloadSpeed, eta)); } else { progress?.Report(new DownloadProgress(DownloadState.Downloading)); } isDownloading = true; } else if ((match = rgxPlaylist.Match(e.Data)).Success) { int index = int.Parse(match.Groups[1].Value); progress?.Report(new DownloadProgress(DownloadState.PreProcessing, 0f, null, null, null, index)); isDownloading = false; } else if (isDownloading && (match = rgxPost.Match(e.Data)).Success) { progress?.Report(new DownloadProgress(DownloadState.PostProcessing, 1f)); isDownloading = false; } this.OutputReceived?.Invoke(this, e); } }; TaskCompletionSource<bool> tcsError = new TaskCompletionSource<bool>(); process.ErrorDataReceived += delegate(object o, DataReceivedEventArgs e) { if (e.Data == null) { tcsError.SetResult(result: true); } else { progress?.Report(new DownloadProgress(DownloadState.Error, 0f, null, null, null, 1, e.Data)); this.ErrorReceived?.Invoke(this, e); } }; process.Exited += async delegate { await tcsOut.Task; await tcsError.Task; tcs.TrySetResult(process.ExitCode); process.Dispose(); }; ct.Register(delegate { if (!tcs.Task.IsCompleted) { tcs.TrySetCanceled(); } try { if (!process.HasExited) { process.KillTree(); } } catch { } }); if (!(await Task.Run(() => process.Start()))) { tcs.TrySetException(new InvalidOperationException("Failed to start yt-dlp process.")); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); progress?.Report(new DownloadProgress(DownloadState.PreProcessing)); return await tcs.Task; } } } namespace YoutubeDLSharp.Options { public enum DownloadMergeFormat { Unspecified, Mp4, Mkv, Ogg, Webm, Flv } public enum AudioConversionFormat { Best, Aac, Flac, Mp3, M4a, Opus, Vorbis, Wav } public enum VideoRecodeFormat { None, Mp4, Mkv, Ogg, Webm, Flv, Avi } public interface IOption { string DefaultOptionString { get; } string[] OptionStrings { get; } bool IsSet { get; } bool IsCustom { get; } void SetFromString(string s); IEnumerable<string> ToStringCollection(); } public class MultiOption<T> : IOption { private MultiValue<T> value; public string DefaultOptionString => OptionStrings.Last(); public string[] OptionStrings { get; } public bool IsSet { get; private set; } public bool IsCustom { get; } public MultiValue<T> Value { get { return value; } set { IsSet = !object.Equals(value, default(T)); this.value = value; } } public MultiOption(params string[] optionStrings) { OptionStrings = optionStrings; IsSet = false; } public MultiOption(bool isCustom, params string[] optionStrings) { OptionStrings = optionStrings; IsSet = false; IsCustom = isCustom; } public void SetFromString(string s) { string[] array = s.Split(new char[1] { ' ' }); string stringValue = s.Substring(array[0].Length).Trim().Trim(new char[1] { '"' }); if (!OptionStrings.Contains(array[0])) { throw new ArgumentException("Given string does not match required format."); } T val = Utils.OptionValueFromString<T>(stringValue); if (!IsSet) { Value = val; } else { Value.Values.Add(val); } } public override string ToString() { return string.Join(" ", ToStringCollection()); } public IEnumerable<string> ToStringCollection() { if (!IsSet) { return new string[1] { "" }; } List<string> list = new List<string>(); foreach (T value in Value.Values) { list.Add(DefaultOptionString + Utils.OptionValueToString(value)); } return list; } } public class MultiValue<T> { private readonly List<T> values; public List<T> Values => values; public MultiValue(params T[] values) { this.values = values.ToList(); } public static implicit operator MultiValue<T>(T value) { return new MultiValue<T>(value); } public static implicit operator MultiValue<T>(T[] values) { return new MultiValue<T>(values); } public static explicit operator T(MultiValue<T> value) { if (value.Values.Count == 1) { return value.Values[0]; } throw new InvalidCastException($"Cannot cast sequence of values to {typeof(T)}."); } public static explicit operator T[](MultiValue<T> value) { return value.Values.ToArray(); } } public class Option<T> : IOption { private T value; public string DefaultOptionString => OptionStrings.First(); public string[] OptionStrings { get; } public bool IsSet { get; private set; } public T Value { get { return value; } set { IsSet = !object.Equals(value, default(T)); this.value = value; } } public bool IsCustom { get; } public Option(params string[] optionStrings) { OptionStrings = optionStrings; IsSet = false; } public Option(bool isCustom, params string[] optionStrings) { OptionStrings = optionStrings; IsSet = false; IsCustom = isCustom; } public void SetFromString(string s) { string[] array = s.Split(new char[1] { ' ' }); string stringValue = s.Substring(array[0].Length).Trim().Trim(new char[1] { '"' }); if (!OptionStrings.Contains(array[0])) { throw new ArgumentException("Given string does not match required format."); } Value = Utils.OptionValueFromString<T>(stringValue); } public override string ToString() { if (!IsSet) { return string.Empty; } string text = Utils.OptionValueToString(Value); return DefaultOptionString + text; } public IEnumerable<string> ToStringCollection() { return new string[1] { ToString() }; } } internal class OptionComparer : IEqualityComparer<IOption> { public bool Equals(IOption x, IOption y) { if (x != null) { if (y != null) { return x.ToString().Equals(y.ToString()); } return false; } return y == null; } public int GetHashCode(IOption obj) { return obj.ToString().GetHashCode(); } } public class OptionSet : ICloneable { private Option<string> username = new Option<string>("-u", "--username"); private Option<string> password = new Option<string>("-p", "--password"); private Option<string> twoFactor = new Option<string>("-2", "--twofactor"); private Option<bool> netrc = new Option<bool>("-n", "--netrc"); private Option<string> netrcLocation = new Option<string>("--netrc-location"); private Option<string> netrcCmd = new Option<string>("--netrc-cmd"); private Option<string> videoPassword = new Option<string>("--video-password"); private Option<string> apMso = new Option<string>("--ap-mso"); private Option<string> apUsername = new Option<string>("--ap-username"); private Option<string> apPassword = new Option<string>("--ap-password"); private Option<bool> apListMso = new Option<bool>("--ap-list-mso"); private Option<string> clientCertificate = new Option<string>("--client-certificate"); private Option<string> clientCertificateKey = new Option<string>("--client-certificate-key"); private Option<string> clientCertificatePassword = new Option<string>("--client-certificate-password"); private static readonly OptionComparer Comparer = new OptionComparer(); public static readonly OptionSet Default = new OptionSet(); private Option<bool> getDescription = new Option<bool>("--get-description"); private Option<bool> getDuration = new Option<bool>("--get-duration"); private Option<bool> getFilename = new Option<bool>("--get-filename"); private Option<bool> getFormat = new Option<bool>("--get-format"); private Option<bool> getId = new Option<bool>("--get-id"); private Option<bool> getThumbnail = new Option<bool>("--get-thumbnail"); private Option<bool> getTitle = new Option<bool>("-e", "--get-title"); private Option<bool> getUrl = new Option<bool>("-g", "--get-url"); private Option<string> matchTitle = new Option<string>("--match-title"); private Option<string> rejectTitle = new Option<string>("--reject-title"); private Option<long?> minViews = new Option<long?>("--min-views"); private Option<long?> maxViews = new Option<long?>("--max-views"); private Option<bool> breakOnReject = new Option<bool>("--break-on-reject"); private Option<string> userAgent = new Option<string>("--user-agent"); private Option<string> referer = new Option<string>("--referer"); private Option<int?> playlistStart = new Option<int?>("--playlist-start"); private Option<int?> playlistEnd = new Option<int?>("--playlist-end"); private Option<bool> playlistReverse = new Option<bool>("--playlist-reverse"); private Option<bool> noColors = new Option<bool>("--no-colors"); private Option<bool> forceGenericExtractor = new Option<bool>("--force-generic-extractor"); private Option<string> execBeforeDownload = new Option<string>("--exec-before-download"); private Option<bool> noExecBeforeDownload = new Option<bool>("--no-exec-before-download"); private Option<bool> allFormats = new Option<bool>("--all-formats"); private Option<bool> allSubs = new Option<bool>("--all-subs"); private Option<bool> printJson = new Option<bool>("--print-json"); private Option<string> autonumberSize = new Option<string>("--autonumber-size"); private Option<int?> autonumberStart = new Option<int?>("--autonumber-start"); private Option<bool> id = new Option<bool>("--id"); private Option<string> metadataFromTitle = new Option<string>("--metadata-from-title"); private Option<bool> hlsPreferNative = new Option<bool>("--hls-prefer-native"); private Option<bool> hlsPreferFfmpeg = new Option<bool>("--hls-prefer-ffmpeg"); private Option<bool> listFormatsOld = new Option<bool>("--list-formats-old", "--no-list-formats-as-table"); private Option<bool> listFormatsAsTable = new Option<bool>("--list-formats-as-table", "--no-list-formats-old"); private Option<bool> youtubeSkipDashManifest = new Option<bool>("--youtube-skip-dash-manifest", "--no-youtube-include-dash-manifest"); private Option<bool> youtubeSkipHlsManifest = new Option<bool>("--youtube-skip-hls-manifest", "--no-youtube-include-hls-manifest"); private Option<bool> geoBypass = new Option<bool>("--geo-bypass"); private Option<bool> noGeoBypass = new Option<bool>("--no-geo-bypass"); private Option<string> geoBypassCountry = new Option<string>("--geo-bypass-country"); private Option<string> geoBypassIpBlock = new Option<string>("--geo-bypass-ip-block"); private Option<int?> concurrentFragments = new Option<int?>("-N", "--concurrent-fragments"); private Option<long?> limitRate = new Option<long?>("-r", "--limit-rate"); private Option<long?> throttledRate = new Option<long?>("--throttled-rate"); private Option<int?> retries = new Option<int?>("-R", "--retries"); private Option<int?> fileAccessRetries = new Option<int?>("--file-access-retries"); private Option<int?> fragmentRetries = new Option<int?>("--fragment-retries"); private MultiOption<string> retrySleep = new MultiOption<string>("--retry-sleep"); private Option<bool> skipUnavailableFragments = new Option<bool>("--skip-unavailable-fragments", "--no-abort-on-unavailable-fragments"); private Option<bool> abortOnUnavailableFragments = new Option<bool>("--abort-on-unavailable-fragments", "--no-skip-unavailable-fragments"); private Option<bool> keepFragments = new Option<bool>("--keep-fragments"); private Option<bool> noKeepFragments = new Option<bool>("--no-keep-fragments"); private Option<long?> bufferSize = new Option<long?>("--buffer-size"); private Option<bool> resizeBuffer = new Option<bool>("--resize-buffer"); private Option<bool> noResizeBuffer = new Option<bool>("--no-resize-buffer"); private Option<long?> httpChunkSize = new Option<long?>("--http-chunk-size"); private Option<bool> playlistRandom = new Option<bool>("--playlist-random"); private Option<bool> lazyPlaylist = new Option<bool>("--lazy-playlist"); private Option<bool> noLazyPlaylist = new Option<bool>("--no-lazy-playlist"); private Option<bool> xattrSetFilesize = new Option<bool>("--xattr-set-filesize"); private Option<bool> hlsUseMpegts = new Option<bool>("--hls-use-mpegts"); private Option<bool> noHlsUseMpegts = new Option<bool>("--no-hls-use-mpegts"); private MultiOption<string> downloadSections = new MultiOption<string>("--download-sections"); private MultiOption<string> downloader = new MultiOption<string>("--downloader", "--external-downloader"); private MultiOption<string> downloaderArgs = new MultiOption<string>("--downloader-args", "--external-downloader-args"); private Option<int?> extractorRetries = new Option<int?>("--extractor-retries"); private Option<bool> allowDynamicMpd = new Option<bool>("--allow-dynamic-mpd", "--no-ignore-dynamic-mpd"); private Option<bool> ignoreDynamicMpd = new Option<bool>("--ignore-dynamic-mpd", "--no-allow-dynamic-mpd"); private Option<bool> hlsSplitDiscontinuity = new Option<bool>("--hls-split-discontinuity"); private Option<bool> noHlsSplitDiscontinuity = new Option<bool>("--no-hls-split-discontinuity"); private MultiOption<string> extractorArgs = new MultiOption<string>("--extractor-args"); private Option<string> batchFile = new Option<string>("-a", "--batch-file"); private Option<bool> noBatchFile = new Option<bool>("--no-batch-file"); private Option<string> paths = new Option<string>("-P", "--paths"); private Option<string> output = new Option<string>("-o", "--output"); private Option<string> outputNaPlaceholder = new Option<string>("--output-na-placeholder"); private Option<bool> restrictFilenames = new Option<bool>("--restrict-filenames"); private Option<bool> noRestrictFilenames = new Option<bool>("--no-restrict-filenames"); private Option<bool> windowsFilenames = new Option<bool>("--windows-filenames"); private Option<bool> noWindowsFilenames = new Option<bool>("--no-windows-filenames"); private Option<int?> trimFilenames = new Option<int?>("--trim-filenames"); private Option<bool> noOverwrites = new Option<bool>("-w", "--no-overwrites"); private Option<bool> forceOverwrites = new Option<bool>("--force-overwrites"); private Option<bool> noForceOverwrites = new Option<bool>("--no-force-overwrites"); private Option<bool> doContinue = new Option<bool>("-c", "--continue"); private Option<bool> noContinue = new Option<bool>("--no-continue"); private Option<bool> part = new Option<bool>("--part"); private Option<bool> noPart = new Option<bool>("--no-part"); private Option<bool> mtime = new Option<bool>("--mtime"); private Option<bool> noMtime = new Option<bool>("--no-mtime"); private Option<bool> writeDescription = new Option<bool>("--write-description"); private Option<bool> noWriteDescription = new Option<bool>("--no-write-description"); private Option<bool> writeInfoJson = new Option<bool>("--write-info-json"); private Option<bool> noWriteInfoJson = new Option<bool>("--no-write-info-json"); private Option<bool> writePlaylistMetafiles = new Option<bool>("--write-playlist-metafiles"); private Option<bool> noWritePlaylistMetafiles = new Option<bool>("--no-write-playlist-metafiles"); private Option<bool> cleanInfoJson = new Option<bool>("--clean-info-json"); private Option<bool> noCleanInfoJson = new Option<bool>("--no-clean-info-json"); private Option<bool> writeComments = new Option<bool>("--write-comments", "--get-comments"); private Option<bool> noWriteComments = new Option<bool>("--no-write-comments", "--no-get-comments"); private Option<string> loadInfoJson = new Option<string>("--load-info-json"); private Option<string> cookies = new Option<string>("--cookies"); private Option<bool> noCookies = new Option<bool>("--no-cookies"); private Option<string> cookiesFromBrowser = new Option<string>("--cookies-from-browser"); private Option<bool> noCookiesFromBrowser = new Option<bool>("--no-cookies-from-browser"); private Option<string> cacheDir = new Option<string>("--cache-dir"); private Option<bool> noCacheDir = new Option<bool>("--no-cache-dir"); private Option<bool> removeCacheDir = new Option<bool>("--rm-cache-dir"); private Option<bool> help = new Option<bool>("-h", "--help"); private Option<bool> version = new Option<bool>("--version"); private Option<bool> update = new Option<bool>("-U", "--update"); private Option<bool> noUpdate = new Option<bool>("--no-update"); private Option<string> updateTo = new Option<string>("--update-to"); private Option<bool> ignoreErrors = new Option<bool>("-i", "--ignore-errors"); private Option<bool> noAbortOnError = new Option<bool>("--no-abort-on-error"); private Option<bool> abortOnError = new Option<bool>("--abort-on-error", "--no-ignore-errors"); private Option<bool> dumpUserAgent = new Option<bool>("--dump-user-agent"); private Option<bool> listExtractors = new Option<bool>("--list-extractors"); private Option<bool> extractorDescriptions = new Option<bool>("--extractor-descriptions"); private Option<string> useExtractors = new Option<string>("--use-extractors", "--ies"); private Option<string> defaultSearch = new Option<string>("--default-search"); private Option<bool> ignoreConfig = new Option<bool>("--ignore-config", "--no-config"); private Option<bool> noConfigLocations = new Option<bool>("--no-config-locations"); private MultiOption<string> configLocations = new MultiOption<string>("--config-locations"); private Option<bool> flatPlaylist = new Option<bool>("--flat-playlist"); private Option<bool> noFlatPlaylist = new Option<bool>("--no-flat-playlist"); private Option<bool> liveFromStart = new Option<bool>("--live-from-start"); private Option<bool> noLiveFromStart = new Option<bool>("--no-live-from-start"); private Option<string> waitForVideo = new Option<string>("--wait-for-video"); private Option<bool> noWaitForVideo = new Option<bool>("--no-wait-for-video"); private Option<bool> markWatched = new Option<bool>("--mark-watched"); private Option<bool> noMarkWatched = new Option<bool>("--no-mark-watched"); private MultiOption<string> color = new MultiOption<string>("--color"); private Option<string> compatOptions = new Option<string>("--compat-options"); private MultiOption<string> alias = new MultiOption<string>("--alias"); private Option<string> geoVerificationProxy = new Option<string>("--geo-verification-proxy"); private Option<string> xff = new Option<string>("--xff"); private Option<bool> writeLink = new Option<bool>("--write-link"); private Option<bool> writeUrlLink = new Option<bool>("--write-url-link"); private Option<bool> writeWeblocLink = new Option<bool>("--write-webloc-link"); private Option<bool> writeDesktopLink = new Option<bool>("--write-desktop-link"); private Option<string> proxy = new Option<string>("--proxy"); private Option<int?> socketTimeout = new Option<int?>("--socket-timeout"); private Option<string> sourceAddress = new Option<string>("--source-address"); private Option<bool> forceIPv4 = new Option<bool>("-4", "--force-ipv4"); private Option<bool> forceIPv6 = new Option<bool>("-6", "--force-ipv6"); private Option<bool> enableFileUrls = new Option<bool>("--enable-file-urls"); private Option<bool> extractAudio = new Option<bool>("-x", "--extract-audio"); private Option<AudioConversionFormat> audioFormat = new Option<AudioConversionFormat>("--audio-format"); private Option<byte?> audioQuality = new Option<byte?>("--audio-quality"); private Option<string> remuxVideo = new Option<string>("--remux-video"); private Option<VideoRecodeFormat> recodeVideo = new Option<VideoRecodeFormat>("--recode-video"); private MultiOption<string> postprocessorArgs = new MultiOption<string>("--postprocessor-args", "--ppa"); private Option<bool> keepVideo = new Option<bool>("-k", "--keep-video"); private Option<bool> noKeepVideo = new Option<bool>("--no-keep-video"); private Option<bool> postOverwrites = new Option<bool>("--post-overwrites"); private Option<bool> noPostOverwrites = new Option<bool>("--no-post-overwrites"); private Option<bool> embedSubs = new Option<bool>("--embed-subs"); private Option<bool> noEmbedSubs = new Option<bool>("--no-embed-subs"); private Option<bool> embedThumbnail = new Option<bool>("--embed-thumbnail"); private Option<bool> noEmbedThumbnail = new Option<bool>("--no-embed-thumbnail"); private Option<bool> embedMetadata = new Option<bool>("--embed-metadata", "--add-metadata"); private Option<bool> noEmbedMetadata = new Option<bool>("--no-embed-metadata", "--no-add-metadata"); private Option<bool> embedChapters = new Option<bool>("--embed-chapters", "--add-chapters"); private Option<bool> noEmbedChapters = new Option<bool>("--no-embed-chapters", "--no-add-chapters"); private Option<bool> embedInfoJson = new Option<bool>("--embed-info-json"); private Option<bool> noEmbedInfoJson = new Option<bool>("--no-embed-info-json"); private Option<string> parseMetadata = new Option<string>("--parse-metadata"); private MultiOption<string> replaceInMetadata = new MultiOption<string>("--replace-in-metadata"); private Option<bool> xattrs = new Option<bool>("--xattrs"); private Option<string> concatPlaylist = new Option<string>("--concat-playlist"); private Option<string> fixup = new Option<string>("--fixup"); private Option<string> ffmpegLocation = new Option<string>("--ffmpeg-location"); private MultiOption<string> exec = new MultiOption<string>("--exec"); private Option<bool> noExec = new Option<bool>("--no-exec"); private Option<string> convertSubs = new Option<string>("--convert-subs", "--convert-subtitles"); private Option<string> convertThumbnails = new Option<string>("--convert-thumbnails"); private Option<bool> splitChapters = new Option<bool>("--split-chapters"); private Option<bool> noSplitChapters = new Option<bool>("--no-split-chapters"); private MultiOption<string> removeChapters = new MultiOption<string>("--remove-chapters"); private Option<bool> noRemoveChapters = new Option<bool>("--no-remove-chapters"); private Option<bool> forceKeyframesAtCuts = new Option<bool>("--force-keyframes-at-cuts"); private Option<bool> noForceKeyframesAtCuts = new Option<bool>("--no-force-keyframes-at-cuts"); private MultiOption<string> usePostprocessor = new MultiOption<string>("--use-postprocessor"); private Option<string> sponsorblockMark = new Option<string>("--sponsorblock-mark"); private Option<string> sponsorblockRemove = new Option<string>("--sponsorblock-remove"); private Option<string> sponsorblockChapterTitle = new Option<string>("--sponsorblock-chapter-title"); private Option<bool> noSponsorblock = new Option<bool>("--no-sponsorblock"); private Option<string> sponsorblockApi = new Option<string>("--sponsorblock-api"); private Option<bool> writeSubs = new Option<bool>("--write-subs"); private Option<bool> noWriteSubs = new Option<bool>("--no-write-subs"); private Option<bool> writeAutoSubs = new Option<bool>("--write-auto-subs", "--write-automatic-subs"); private Option<bool> noWriteAutoSubs = new Option<bool>("--no-write-auto-subs", "--no-write-automatic-subs"); private Option<bool> listSubs = new Option<bool>("--list-subs"); private Option<string> subFormat = new Option<string>("--sub-format"); private Option<string> subLangs = new Option<string>("--sub-langs"); private Option<bool> writeThumbnail = new Option<bool>("--write-thumbnail"); private Option<bool> noWriteThumbnail = new Option<bool>("--no-write-thumbnail"); private Option<bool> writeAllThumbnails = new Option<bool>("--write-all-thumbnails"); private Option<bool> listThumbnails = new Option<bool>("--list-thumbnails"); private Option<bool> quiet = new Option<bool>("-q", "--quiet"); private Option<bool> noQuiet = new Option<bool>("--no-quiet"); private Option<bool> noWarnings = new Option<bool>("--no-warnings"); private Option<bool> simulate = new Option<bool>("-s", "--simulate"); private Option<bool> noSimulate = new Option<bool>("--no-simulate"); private Option<bool> ignoreNoFormatsError = new Option<bool>("--ignore-no-formats-error"); private Option<bool> noIgnoreNoFormatsError = new Option<bool>("--no-ignore-no-formats-error"); private Option<bool> skipDownload = new Option<bool>("--skip-download", "--no-download"); private MultiOption<string> print = new MultiOption<string>("-O", "--print"); private MultiOption<string> printToFile = new MultiOption<string>("--print-to-file"); private Option<bool> dumpJson = new Option<bool>("-j", "--dump-json"); private Option<bool> dumpSingleJson = new Option<bool>("-J", "--dump-single-json"); private Option<bool> forceWriteArchive = new Option<bool>("--force-write-archive", "--force-download-archive"); private Option<bool> newline = new Option<bool>("--newline"); private Option<bool> noProgress = new Option<bool>("--no-progress"); private Option<bool> progress = new Option<bool>("--progress"); private Option<bool> consoleTitle = new Option<bool>("--console-title"); private Option<string> progressTemplate = new Option<string>("--progress-template"); private Option<bool> verbose = new Option<bool>("-v", "--verbose"); private Option<bool> dumpPages = new Option<bool>("--dump-pages"); private Option<bool> writePages = new Option<bool>("--write-pages"); private Option<bool> printTraffic = new Option<bool>("--print-traffic"); private Option<string> format = new Option<string>("-f", "--format"); private Option<string> formatSort = new Option<string>("-S", "--format-sort"); private Option<bool> formatSortForce = new Option<bool>("--format-sort-force", "--S-force"); private Option<bool> noFormatSortForce = new Option<bool>("--no-format-sort-force"); private Option<bool> videoMultistreams = new Option<bool>("--video-multistreams"); private Option<bool> noVideoMultistreams = new Option<bool>("--no-video-multistreams"); private Option<bool> audioMultistreams = new Option<bool>("--audio-multistreams"); private Option<bool> noAudioMultistreams = new Option<bool>("--no-audio-multistreams"); private Option<bool> preferFreeFormats = new Option<bool>("--prefer-free-formats"); private Option<bool> noPreferFreeFormats = new Option<bool>("--no-prefer-free-formats"); private Option<bool> checkFormats = new Option<bool>("--check-formats"); private Option<bool> checkAllFormats = new Option<bool>("--check-all-formats"); private Option<bool> noCheckFormats = new Option<bool>("--no-check-formats"); private Option<bool> listFormats = new Option<bool>("-F", "--list-formats"); private Option<DownloadMergeFormat> mergeOutputFormat = new Option<DownloadMergeFormat>("--merge-output-format"); private Option<string> playlistItems = new Option<string>("-I", "--playlist-items"); private Option<string> minFilesize = new Option<string>("--min-filesize"); private Option<string> maxFilesize = new Option<string>("--max-filesize"); private Option<DateTime> date = new Option<DateTime>("--date"); private Option<DateTime> dateBefore = new Option<DateTime>("--datebefore"); private Option<DateTime> dateAfter = new Option<DateTime>("--dateafter"); private MultiOption<string> matchFilters = new MultiOption<string>("--match-filters"); private Option<bool> noMatchFilters = new Option<bool>("--no-match-filters"); private Option<string> breakMatchFilters = new Option<string>("--break-match-filters"); private Option<bool> noBreakMatchFilters = new Option<bool>("--no-break-match-filters"); private Option<bool> noPlaylist = new Option<bool>("--no-playlist"); private Option<bool> yesPlaylist = new Option<bool>("--yes-playlist"); private Option<byte?> ageLimit = new Option<byte?>("--age-limit"); private Option<string> downloadArchive = new Option<string>("--download-archive"); private Option<bool> noDownloadArchive = new Option<bool>("--no-download-archive"); private Option<int?> maxDownloads = new Option<int?>("--max-downloads"); private Option<bool> breakOnExisting = new Option<bool>("--break-on-existing"); private Option<bool> breakPerInput = new Option<bool>("--break-per-input"); private Option<bool> noBreakPerInput = new Option<bool>("--no-break-per-input"); private Option<int?> skipPlaylistAfterErrors = new Option<int?>("--skip-playlist-after-errors"); private Option<string> encoding = new Option<string>("--encoding"); private Option<bool> legacyServerConnect = new Option<bool>("--legacy-server-connect"); private Option<bool> noCheckCertificates = new Option<bool>("--no-check-certificates"); private Option<bool> preferInsecure = new Option<bool>("--prefer-insecure"); private MultiOption<string> addHeaders = new MultiOption<string>("--add-headers"); private Option<bool> bidiWorkaround = new Option<bool>("--bidi-workaround"); private Option<int?> sleepRequests = new Option<int?>("--sleep-requests"); private Option<int?> sleepInterval = new Option<int?>("--sleep-interval", "--min-sleep-interval"); private Option<int?> maxSleepInterval = new Option<int?>("--max-sleep-interval"); private Option<int?> sleepSubtitles = new Option<int?>("--sleep-subtitles"); public string Username { get { return username.Value; } set { username.Value = value; } } public string Password { get { return password.Value; } set { password.Value = value; } } public string TwoFactor { get { return twoFactor.Value; } set { twoFactor.Value = value; } } public bool Netrc { get { return netrc.Value; } set { netrc.Value = value; } } public string NetrcLocation { get { return netrcLocation.Value; } set { netrcLocation.Value = value; } } public string NetrcCmd { get { return netrcCmd.Value; } set { netrcCmd.Value = value; } } public string VideoPassword { get { return videoPassword.Value; } set { videoPassword.Value = value; } } public string ApMso { get { return apMso.Value; } set { apMso.Value = value; } } public string ApUsername { get { return apUsername.Value; } set { apUsername.Value = value; } } public string ApPassword { get { return apPassword.Value; } set { apPassword.Value = value; } } public bool ApListMso { get { return apListMso.Value; } set { apListMso.Value = value; } } public string ClientCertificate { get { return clientCertificate.Value; } set { clientCertificate.Value = value; } } public string ClientCertificateKey { get { return clientCertificateKey.Value; } set { clientCertificateKey.Value = value; } } public string ClientCertificatePassword { get { return clientCertificatePassword.Value; } set { clientCertificatePassword.Value = value; } } public IOption[] CustomOptions { get; set; } = new IOption[0]; [Obsolete("Deprecated in favor of: --print description.")] public bool GetDescription { get { return getDescription.Value; } set { getDescription.Value = value; } } [Obsolete("Deprecated in favor of: --print duration_string.")] public bool GetDuration { get { return getDuration.Value; } set { getDuration.Value = value; } } [Obsolete("Deprecated in favor of: --print filename.")] public bool GetFilename { get { return getFilename.Value; } set { getFilename.Value = value; } } [Obsolete("Deprecated in favor of: --print format.")] public bool GetFormat { get { return getFormat.Value; } set { getFormat.Value = value; } } [Obsolete("Deprecated in favor of: --print id.")] public bool GetId { get { return getId.Value; } set { getId.Value = value; } } [Obsolete("Deprecated in favor of: --print thumbnail.")] public bool GetThumbnail { get { return getThumbnail.Value; } set { getThumbnail.Value = value; } } [Obsolete("Deprecated in favor of: --print title.")] public bool GetTitle { get { return getTitle.Value; } set { getTitle.Value = value; } } [Obsolete("Deprecated in favor of: --print urls.")] public bool GetUrl { get { return getUrl.Value; } set { getUrl.Value = value; } } [Obsolete("Deprecated in favor of: --match-filter \"title ~= (?i)REGEX\".")] public string MatchTitle { get { return matchTitle.Value; } set { matchTitle.Value = value; } } [Obsolete("Deprecated in favor of: --match-filter \"title !~= (?i)REGEX\".")] public string RejectTitle { get { return rejectTitle.Value; } set { rejectTitle.Value = value; } } [Obsolete("Deprecated in favor of: --match-filter \"view_count >=? COUNT\".")] public long? MinViews { get { return minViews.Value; } set { minViews.Value = value; } } [Obsolete("Deprecated in favor of: --match-filter \"view_count <=? COUNT\".")] public long? MaxViews { get { return maxViews.Value; } set { maxViews.Value = value; } } [Obsolete("Deprecated in favor of: Use --break-match-filter.")] public bool BreakOnReject { get { return breakOnReject.Value; } set { breakOnReject.Value = value; } } [Obsolete("Deprecated in favor of: --add-header \"User-Agent:UA\".")] public string UserAgent { get { return userAgent.Value; } set { userAgent.Value = value; } } [Obsolete("Deprecated in favor of: --add-header \"Referer:URL\".")] public string Referer { get { return referer.Value; } set { referer.Value = value; } } [Obsolete("Deprecated in favor of: -I NUMBER:.")] public int? PlaylistStart { get { return playlistStart.Value; } set { playlistStart.Value = value; } } [Obsolete("Deprecated in favor of: -I :NUMBER.")] public int? PlaylistEnd { get { return playlistEnd.Value; } set { playlistEnd.Value = value; } } [Obsolete("Deprecated in favor of: -I ::-1.")] public bool PlaylistReverse { get { return playlistReverse.Value; } set { playlistReverse.Value = value; } } [Obsolete("Deprecated in favor of: --color no_color.")] public bool NoColors { get { return noColors.Value; } set { noColors.Value = value; } } [Obsolete("Deprecated in favor of: --ies generic,default.")] public bool ForceGenericExtractor { get { return forceGenericExtractor.Value; } set { forceGenericExtractor.Value = value; } } [Obsolete("Deprecated in favor of: --exec \"before_dl:CMD\".")] public string ExecBeforeDownload { get { return execBeforeDownload.Value; } set { execBeforeDownload.Value = value; } } [Obsolete("Deprecated in favor of: --no-exec.")] public bool NoExecBeforeDownload { get { return noExecBeforeDownload.Value; } set { noExecBeforeDownload.Value = value; } } [Obsolete("Deprecated in favor of: -f all.")] public bool AllFormats { get { return allFormats.Value; } set { allFormats.Value = value; } } [Obsolete("Deprecated in favor of: --sub-langs all --write-subs.")] public bool AllSubs { get { return allSubs.Value; } set { allSubs.Value = value; } } [Obsolete("Deprecated in favor of: -j --no-simulate.")] public bool PrintJson { get { return printJson.Value; } set { printJson.Value = value; } } [Obsolete("Deprecated in favor of: Use string formatting, e.g. %(autonumber)03d.")] public string AutonumberSize { get { return autonumberSize.Value; } set { autonumberSize.Value = value; } } [Obsolete("Deprecated in favor of: Use internal field formatting like %(autonumber+NUMBER)s.")] public int? AutonumberStart { get { return autonumberStart.Value; } set { autonumberStart.Value = value; } } [Obsolete("Deprecated in favor of: -o \"%(id)s.%(ext)s\".")] public bool Id { get { return id.Value; } set { id.Value = value; } } [Obsolete("Deprecated in favor of: --parse-metadata \"%(title)s:FORMAT\".")] public string MetadataFromTitle { get { return metadataFromTitle.Value; } set { metadataFromTitle.Value = value; } } [Obsolete("Deprecated in favor of: --downloader \"m3u8:native\".")] public bool HlsPreferNative { get { return hlsPreferNative.Value; } set { hlsPreferNative.Value = value; } } [Obsolete("Deprecated in favor of: --downloader \"m3u8:ffmpeg\".")] public bool HlsPreferFfmpeg { get { return hlsPreferFfmpeg.Value; } set { hlsPreferFfmpeg.Value = value; } } [Obsolete("Deprecated in favor of: --compat-options list-formats (Alias: --no-list-formats-as-table).")] public bool ListFormatsOld { get { return listFormatsOld.Value; } set { listFormatsOld.Value = value; } } [Obsolete("Deprecated in favor of: --compat-options -list-formats [Default] (Alias: --no-list-formats-old).")] public bool ListFormatsAsTable { get { return listFormatsAsTable.Value; } set { listFormatsAsTable.Value = value; } } [Obsolete("Deprecated in favor of: --extractor-args \"youtube:skip=dash\" (Alias: --no-youtube-include-dash-manifest).")] public bool YoutubeSkipDashManifest { get { return youtubeSkipDashManifest.Value; } set { youtubeSkipDashManifest.Value = value; } } [Obsolete("Deprecated in favor of: --extractor-args \"youtube:skip=hls\" (Alias: --no-youtube-include-hls-manifest).")] public bool YoutubeSkipHlsManifest { get { return youtubeSkipHlsManifest.Value; } set { youtubeSkipHlsManifest.Value = value; } } [Obsolete("Deprecated in favor of: --xff \"default\".")] public bool GeoBypass { get { return geoBypass.Value; } set { geoBypass.Value = value; } } [Obsolete("Deprecated in favor of: --xff \"never\".")] public bool NoGeoBypass { get { return noGeoBypass.Value; } set { noGeoBypass.Value = value; } } [Obsolete("Deprecated in favor of: --xff CODE.")] public string GeoBypassCountry { get { return geoBypassCountry.Value; } set { geoBypassCountry.Value = value; } } [Obsolete("Deprecated in favor of: --xff IP_BLOCK.")] public string GeoBypassIpBlock { get { return geoBypassIpBlock.Value; } set { geoBypassIpBlock.Value = value; } } public int? ConcurrentFragments { get { return concurrentFragments.Value; } set { concurrentFragments.Value = value; } } public long? LimitRate { get { return limitRate.Value; } set { limitRate.Value = value; } } public long? ThrottledRate { get { return throttledRate.Value; } set { throttledRate.Value = value; } } public int? Retries { get { return retries.Value; } set { retries.Value = value; } } public int? FileAccessRetries { get { return fileAccessRetries.Value; } set { fileAccessRetries.Value = value; } } public int? FragmentRetries { get { return fragmentRetries.Value; } set { fragmentRetries.Value = value; } } public MultiValue<string> RetrySleep { get { return retrySleep.Value; } set { retrySleep.Value = value; } } public bool SkipUnavailableFragments { get { return skipUnavailableFragments.Value; } set { skipUnavailableFragments.Value = value; } } public bool AbortOnUnavailableFragments { get { return abortOnUnavailableFragments.Value; } set { abortOnUnavailableFragments.Value = value; } } public bool KeepFragments { get { return keepFragments.Value; } set { keepFragments.Value = value; } } public bool NoKeepFragments { get { return noKeepFragments.Value; } set { noKeepFragments.Value = value; } } public long? BufferSize { get { return bufferSize.Value; } set { bufferSize.Value = value; } } public bool ResizeBuffer { get { return resizeBuffer.Value; } set { resizeBuffer.Value = value; } } public bool NoResizeBuffer { get { return noResizeBuffer.Value; } set { noResizeBuffer.Value = value; } } public long? HttpChunkSize { get { return httpChunkSize.Value; } set { httpChunkSize.Value = value; } } public bool PlaylistRandom { get { return playlistRandom.Value; } set { playlistRandom.Value = value; } } public bool LazyPlaylist { get { return lazyPlaylist.Value; } set { lazyPlaylist.Value = value; } } public bool NoLazyPlaylist { get { return noLazyPlaylist.Value; } set { noLazyPlaylist.Value = value; } } public bool XattrSetFilesize { get { return xattrSetFilesize.Value; } set { xattrSetFilesize.Value = value; } } public bool HlsUseMpegts { get { return hlsUseMpegts.Value; } set { hlsUseMpegts.Value = value; } } public bool NoHlsUseMpegts { get { return noHlsUseMpegts.Value; } set { noHlsUseMpegts.Value = value; } } public MultiValue<string> DownloadSections { get { return downloadSections.Value; } set { downloadSections.Value = value; } } public MultiValue<string> Downloader { get { return downloader.Value; } set { downloader.Value = value; } } public MultiValue<string> DownloaderArgs { get { return downloaderArgs.Value; } set { downloaderArgs.Value = value; } } public int? ExtractorRetries { get { return extractorRetries.Value; } set { extractorRetries.Value = value; } } public bool AllowDynamicMpd { get { return allowDynamicMpd.Value; } set { allowDynamicMpd.Value = value; } } public bool IgnoreDynamicMpd { get { return ignoreDynamicMpd.Value; } set { ignoreDynamicMpd.Value = value; } } public bool HlsSplitDiscontinuity { get { return hlsSplitDiscontinuity.Value; } set { hlsSplitDiscontinuity.Value = value; } } public bool NoHlsSplitDiscontinuity { get { return noHlsSplitDiscontinuity.Value; } set { noHlsSplitDiscontinuity.Value = value; } } public MultiValue<string> ExtractorArgs { get { return extractorArgs.Value; } set { extractorArgs.Value = value; } } public string BatchFile { get { return batchFile.Value; } set { batchFile.Value = value; } } public bool NoBatchFile { get { return noBatchFile.Value; } set { noBatchFile.Value = value; } } public string Paths { get { return paths.Value; } set { paths.Value = value; } } public string Output { get { return output.Value; } set { output.Value = value; } } public string OutputNaPlaceholder { get { return outputNaPlaceholder.Value; } set { outputNaPlaceholder.Value = value; } } public bool RestrictFilenames { get { return restrictFilenames.Value; } set { restrictFilenames.Value = value; } } public bool NoRestrictFilenames { get { return noRestrictFilenames.Value; } set { noRestrictFilenames.Value = value; } } public bool WindowsFilenames { get { return windowsFilenames.Value; } set { windowsFilenames.Value = value; } } public bool NoWindowsFilenames { get { return noWindowsFilenames.Value; } set { noWindowsFilenames.Value = value; } } public int? TrimFilenames { get { return trimFilenames.Value; } set { trimFilenames.Value = value; } } public bool NoOverwrites { get { return noOverwrites.Value; } set { noOverwrites.Value = value; } } public bool ForceOverwrites { get { return forceOverwrites.Value; } set { forceOverwrites.Value = value; } } public bool NoForceOverwrites { get { return noForceOverwrites.Value; } set { noForceOverwrites.Value = value; } } public bool Continue { get { return doContinue.Value; } set { doContinue.Value = value; } } public bool NoContinue { get { return noContinue.Value; } set { noContinue.Value = value; } } public bool Part { get { return part.Value; } set { part.Value = value; } } public bool NoPart { get { return noPart.Value; } set { noPart.Value = value; } } public bool Mtime { get { return mtime.Value; } set { mtime.Value = value; } } public bool NoMtime { get { return noMtime.Value; } set { noMtime.Value = value; } } public bool WriteDescription { get { return writeDescription.Value; } set { writeDescription.Value = value; } } public bool NoWriteDescription { get { return noWriteDescription.Value; } set { noWriteDescription.Value = value; } } public bool WriteInfoJson { get { return writeInfoJson.Value; } set { writeInfoJson.Value = value; } } public bool NoWriteInfoJson { get { return noWriteInfoJson.Value; } set { noWriteInfoJson.Value = value; } } public bool WritePlaylistMetafiles { get { return writePlaylistMetafiles.Value; } set { writePlaylistMetafiles.Value = value; } } public bool NoWritePlaylistMetafiles { get { return noWritePlaylistMetafiles.Value; } set { noWritePlaylistMetafiles.Value = value; } } public bool CleanInfoJson { get { return cleanInfoJson.Value; } set { cleanInfoJson.Value = value; } } public bool NoCleanInfoJson { get { return noCleanInfoJson.Value; } set { noCleanInfoJson.Value = value; } } public bool WriteComments { get { return writeComments.Value; } set { writeComments.Value = value; } } public bool NoWriteComments { get { return noWriteComments.Value; } set { noWriteComments.Value = value; } } public string LoadInfoJson { get { return loadInfoJson.Value; } set { loadInfoJson.Value = value; } } public string Cookies { get { return cookies.Value; } set { cookies.Value = value; } } public bool NoCookies { get { return noCookies.Value; } set { noCookies.Value = value; } } public string CookiesFromBrowser { get { return cookiesFromBrowser.Value; } set { cookiesFromBrowser.Value = value; } } public bool NoCookiesFromBrowser { get { return noCookiesFromBrowser.Value; } set { noCookiesFromBrowser.Value = value; } } public string CacheDir { get { return cacheDir.Value; } set { cacheDir.Value = value; } } public bool NoCacheDir { get { return noCacheDir.Value; } set { noCacheDir.Value = value; } } public bool RemoveCacheDir { get { return removeCacheDir.Value; } set { removeCacheDir.Value = value; } } public bool Help { get { return help.Value; } set { help.Value = value; } } public bool Version { get { return version.Value; } set { version.Value = value; } } public bool Update { get { return update.Value; } set { update.Value = value; } } public bool NoUpdate { get { return noUpdate.Value; } set { noUpdate.Value = value; } } public string UpdateTo { get { return updateTo.Value; } set { updateTo.Value = value; } } public bool IgnoreErrors { get { return ignoreErrors.Value; } set { ignoreErrors.Value = value; } } public bool NoAbortOnError { get { return noAbortOnError.Value; } set { noAbortOnError.Value = value; } } public bool AbortOnError { get { return abortOnError.Value; } set { abortOnError.Value = value; } } public bool DumpUserAgent { get { return dumpUserAgent.Value; } set { dumpUserAgent.Value = value; } } public bool ListExtractors { get { return listExtractors.Value; } set { listExtractors.Value = value; } } public bool ExtractorDescriptions { get { return extractorDescriptions.Value; } set { extractorDescriptions.Value = value; } } public string UseExtractors { get { return useExtractors.Value; } set { useExtractors.Value = value; } } public string DefaultSearch { get { return defaultSearch.Value; } set { defaultSearch.Value = value; } } public bool IgnoreConfig { get { return ignoreConfig.Value; } set { ignoreConfig.Value = value; } } public bool NoConfigLocations { get { return noConfigLocations.Value; } set { noConfigLocations.Value = value; } } public MultiValue<string> ConfigLocations { get { return configLocations.Value; } set { configLocations.Value = value; } } public bool FlatPlaylist { get { return flatPlaylist.Value; } set { flatPlaylist.Value = value; } } public bool NoFlatPlaylist { get { return noFlatPlaylist.Value; } set { noFlatPlaylist.Value = value; } } public bool LiveFromStart { get { return liveFromStart.Value; } set { liveFromStart.Value = value; } } public bool NoLiveFromStart { get { return noLiveFromStart.Value; } set { noLiveFromStart.Value = value; } } public string WaitForVideo { get { return waitForVideo.Value; } set { waitForVideo.Value = value; } } public bool NoWaitForVideo { get { return noWaitForVideo.Value; } set { noWaitForVideo.Value = value; } } public bool MarkWatched { get { return markWatched.Value; } set { markWatched.Value = value; } } public bool NoMarkWatched { get { return noMarkWatched.Value; } set { noMarkWatched.Value = value; } } public MultiValue<string> Color { get { return color.Value; } set { color.Value = value; } } public string CompatOptions { get { return compatOptions.Value; } set { compatOptions.Value = value; } } public MultiValue<string> Alias { get { return alias.Value; } set { alias.Value = value; } } public string GeoVerificationProxy { get { return geoVerificationProxy.Value; } set { geoVerificationProxy.Value = value; } } public string Xff { get { return xff.Value; } set { xff.Value = value; } } public bool WriteLink { get { return writeLink.Value; } set { writeLink.Value = value; } } public bool WriteUrlLink { get { return writeUrlLink.Value; } set { writeUrlLink.Value = value; } } public bool WriteWeblocLink { get { return writeWeblocLink.Value; } set { writeWeblocLink.Value = value; } } public bool WriteDesktopLink { get { return writeDesktopLink.Value; } set { writeDesktopLink.Value = value; } } public string Proxy { get { return proxy.Value; } set { proxy.Value = value; } } public int? SocketTimeout { get { return socketTimeout.Value; } set { socketTimeout.Value = value; } } public string SourceAddress { get { return sourceAddress.Value; } set { sourceAddress.Value = value; } } public bool ForceIPv4 { get { return forceIPv4.Value; } set { forceIPv4.Value = value; } } public bool ForceIPv6 { get { return forceIPv6.Value; } set { forceIPv6.Value = value; } } public bool EnableFileUrls { get { return enableFileUrls.Value; } set { enableFileUrls.Value = value; } } public bool ExtractAudio { get { return extractAudio.Value; } set { extractAudio.Value = value; } } public AudioConversionFormat AudioFormat { get { return audioFormat.Value; } set { audioFormat.Value = value; } } public byte? AudioQuality { get { return audioQuality.Value; } set { audioQuality.Value = value; } } public string RemuxVideo { get { return remuxVideo.Value; } set { remuxVideo.Value = value; } } public VideoRecodeFormat RecodeVideo { get { return recodeVideo.Value; } set { recodeVideo.Value = value; } } public MultiValue<string> PostprocessorArgs { get { return postprocessorArgs.Value; } set { postprocessorArgs.Value = value; } } public bool KeepVideo { get { return keepVideo.Value; } set { keepVideo.Value = value; } } public bool NoKeepVideo { get { return noKeepVideo.Value; } set { noKeepVideo.Value = value; } } public bool PostOverwrites { get { return postOverwrites.Value; } set { postOverwrites.Value = value; } } public bool NoPostOverwrites { get { return noPostOverwrites.Value; } set { noPostOverwrites.Value = value; } } public bool EmbedSubs { get { return embedSubs.Value; } set { embedSubs.Value = value; } } public bool NoEmbedSubs { get { return noEmbedSubs.Value; } set { noEmbedSubs.Value = value; } } public bool EmbedThumbnail { get { return embedThumbnail.Value; } set { embedThumbnail.Value = value; } } public bool NoEmbedThumbnail { get { return noEmbedThumbnail.Value; } set { noEmbedThumbnail.Value = value; } } public bool EmbedMetadata { get { return embedMetadata.Value; } set { embedMetadata.Value = value; } } public bool NoEmbedMetadata { get { return noEmbedMetadata.Value; } set { noEmbedMetadata.Value = value; } } public bool EmbedChapters { get { return embedChapters.Value; } set { embedChapters.Value = value; } } public bool NoEmbedChapters { get { return noEmbedChapters.Value; } set { noEmbedChapters.Value = value; } } public bool EmbedInfoJson { get { return embedInfoJson.Value; } set { embedInfoJson.Value = value; } } public bool NoEmbedInfoJson { get { return noEmbedInfoJson.Value; } set { noEmbedInfoJson.Value = value; } } public string ParseMetadata { get { return parseMetadata.Value; } set { parseMetadata.Value = value; } } public MultiValue<string> ReplaceInMetadata { get { return replaceInMetadata.Value; } set { replaceInMetadata.Value = value; } } public bool Xattrs { get { return xattrs.Value; } set { xattrs.Value = value; } } public string ConcatPlaylist { get { return concatPlaylist.Value; } set { concatPlaylist.Value = value; } } public string Fixup { get { return fixup.Value; } set { fixup.Value = value; } } public string FfmpegLocation { get { return ffmpegLocation.Value; } set { ffmpegLocation.Value = value; } } public MultiValue<string> Exec { get { return exec.Value; } set { exec.Value = value; } } public bool NoExec { get { return noExec.Value; } set { noExec.Value = value; } } public string ConvertSubs { get { return convertSubs.Value; } set { convertSubs.Value = value; } } public string ConvertThumbnails { get { return convertThumbnails.Value; } set { convertThumbnails.Value = value; } } public bool SplitChapters { get { return splitChapters.Value; } set { splitChapters.Value = value; } } public bool NoSplitChapters { get { return noSplitChapters.Value; } set { noSplitChapters.Value = value; } } public MultiValue<string> RemoveChapters { get { return removeChapters.Value; } set { removeChapters.Value = value; } } public bool NoRemoveChapters { get { return noRemoveChapters.Value; } set { noRemoveChapters.Value = value; } } public bool ForceKeyframesAtCuts { get { return forceKeyframesAtCuts.Value; } set { forceKeyframesAtCuts.Value = value; } } public bool NoForceKeyframesAtCuts { get { return noForceKeyframesAtCuts.Value; } set { noForceKeyframesAtCuts.Value = value; } } public MultiValue<string> UsePostprocessor { get { return usePostprocessor.Value; } set { usePostprocessor.Value = value; } } public string SponsorblockMark { get { return sponsorblockMark.Value; } set { sponsorblockMark.Value = value; } } public string SponsorblockRemove { get { return sponsorblockRemove.Value; } set { sponsorblockRemove.Value = value; } } public string SponsorblockChapterTitle { get { return sponsorblockChapterTitle.Value; } set { sponsorblockChapterTitle.Value = value; } } public bool NoSponsorblock { get { return noSponsorblock.Value; } set { noSponsorblock.Value = value; } } public string SponsorblockApi { get { return sponsorblockApi.Value; } set { sponsorblockApi.Value = value; } } public bool WriteSubs { get { return writeSubs.Value; } set { writeSubs.Value = value; } } public bool NoWriteSubs { get { return noWriteSubs.Value; } set { noWriteSubs.Value = value; } } public bool WriteAutoSubs { get { return writeAutoSubs.Value; } set { writeAutoSubs.Value = value; } } public bool NoWriteAutoSubs { get { return noWriteAutoSubs.Value; } set { noWriteAutoSubs.Value = value; } } public bool ListSubs { get { return listSubs.Value; } set { listSubs.Value = value; } } public string SubFormat { get { return subFormat.Value; } set { subFormat.Value = value; } } public string SubLangs { get { return subLangs.Value; } set { subLangs.Value = value; } } public bool WriteThumbnail { get { return writeThumbnail.Value; } set { writeThumbnail.Value = value; } } public bool NoWriteThumbnail { get { return noWriteThumbnail.Value; } set { noWriteThumbnail.Value = value; } } public bool WriteAllThumbnails { get { return writeAllThumbnails.Value; } set { writeAllThumbnails.Value = value; } } public bool ListThumbnails { get { return listThumbnails.Value; } set { listThumbnails.Value = value; } } public bool Quiet { get { return quiet.Value; } set { quiet.Value = value; } } public bool NoQuiet { get { return noQuiet.Value; } set { noQuiet.Value = value; } } public bool NoWarnings { get { return noWarnings.Value; } set { noWarnings.Value = value; } } public bool Simulate { get { return simulate.Value; } set { simulate.Value = value; } } public bool NoSimulate { get { return noSimulate.Value; } set { noSimulate.Value = value; } } public bool IgnoreNoFormatsError { get { return ignoreNoFormatsError.Value; } set { ignoreNoFormatsError.Value = value; } } public bool NoIgnoreNoFormatsError { get { return noIgnoreNoFormatsError.Value; } set { noIgnoreNoFormatsError.Value = value; } } public bool SkipDownload { get { return skipDownload.Value; } set { skipDownload.Value = value; } } public MultiValue<string> Print { get { return print.Value; } set { print.Value = value; } } public MultiValue<string> PrintToFile { get { return printToFile.Value; } set { printToFile.Value = value; } } public bool DumpJson { get { return dumpJson.Value; } set { dumpJson.Value = value; } } public bool DumpSingleJson { get { return dumpSingleJson.Value; } set { dumpSingleJson.Value = value; } } public bool ForceWriteArchive { get { return forceWriteArchive.Value; } set { forceWriteArchive.Value = value; } } public bool Newline { get { return newline.Value; } set { newline.Value = value; } } public bool NoProgress { get { return noProgress.Value; } set { noProgress.Value = value; } } public bool Progress { get { return progress.Value; } set { progress.Value = value; } } public bool ConsoleTitle { get { return consoleTitle.Value; } set { consoleTitle.Value = value; } } public string ProgressTemplate { get { return progressTemplate.Value; } set { progressTemplate.Value = value; } } public bool Verbose { get { return verbose.Value; } set { verbose.Value = value; } } public bool DumpPages { get { return dumpPages.Value; } set { dumpPages.Value = value; } } public bool WritePages { get { return writePages.Value; } set { writePages.Value = value; } } public bool PrintTraffic { get { return printTraffic.Value; } set { printTraffic.Value = value; } } public string Format { get { return format.Value; } set { format.Value = value; } } public string FormatSort { get { return formatSort.Value; } set { formatSort.Value = value; } } public bool FormatSortForce { get { return formatSortForce.Value; } set { formatSortForce.Value = value; } } public bool NoFormatSortForce { get { return noFormatSortForce.Value; } set { noFormatSortForce.Value = value; } } public bool VideoMultistreams { get { return videoMultistreams.Value; } set { videoMultistreams.Value = value; } } public bool NoVideoMultistreams { get { return noVideoMultistreams.Value; } set { noVideoMultistreams.Value = value; } } public bool AudioMultistreams { get { return audioMultistreams.Value; } set { audioMultistreams.Value = value; } } public bool NoAudioMultistreams { get { return noAudioMultistreams.Value; } set { noAudioMultistreams.Value = value; } } public bool PreferFreeFormats { get { return preferFreeFormats.Value; } set { preferFreeFormats.Value = value; } } public bool NoPreferFreeFormats { get { return noPreferFreeFormats.Value; } set { noPreferFreeFormats.Value = value; } } public bool CheckFormats { get { return checkFormats.Value; } set { checkFormats.Value = value; } } public bool CheckAllFormats { get { return checkAllFormats.Value; } set { checkAllFormats.Value = value; } } public bool NoCheckFormats { get { return noCheckFormats.Value; } set { noCheckFormats.Value = value; } } public bool ListFormats { get { return listFormats.Value; } set { listFormats.Value = value; } } public DownloadMergeFormat MergeOutputFormat { get { return mergeOutputFormat.Value; } set { mergeOutputFormat.Value = value; } } public string PlaylistItems { get { return playlistItems.Value; } set { playlistItems.Value = value; } } public string MinFilesize { get { return minFilesize.Value; } set { minFilesize.Value = value; } } public string MaxFilesize { get { return maxFilesize.Value; } set { maxFilesize.Value = value; } } public DateTime Date { get { return date.Value; } set { date.Value = value; } } public DateTime DateBefore { get { return dateBefore.Value; } set { dateBefore.Value = value; } } public DateTime DateAfter { get { return dateAfter.Value; } set { dateAfter.Value = value; } } public MultiValue<string> MatchFilters { get { return matchFilters.Value; } set { matchFilters.Value = value; } } public bool NoMatchFilters { get { return noMatchFilters.Value; } set { noMatchFilters.Value = value; } } public string BreakMatchFilters { get { return breakMatchFilters.Value; } set { breakMatchFilters.Value = value; } } public bool NoBreakMatchFilters { get { return noBreakMatchFilters.Value; } set { noBreakMatchFilters.Value = value; } } public bool NoPlaylist { get { return noPlaylist.Value; } set { noPlaylist.Value = value; } } public bool YesPlaylist { get { return yesPlaylist.Value; } set { yesPlaylist.Value = value; } } public byte? AgeLimit { get { return ageLimit.Value; } set { ageLimit.Value = value; } } public string DownloadArchive { get { return downloadArchive.Value; } set { downloadArchive.Value = value; } } public bool NoDownloadArchive { get { return noDownloadArchive.Value; } set { noDownloadArchive.Value = value; } } public int? MaxDownloads { get { return maxDownloads.Value; } set { maxDownloads.Value = value; } } public bool BreakOnExisting { get { return breakOnExisting.Value; } set { breakOnExisting.Value = value; } } public bool BreakPerInput { get { return breakPerInput.Value; } set { breakPerInput.Value = value; } } public bool NoBreakPerInput { get { return noBreakPerInput.Value; } set { noBreakPerInput.Value = value; } } public int? SkipPlaylistAfterErrors { get { return skipPlaylistAfterErrors.Value; } set { skipPlaylistAfterErrors.Value = value; } } public string Encoding { get { return encoding.Value; } set { encoding.Value = value; } } public bool LegacyServerConnect { get { return legacyServerConnect.Value; } set { legacyServerConnect.Value = value; } } public bool NoCheckCertificates { get { return noCheckCertificates.Value; } set { noCheckCertificates.Value = value; } } public bool PreferInsecure { get { return preferInsecure.Value; } set { preferInsecure.Value = value; } } public MultiValue<string> AddHeaders { get { return addHeaders.Value; } set { addHeaders.Value = value; } } public bool BidiWorkaround { get { return bidiWorkaround.Value; } set { bidiWorkaround.Value = value; } } public int? SleepRequests { get { return sleepRequests.Value; } set { sleepRequests.Value = value; } } public int? SleepInterval { get { return sleepInterval.Value; } set { sleepInterval.Value = value; } } public int? MaxSleepInterval { get { return maxSleepInterval.Value; } set { maxSleepInterval.Value = value; } } public int? SleepSubtitles { get { return sleepSubtitles.Value; } set { sleepSubtitles.Value = value; } } public void WriteConfigFile(string path) { File.WriteAllLines(path, GetOptionFlags()); } public override string ToString() { return " " + string.Join(" ", GetOptionFlags()); } public IEnumerable<string> GetOptionFlags() { return from value in GetKnownOptions().Concat(CustomOptions).SelectMany((IOption opt) => opt.ToStringCollection()) where !string.IsNullOrWhiteSpace(value) select value; } internal IEnumerable<IOption> GetKnownOptions() { return (from p in GetType().GetRuntimeFields() where p.FieldType.IsGenericType && p.FieldType.GetInterfaces().Contains(typeof(IOption)) select p.GetValue(this)).Cast<IOption>(); } public OptionSet OverrideOptions(OptionSet overrideOptions, bool forceOverride = false) { OptionSet optionSet = (OptionSet)Clone(); optionSet.CustomOptions = optionSet.CustomOptions.Concat(overrideOptions.CustomOptions).Distinct(Comparer).ToArray(); foreach (FieldInfo item in from p in overrideOptions.GetType().GetRuntimeFields() where p.FieldType.IsGenericType && p.FieldType.GetInterfaces().Contains(typeof(IOption)) select p) { IOption option = (IOption)item.GetValue(overrideOptions); if (forceOverride || option.IsSet) { optionSet.GetType().GetField(item.Name, BindingFlags.Instance | BindingFlags.NonPublic).SetValue(optionSet, option); } } return optionSet; } public static OptionSet FromString(IEnumerable<string> lines) { OptionSet optionSet = new OptionSet(); IOption[] customOptions = (from option in GetOptions(lines, optionSet.GetKnownOptions()) where option.IsCustom select option).ToArray(); optionSet.CustomOptions = customOptions; return optionSet; } private static IEnumerable<IOption> GetOptions(IEnumerable<string> lines, IEnumerable<IOption> options) { IEnumerable<IOption> knownOptions = options.ToList(); foreach (string line in lines) { string text = line.Trim(); if (!text.StartsWith("#") && !string.IsNullOrWhiteSpace(text)) { string[] array = text.Split(new char[1] { ' ' }); string flag = array[0]; IOption option = knownOptions.FirstOrDefault((IOption o) => o.OptionStrings.Contains(flag)); IOption option3; if (array.Length <= 1) { IOption option2 = new Option<bool>(true, flag); option3 = option2; } else { IOption option2 = new Option<string>(true, flag); option3 = option2; } IOption option4 = option3; IOption option5 = option ?? option4; option5.SetFromString(text); yield return option5; } } } public static OptionSet LoadConfigFile(string path) { return FromString(File.ReadAllLines(path)); } public object Clone() { return FromString(GetOptionFlags()); } public void AddCustomOption<T>(string optionString, T value) { Option<T> option = new Option<T>(true, optionString); option.Value = value; CustomOptions = CustomOptions.Concat(new Option<T>[1] { option }).ToArray(); } public void SetCustomOption<T>(string optionString, T value) { foreach (IOption item in CustomOptions.Where((IOption o) => o.OptionStrings.Contains(optionString))) { if (item is Option<T> option) { option.Value = value; continue; } throw new ArgumentException($"Value passed to option '{optionString}' has invalid type '{value.GetType()}'."); } } public void DeleteCustomOption(string optionString) { CustomOptions = CustomOptions.Where((IOption o) => !o.OptionStrings.Contains(optionString)).ToArray(); } } internal static class Utils { internal static T OptionValueFromString<T>(string stringValue) { if (typeof(T) == typeof(bool)) { return (T)(object)true; } if (typeof(T) == typeof(Enum)) { string value = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(stringValue); return (T)Enum.Parse(typeof(T), value); } if (typeof(T) == typeof(DateTime)) { return (T)(object)DateTime.ParseExact(stringValue, "yyyyMMdd", null); } return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(stringValue); } internal static string OptionValueToString<T>(T value) { if (value is bool) { return string.Empty; } if (value is Enum) { return " \"" + value.ToString().ToLower() + "\""; } if (value is DateTime) { object obj = value; return " " + ((DateTime)((obj is DateTime) ? obj : null)).ToString("yyyyMMdd"); } if (value is string) { return $" \"{value}\""; } T val = value; return " " + val; } } } namespace YoutubeDLSharp.Metadata { public class ChapterData { [JsonProperty("start_time")] public float? StartTime { get; set; } [JsonProperty("end_time")] public float? EndTime { get; set; } [JsonProperty("title")] public string Title { get; set; } } public class CommentData { [JsonProperty("id")] public string ID { get; set; } [JsonProperty("author")] public string Author { get; set; } [JsonProperty("author_id")] public string AuthorID { get; set; } [JsonProperty("author_thumbnail")] public string AuthorThumbnail { get; set; } [JsonProperty("html")] public string Html { get; set; } [JsonProperty("text")] public string Text { get; set; } [JsonProperty("timestamp")] [JsonConverter(typeof(UnixTimestampConverter))] public DateTime Timestamp { get; set; } [JsonProperty("parent")] public string Parent { get; set; } [JsonProperty("like_count")] public int? LikeCount { get; set; } [JsonProperty("dislike_count")] public int? DislikeCount { get; set; } [JsonProperty("is_favorited")] public bool? IsFavorited { get; set; } [JsonProperty("author_is_uploader")] public bool? AuthorIsUploader { get; set; } } public class FormatData { [JsonProperty("url")] public string Url { get; set; } [JsonProperty("manifest_url")] public string ManifestUrl { get; set; } [JsonProperty("ext")] public string Extension { get; set; } [JsonProperty("format")] public string Format { get; set; } [JsonProperty("format_id")] public string FormatId { get; set; } [JsonProperty("format_note")] public string FormatNote { get; set; } [JsonConverter(typeof(StringToNullableIntConverter))] [JsonProperty("width")] public int? Width { get; set; } [JsonConverter(typeof(StringToNullableIntConverter))] [JsonProperty("height")] public int? Height { get; set; } [JsonProperty("resolution")] public string Resolution { get; set; } [JsonProperty("dynamic_range")] public string DynamicRange { get; set; } [JsonProperty("tbr")] public double? Bitrate { get; set; } [JsonProperty("abr")] public double? AudioBitrate { get; set; } [JsonProperty("acodec")] public string AudioCodec { get; set; } [JsonProperty("asr")] public double? AudioSamplingRate { get; set; } [JsonConverter(typeof(
YoutubeExplode.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
#define DEBUG using System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Management; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using AngleSharp.Dom; using AngleSharp.Html.Dom; using AngleSharp.Html.Parser; using Microsoft.CodeAnalysis; using YoutubeExplode.Bridge; using YoutubeExplode.Bridge.Cipher; using YoutubeExplode.Channels; using YoutubeExplode.Common; using YoutubeExplode.Exceptions; using YoutubeExplode.Playlists; using YoutubeExplode.Search; using YoutubeExplode.Utils; using YoutubeExplode.Utils.Extensions; using YoutubeExplode.Videos; using YoutubeExplode.Videos.ClosedCaptions; using YoutubeExplode.Videos.Streams; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.6.1", FrameworkDisplayName = ".NET Framework 4.6.1")] [assembly: AssemblyCompany("Tyrrrz")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyCopyright("Copyright (C) Oleksii Holub")] [assembly: AssemblyDescription("Abstraction layer over YouTube's internal API. Note: this package has limited availability in Russia and Belarus.")] [assembly: AssemblyFileVersion("0.0.0.0")] [assembly: AssemblyInformationalVersion("0.0.0-dev+a3f5d6cc5cb6c5a399073e2f13973d6a4cc6cc6b")] [assembly: AssemblyProduct("YoutubeExplode")] [assembly: AssemblyTitle("YoutubeExplode")] [assembly: AssemblyVersion("0.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class PolyfillExtensions { public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { try { HttpResponseMessage response = await httpClient.GetAsync(requestUri, (HttpCompletionOption)1, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await httpClient.GetStreamAsync(requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { try { HttpResponseMessage response = await httpClient.GetAsync(requestUri, (HttpCompletionOption)1, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); try { response.EnsureSuccessStatusCode(); return await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } finally { ((IDisposable)response)?.Dispose(); } } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await httpClient.GetByteArrayAsync(requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> GetStringAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { try { HttpResponseMessage response = await httpClient.GetAsync(requestUri, (HttpCompletionOption)1, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); try { response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } finally { ((IDisposable)response)?.Dispose(); } } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<string> GetStringAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await httpClient.GetStringAsync(requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<Stream> ReadAsStreamAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> ReadAsByteArrayAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsByteArrayAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> ReadAsStringAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken)) { TaskCompletionSource<object?> tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); try { process.EnableRaisingEvents = true; } catch when (process.HasExited) { return; } process.Exited += HandleExited; try { using (cancellationToken.Register(delegate { tcs.TrySetCanceled(cancellationToken); })) { await tcs.Task; } } finally { process.Exited -= HandleExited; } void HandleExited(object? sender, EventArgs args) { tcs.TrySetResult(null); } } public static bool IsAssignableTo(this Type type, Type? otherType) { return otherType?.IsAssignableFrom(type) ?? false; } public static string ReplaceLineEndings(this string str, string replacementText) { return Replace(Replace(Replace(str, "\r\n", "\n", StringComparison.Ordinal), "\r", "\n", StringComparison.Ordinal), "\n", replacementText, StringComparison.Ordinal); } public static string ReplaceLineEndings(this string str) { return ReplaceLineEndings(str, Environment.NewLine); } public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } } public static async Task WaitAsync(this Task task, CancellationToken cancellationToken) { await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitAsync(this Task task, TimeSpan timeout) { await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } return task.Result; } public static async Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken) { return await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout) { return await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = stream.Read(buffer, i, Math.Min(minimumBytes, buffer.Length - i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, byte[] buffer, int offset, int count) { int num; for (int i = 0; i < count; i += num) { num = stream.Read(buffer, offset + i, count - i); if (num <= 0) { throw new EndOfStreamException(); } } } public static void ReadExactly(this Stream stream, byte[] buffer) { stream.ReadExactly(buffer, 0, buffer.Length); } public static async Task<int> ReadAtLeastAsync(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int bytesRead; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += bytesRead) { bytesRead = await stream.ReadAsync(buffer, totalBytesRead, Math.Min(minimumBytes, buffer.Length - totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (bytesRead <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) { int bytesRead; for (int totalBytesRead = 0; totalBytesRead < count; totalBytesRead += bytesRead) { bytesRead = await stream.ReadAsync(buffer, offset + totalBytesRead, count - totalBytesRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (bytesRead <= 0) { throw new EndOfStreamException(); } } } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { await stream.ReadExactlyAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, Span<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = Read(stream, buffer.Slice(i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, Span<byte> buffer) { byte[] array = buffer.ToArray(); stream.ReadExactly(array, 0, array.Length); array.CopyTo(buffer); } public static async Task<int> ReadAtLeastAsync(this Stream stream, Memory<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int bytesRead; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += bytesRead) { bytesRead = await ReadAsync(stream, buffer.Slice(totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (bytesRead <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { byte[] bufferArray = buffer.ToArray(); await stream.ReadExactlyAsync(bufferArray, 0, bufferArray.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); bufferArray.CopyTo(buffer); } public static Task CancelAsync(this CancellationTokenSource cts) { cts.Cancel(); return Task.CompletedTask; } public static void Deconstruct(this DictionaryEntry entry, out object key, out object? value) { key = entry.Key; value = entry.Value; } public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } public static IEnumerable<Match> AsEnumerable(this MatchCollection matchCollection) { return matchCollection.Cast<Match>(); } public static IEnumerator<Match> GetEnumerator(this MatchCollection matchCollection) { return matchCollection.AsEnumerable().GetEnumerator(); } public static Match[] ToArray(this MatchCollection matchCollection) { return matchCollection.AsEnumerable().ToArray(); } public static bool StartsWith(this string str, char c) { return str.Length > 0 && str[0] == c; } public static bool EndsWith(this string str, char c) { int result; if (str.Length > 0) { result = ((str[str.Length - 1] == c) ? 1 : 0); } else { result = 0; } return (byte)result != 0; } public static bool Contains(this string str, char c) { return str.IndexOf(c) >= 0; } public static string Replace(this string str, string oldValue, string? newValue, StringComparison comparison) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; int num2 = 0; while (true) { num = str.IndexOf(oldValue, num, comparison); if (num < 0) { break; } stringBuilder.Append(str, num2, num - num2); stringBuilder.Append(newValue); num += oldValue.Length; num2 = num; } stringBuilder.Append(str, num2, str.Length - num2); return stringBuilder.ToString(); } public static string Replace(this string str, string oldValue, string? newValue, bool ignoreCase, CultureInfo? culture) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; int num2 = 0; while (true) { num = (culture ?? CultureInfo.CurrentCulture).CompareInfo.IndexOf(str, oldValue, num, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); if (num < 0) { break; } stringBuilder.Append(str, num2, num - num2); stringBuilder.Append(newValue); num += oldValue.Length; num2 = num; } stringBuilder.Append(str, num2, str.Length - num2); return stringBuilder.ToString(); } public static string[] Split(this string str, char separator, int count, StringSplitOptions options = StringSplitOptions.None) { return str.Split(new char[1] { separator }, count, options); } public static string[] Split(this string str, char separator, StringSplitOptions options = StringSplitOptions.None) { return str.Split(new char[1] { separator }, options); } public static string[] Split(this string str, string? separator, int count, StringSplitOptions options = StringSplitOptions.None) { return str.Split(new string[1] { separator ?? "" }, count, options); } public static string[] Split(this string str, string? separator, StringSplitOptions options = StringSplitOptions.None) { return str.Split(new string[1] { separator ?? "" }, options); } public static void NextBytes(this Random random, Span<byte> buffer) { byte[] array = buffer.ToArray(); random.NextBytes(array); array.CopyTo(buffer); } public static int Read(this Stream stream, byte[] buffer) { return stream.Read(buffer, 0, buffer.Length); } public static void Write(this Stream stream, byte[] buffer) { stream.Write(buffer, 0, buffer.Length); } public static async Task CopyToAsync(this Stream stream, Stream destination, CancellationToken cancellationToken = default(CancellationToken)) { await stream.CopyToAsync(destination, 81920, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<int> ReadAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { return await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task WriteAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { await stream.WriteAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static int Read(this Stream stream, Span<byte> buffer) { byte[] array = buffer.ToArray(); int result = stream.Read(array, 0, array.Length); array.CopyTo(buffer); return result; } public static void Write(this Stream stream, ReadOnlySpan<byte> buffer) { byte[] array = buffer.ToArray(); stream.Write(array, 0, array.Length); } public static async Task<int> ReadAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { byte[] bufferArray = buffer.ToArray(); int result = await stream.ReadAsync(bufferArray, 0, bufferArray.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); bufferArray.CopyTo(buffer); return result; } public static async Task WriteAsync(this Stream stream, ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { byte[] bufferArray = buffer.ToArray(); await stream.WriteAsync(bufferArray, 0, bufferArray.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static int Read(this StreamReader reader, char[] buffer) { return reader.Read(buffer, 0, buffer.Length); } public static async Task<int> ReadAsync(this StreamReader reader, char[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(continueOnCapturedContext: false); } public static int Read(this StreamReader reader, Span<char> buffer) { char[] array = buffer.ToArray(); int result = reader.Read(array, 0, array.Length); array.CopyTo(buffer); return result; } public static async Task<int> ReadAsync(this StreamReader reader, Memory<char> buffer, CancellationToken cancellationToken = default(CancellationToken)) { char[] bufferArray = buffer.ToArray(); cancellationToken.ThrowIfCancellationRequested(); int result = await reader.ReadAsync(bufferArray, 0, bufferArray.Length).ConfigureAwait(continueOnCapturedContext: false); bufferArray.CopyTo(buffer); return result; } public static void Write(this StreamWriter writer, ReadOnlySpan<char> buffer) { char[] array = buffer.ToArray(); writer.Write(array, 0, array.Length); } public static async Task WriteAsync(this StreamWriter writer, Memory<char> buffer, CancellationToken cancellationToken = default(CancellationToken)) { char[] bufferArray = buffer.ToArray(); cancellationToken.ThrowIfCancellationRequested(); await writer.WriteAsync(bufferArray, 0, bufferArray.Length).ConfigureAwait(continueOnCapturedContext: false); } public static bool Contains(this string str, char c, StringComparison comparison) { return Contains(str, c.ToString(), comparison); } public static bool Contains(this string str, string sub, StringComparison comparison) { return str.IndexOf(sub, comparison) >= 0; } private static void KillProcessTree(int processId) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown ManagementObjectSearcher val = new ManagementObjectSearcher($"SELECT * FROM Win32_Process WHERE ParentProcessID={processId}"); try { ManagementObjectCollection val2 = val.Get(); try { try { using Process process = Process.GetProcessById(processId); if (!process.HasExited) { process.Kill(); } } catch { } foreach (ManagementObject item in ((IEnumerable)val2).Cast<ManagementObject>()) { int processId2 = Convert.ToInt32(((ManagementBaseObject)item)["ProcessID"]); KillProcessTree(processId2); } } finally { ((IDisposable)val2)?.Dispose(); } } finally { ((IDisposable)val)?.Dispose(); } } public static void Kill(this Process process, bool entireProcessTree) { if (!entireProcessTree) { process.Kill(); } else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { process.Kill(); } else { KillProcessTree(process.Id); } } } namespace YoutubeExplode { public class YoutubeClient { public VideoClient Videos { get; } public PlaylistClient Playlists { get; } public ChannelClient Channels { get; } public SearchClient Search { get; } public YoutubeClient(HttpClient http, IReadOnlyList<Cookie> initialCookies) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown HttpClient http2 = new HttpClient((HttpMessageHandler)(object)new YoutubeHttpHandler(http, initialCookies), true); Videos = new VideoClient(http2); Playlists = new PlaylistClient(http2); Channels = new ChannelClient(http2); Search = new SearchClient(http2); } public YoutubeClient(HttpClient http) : this(http, Array.Empty<Cookie>()) { } public YoutubeClient(IReadOnlyList<Cookie> initialCookies) : this(Http.Client, initialCookies) { } public YoutubeClient() : this(Http.Client) { } } internal class YoutubeHttpHandler : ClientDelegatingHandler { private readonly CookieContainer _cookieContainer = new CookieContainer(); public YoutubeHttpHandler(HttpClient http, IReadOnlyList<Cookie> initialCookies, bool disposeClient = false) : base(http, disposeClient) { foreach (Cookie initialCookie in initialCookies) { _cookieContainer.Add(initialCookie); } _cookieContainer.Add(new Cookie("SOCS", "CAISNQgDEitib3FfaWRlbnRpdHlmcm9udGVuZHVpc2VydmVyXzIwMjMwODI5LjA3X3AxGgJlbiACGgYIgLC_pwY") { Domain = "youtube.com" }); } private string? TryGenerateAuthHeaderValue(Uri uri) { Cookie[] source = _cookieContainer.GetCookies(uri).Cast<Cookie>().ToArray(); string text = source.FirstOrDefault((Cookie c) => string.Equals(c.Name, "__Secure-3PAPISID", StringComparison.Ordinal))?.Value ?? source.FirstOrDefault((Cookie c) => string.Equals(c.Name, "SAPISID", StringComparison.Ordinal))?.Value; if (string.IsNullOrWhiteSpace(text)) { return null; } long num = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); string domain = uri.GetDomain(); string s = $"{num} {text} {domain}"; string arg = Hash.Compute(SHA1.Create(), Encoding.UTF8.GetBytes(s)).ToHex(); return $"SAPISIDHASH {num}_{arg}"; } private HttpRequestMessage HandleRequest(HttpRequestMessage request) { if ((object)request.RequestUri == null) { return request; } if (request.RequestUri.AbsolutePath.StartsWith("/youtubei/", StringComparison.Ordinal) && !UrlEx.ContainsQueryParameter(request.RequestUri.Query, "key")) { request.RequestUri = new Uri(UrlEx.SetQueryParameter(request.RequestUri.OriginalString, "key", "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w")); } if (!UrlEx.ContainsQueryParameter(request.RequestUri.Query, "hl")) { request.RequestUri = new Uri(UrlEx.SetQueryParameter(request.RequestUri.OriginalString, "hl", "en")); } if (!((HttpHeaders)request.Headers).Contains("Origin")) { ((HttpHeaders)request.Headers).Add("Origin", request.RequestUri.GetDomain()); } if (!((HttpHeaders)request.Headers).Contains("User-Agent")) { ((HttpHeaders)request.Headers).Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"); } if (!((HttpHeaders)request.Headers).Contains("Cookie") && _cookieContainer.Count > 0) { string cookieHeader = _cookieContainer.GetCookieHeader(request.RequestUri); if (!string.IsNullOrWhiteSpace(cookieHeader)) { ((HttpHeaders)request.Headers).Add("Cookie", cookieHeader); } } if (!((HttpHeaders)request.Headers).Contains("Authorization")) { string text = TryGenerateAuthHeaderValue(request.RequestUri); if (text != null) { ((HttpHeaders)request.Headers).Add("Authorization", text); } } return request; } private HttpResponseMessage HandleResponse(HttpResponseMessage response) { HttpRequestMessage requestMessage = response.RequestMessage; if ((object)((requestMessage != null) ? requestMessage.RequestUri : null) == null) { return response; } if (response.StatusCode == HttpStatusCode.TooManyRequests) { throw new RequestLimitExceededException("Exceeded request rate limit. Please try again in a few hours. Alternatively, inject cookies corresponding to a pre-authenticated user when initializing an instance of `YoutubeClient`."); } IEnumerable<string> enumerable = default(IEnumerable<string>); if (((HttpHeaders)response.Headers).TryGetValues("Set-Cookie", ref enumerable)) { foreach (string item in enumerable) { try { _cookieContainer.SetCookies(response.RequestMessage.RequestUri, item); } catch (CookieException) { } } } return response; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { int retriesRemaining = 5; HttpResponseMessage response; while (true) { response = HandleResponse(await base.SendAsync(HandleRequest(request), cancellationToken)); if (response.StatusCode < HttpStatusCode.InternalServerError || retriesRemaining <= 0) { break; } response.Dispose(); retriesRemaining--; } return response; } } } namespace YoutubeExplode.Videos { public class Engagement { public long ViewCount { get; } public long LikeCount { get; } public long DislikeCount { get; } public double AverageRating => (LikeCount + DislikeCount != 0L) ? (1.0 + 4.0 * (double)LikeCount / (double)(LikeCount + DislikeCount)) : 0.0; public Engagement(long viewCount, long likeCount, long dislikeCount) { ViewCount = viewCount; LikeCount = likeCount; DislikeCount = dislikeCount; base..ctor(); } [ExcludeFromCodeCoverage] public override string ToString() { return $"Rating: {AverageRating:N1}"; } } public interface IVideo { VideoId Id { get; } string Url { get; } string Title { get; } Author Author { get; } TimeSpan? Duration { get; } IReadOnlyList<Thumbnail> Thumbnails { get; } } public class Video : IVideo { public VideoId Id { get; } public string Url => $"https://www.youtube.com/watch?v={Id}"; public string Title { get; } public Author Author { get; } public DateTimeOffset UploadDate { get; } public string Description { get; } public TimeSpan? Duration { get; } public IReadOnlyList<Thumbnail> Thumbnails { get; } public IReadOnlyList<string> Keywords { get; } public Engagement Engagement { get; } public Video(VideoId id, string title, Author author, DateTimeOffset uploadDate, string description, TimeSpan? duration, IReadOnlyList<Thumbnail> thumbnails, IReadOnlyList<string> keywords, Engagement engagement) { Id = id; Title = title; Author = author; UploadDate = uploadDate; Description = description; Duration = duration; Thumbnails = thumbnails; Keywords = keywords; Engagement = engagement; base..ctor(); } [ExcludeFromCodeCoverage] public override string ToString() { return "Video (" + Title + ")"; } } public class VideoClient { private readonly VideoController _controller = new VideoController(http); public StreamClient Streams { get; } = new StreamClient(http); public ClosedCaptionClient ClosedCaptions { get; } = new ClosedCaptionClient(http); public VideoClient(HttpClient http) { } public async ValueTask<Video> GetAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { VideoWatchPage watchPage = await _controller.GetVideoWatchPageAsync(videoId, cancellationToken); PlayerResponse playerResponse2 = watchPage.PlayerResponse; PlayerResponse playerResponse3 = playerResponse2; if (playerResponse3 == null) { playerResponse3 = await _controller.GetPlayerResponseAsync(videoId, cancellationToken); } PlayerResponse playerResponse = playerResponse3; string title = playerResponse.Title ?? ""; string channelTitle = playerResponse.Author ?? throw new YoutubeExplodeException("Failed to extract the video author."); string channelId = playerResponse.ChannelId ?? throw new YoutubeExplodeException("Failed to extract the video channel ID."); return new Video(uploadDate: playerResponse.UploadDate ?? watchPage.UploadDate ?? throw new YoutubeExplodeException("Failed to extract the video upload date."), thumbnails: playerResponse.Thumbnails.Select(delegate(ThumbnailData t) { string url = t.Url ?? throw new YoutubeExplodeException("Failed to extract the thumbnail URL."); int width = t.Width ?? throw new YoutubeExplodeException("Failed to extract the thumbnail width."); int height = t.Height ?? throw new YoutubeExplodeException("Failed to extract the thumbnail height."); Resolution resolution = new Resolution(width, height); return new Thumbnail(url, resolution); }).Concat(Thumbnail.GetDefaultSet(videoId)).ToArray(), id: videoId, title: title, author: new Author(channelId, channelTitle), description: playerResponse.Description ?? "", duration: playerResponse.Duration, keywords: playerResponse.Keywords, engagement: new Engagement(playerResponse.ViewCount.GetValueOrDefault(), watchPage.LikeCount.GetValueOrDefault(), watchPage.DislikeCount.GetValueOrDefault())); } } internal class VideoController { protected HttpClient Http { get; } public VideoController(HttpClient http) { Http = http; base..ctor(); } public async ValueTask<VideoWatchPage> GetVideoWatchPageAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { int retriesRemaining = 5; VideoWatchPage watchPage; while (true) { watchPage = VideoWatchPage.TryParse(await Http.GetStringAsync($"https://www.youtube.com/watch?v={videoId}&bpctr=9999999999", cancellationToken)); if (watchPage != null) { break; } if (retriesRemaining <= 0) { throw new YoutubeExplodeException("Video watch page is broken. Please try again in a few minutes."); } retriesRemaining--; } if (!watchPage.IsAvailable) { throw new VideoUnavailableException($"Video '{videoId}' is not available."); } return watchPage; } public async ValueTask<PlayerResponse> GetPlayerResponseAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://www.youtube.com/youtubei/v1/player"); try { request.Content = (HttpContent)new StringContent("{\r\n \"videoId\": " + Json.Serialize(videoId) + ",\r\n \"context\": {\r\n \"client\": {\r\n \"clientName\": \"ANDROID_TESTSUITE\",\r\n \"clientVersion\": \"1.9\",\r\n \"androidSdkVersion\": 30,\r\n \"hl\": \"en\",\r\n \"gl\": \"US\",\r\n \"utcOffsetMinutes\": 0\r\n }\r\n }\r\n}"); ((HttpHeaders)request.Headers).Add("User-Agent", "com.google.android.youtube/17.36.4 (Linux; U; Android 12; GB) gzip"); HttpResponseMessage response = await ((HttpMessageInvoker)Http).SendAsync(request, cancellationToken); try { response.EnsureSuccessStatusCode(); PlayerResponse playerResponse = PlayerResponse.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); if (!playerResponse.IsAvailable) { throw new VideoUnavailableException($"Video '{videoId}' is not available."); } return playerResponse; } finally { ((IDisposable)response)?.Dispose(); } } finally { ((IDisposable)request)?.Dispose(); } } public async ValueTask<PlayerResponse> GetPlayerResponseAsync(VideoId videoId, string? signatureTimestamp, CancellationToken cancellationToken = default(CancellationToken)) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://www.youtube.com/youtubei/v1/player"); try { request.Content = (HttpContent)new StringContent("{\r\n \"videoId\": " + Json.Serialize(videoId) + ",\r\n \"context\": {\r\n \"client\": {\r\n \"clientName\": \"TVHTML5_SIMPLY_EMBEDDED_PLAYER\",\r\n \"clientVersion\": \"2.0\",\r\n \"hl\": \"en\",\r\n \"gl\": \"US\",\r\n \"utcOffsetMinutes\": 0\r\n },\r\n \"thirdParty\": {\r\n \"embedUrl\": \"https://www.youtube.com\"\r\n }\r\n },\r\n \"playbackContext\": {\r\n \"contentPlaybackContext\": {\r\n \"signatureTimestamp\": " + Json.Serialize(signatureTimestamp) + "\r\n }\r\n }\r\n}"); HttpResponseMessage response = await ((HttpMessageInvoker)Http).SendAsync(request, cancellationToken); try { response.EnsureSuccessStatusCode(); PlayerResponse playerResponse = PlayerResponse.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); if (!playerResponse.IsAvailable) { throw new VideoUnavailableException($"Video '{videoId}' is not available."); } return playerResponse; } finally { ((IDisposable)response)?.Dispose(); } } finally { ((IDisposable)request)?.Dispose(); } } } public readonly struct VideoId : IEquatable<VideoId> { public string Value { get; } public VideoId(string value) { Value = value; } public override string ToString() { return Value; } private static bool IsValid(string videoId) { return videoId.Length == 11 && videoId.All(delegate(char c) { bool flag = char.IsLetterOrDigit(c); bool flag2 = flag; if (!flag2) { bool flag3 = ((c == '-' || c == '_') ? true : false); flag2 = flag3; } return flag2; }); } private static string? TryNormalize(string? videoIdOrUrl) { if (string.IsNullOrWhiteSpace(videoIdOrUrl)) { return null; } if (IsValid(videoIdOrUrl)) { return videoIdOrUrl; } string text = Regex.Match(videoIdOrUrl, "youtube\\..+?/watch.*?v=(.*?)(?:&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text) && IsValid(text)) { return text; } string text2 = Regex.Match(videoIdOrUrl, "youtu\\.be/(.*?)(?:\\?|&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text2) && IsValid(text2)) { return text2; } string text3 = Regex.Match(videoIdOrUrl, "youtube\\..+?/embed/(.*?)(?:\\?|&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text3) && IsValid(text3)) { return text3; } string text4 = Regex.Match(videoIdOrUrl, "youtube\\..+?/shorts/(.*?)(?:\\?|&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text4) && IsValid(text4)) { return text4; } string text5 = Regex.Match(videoIdOrUrl, "youtube\\..+?/live/(.*?)(?:\\?|&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text5) && IsValid(text5)) { return text5; } return null; } public static VideoId? TryParse(string? videoIdOrUrl) { return TryNormalize(videoIdOrUrl)?.Pipe((string id) => new VideoId(id)); } public static VideoId Parse(string videoIdOrUrl) { return TryParse(videoIdOrUrl) ?? throw new ArgumentException("Invalid YouTube video ID or URL '" + videoIdOrUrl + "'."); } public static implicit operator VideoId(string videoIdOrUrl) { return Parse(videoIdOrUrl); } public static implicit operator string(VideoId videoId) { return videoId.ToString(); } public bool Equals(VideoId other) { return StringComparer.Ordinal.Equals(Value, other.Value); } public override bool Equals(object? obj) { return obj is VideoId other && Equals(other); } public override int GetHashCode() { return StringComparer.Ordinal.GetHashCode(Value); } public static bool operator ==(VideoId left, VideoId right) { return left.Equals(right); } public static bool operator !=(VideoId left, VideoId right) { return !(left == right); } } } namespace YoutubeExplode.Videos.Streams { public class AudioOnlyStreamInfo : IAudioStreamInfo, IStreamInfo { public string Url { get; } public Container Container { get; } public FileSize Size { get; } public Bitrate Bitrate { get; } public string AudioCodec { get; } public AudioOnlyStreamInfo(string url, Container container, FileSize size, Bitrate bitrate, string audioCodec) { Url = url; Container = container; Size = size; Bitrate = bitrate; AudioCodec = audioCodec; base..ctor(); } [ExcludeFromCodeCoverage] public override string ToString() { return $"Audio-only ({Container})"; } } public readonly struct Bitrate : IComparable<Bitrate>, IEquatable<Bitrate> { public long BitsPerSecond { get; } public double KiloBitsPerSecond => (double)BitsPerSecond / 1024.0; public double MegaBitsPerSecond => KiloBitsPerSecond / 1024.0; public double GigaBitsPerSecond => MegaBitsPerSecond / 1024.0; public Bitrate(long bitsPerSecond) { BitsPerSecond = bitsPerSecond; } private string GetLargestWholeNumberSymbol() { if (Math.Abs(GigaBitsPerSecond) >= 1.0) { return "Gbit/s"; } if (Math.Abs(MegaBitsPerSecond) >= 1.0) { return "Mbit/s"; } if (Math.Abs(KiloBitsPerSecond) >= 1.0) { return "Kbit/s"; } return "Bit/s"; } private double GetLargestWholeNumberValue() { if (Math.Abs(GigaBitsPerSecond) >= 1.0) { return GigaBitsPerSecond; } if (Math.Abs(MegaBitsPerSecond) >= 1.0) { return MegaBitsPerSecond; } if (Math.Abs(KiloBitsPerSecond) >= 1.0) { return KiloBitsPerSecond; } return BitsPerSecond; } public override string ToString() { return $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}"; } public int CompareTo(Bitrate other) { return BitsPerSecond.CompareTo(other.BitsPerSecond); } public bool Equals(Bitrate other) { return CompareTo(other) == 0; } public override bool Equals(object? obj) { return obj is Bitrate other && Equals(other); } public override int GetHashCode() { return HashCode.Combine(BitsPerSecond); } public static bool operator ==(Bitrate left, Bitrate right) { return left.Equals(right); } public static bool operator !=(Bitrate left, Bitrate right) { return !(left == right); } public static bool operator >(Bitrate left, Bitrate right) { return left.CompareTo(right) > 0; } public static bool operator <(Bitrate left, Bitrate right) { return left.CompareTo(right) < 0; } } public readonly struct Container : IEquatable<Container> { public string Name { get; } public bool IsAudioOnly => string.Equals(Name, "mp3", StringComparison.OrdinalIgnoreCase) || string.Equals(Name, "m4a", StringComparison.OrdinalIgnoreCase) || string.Equals(Name, "wav", StringComparison.OrdinalIgnoreCase) || string.Equals(Name, "wma", StringComparison.OrdinalIgnoreCase) || string.Equals(Name, "ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(Name, "aac", StringComparison.OrdinalIgnoreCase) || string.Equals(Name, "opus", StringComparison.OrdinalIgnoreCase); public static Container Mp3 { get; } = new Container("mp3"); public static Container Mp4 { get; } = new Container("mp4"); public static Container WebM { get; } = new Container("webm"); public static Container Tgpp { get; } = new Container("3gpp"); public Container(string name) { Name = name; } public override string ToString() { return Name; } public bool Equals(Container other) { return StringComparer.OrdinalIgnoreCase.Equals(Name, other.Name); } public override bool Equals(object? obj) { return obj is Container other && Equals(other); } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(Name); } public static bool operator ==(Container left, Container right) { return left.Equals(right); } public static bool operator !=(Container left, Container right) { return !(left == right); } } public readonly struct FileSize : IComparable<FileSize>, IEquatable<FileSize> { public long Bytes { get; } public double KiloBytes => (double)Bytes / 1024.0; public double MegaBytes => KiloBytes / 1024.0; public double GigaBytes => MegaBytes / 1024.0; public FileSize(long bytes) { Bytes = bytes; } private string GetLargestWholeNumberSymbol() { if (Math.Abs(GigaBytes) >= 1.0) { return "GB"; } if (Math.Abs(MegaBytes) >= 1.0) { return "MB"; } if (Math.Abs(KiloBytes) >= 1.0) { return "KB"; } return "B"; } private double GetLargestWholeNumberValue() { if (Math.Abs(GigaBytes) >= 1.0) { return GigaBytes; } if (Math.Abs(MegaBytes) >= 1.0) { return MegaBytes; } if (Math.Abs(KiloBytes) >= 1.0) { return KiloBytes; } return Bytes; } public override string ToString() { return $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}"; } public int CompareTo(FileSize other) { return Bytes.CompareTo(other.Bytes); } public bool Equals(FileSize other) { return CompareTo(other) == 0; } public override bool Equals(object? obj) { return obj is FileSize other && Equals(other); } public override int GetHashCode() { return HashCode.Combine(Bytes); } public static bool operator ==(FileSize left, FileSize right) { return left.Equals(right); } public static bool operator !=(FileSize left, FileSize right) { return !(left == right); } public static bool operator >(FileSize left, FileSize right) { return left.CompareTo(right) > 0; } public static bool operator <(FileSize left, FileSize right) { return left.CompareTo(right) < 0; } } public interface IAudioStreamInfo : IStreamInfo { string AudioCodec { get; } } public interface IStreamInfo { string Url { get; } Container Container { get; } FileSize Size { get; } Bitrate Bitrate { get; } } public static class StreamInfoExtensions { internal static bool IsThrottled(this IStreamInfo streamInfo) { return !string.Equals(UrlEx.TryGetQueryParameterValue(streamInfo.Url, "ratebypass"), "yes", StringComparison.OrdinalIgnoreCase); } public static IStreamInfo? TryGetWithHighestBitrate(this IEnumerable<IStreamInfo> streamInfos) { return System.Linq.PolyfillExtensions.MaxBy(streamInfos, (IStreamInfo s) => s.Bitrate); } public static IStreamInfo GetWithHighestBitrate(this IEnumerable<IStreamInfo> streamInfos) { return streamInfos.TryGetWithHighestBitrate() ?? throw new InvalidOperationException("Input stream collection is empty."); } } public interface IVideoStreamInfo : IStreamInfo { string VideoCodec { get; } VideoQuality VideoQuality { get; } Resolution VideoResolution { get; } } public static class VideoStreamInfoExtensions { public static IVideoStreamInfo? TryGetWithHighestVideoQuality(this IEnumerable<IVideoStreamInfo> streamInfos) { return System.Linq.PolyfillExtensions.MaxBy(streamInfos, (IVideoStreamInfo s) => s.VideoQuality); } public static IVideoStreamInfo GetWithHighestVideoQuality(this IEnumerable<IVideoStreamInfo> streamInfos) { return streamInfos.TryGetWithHighestVideoQuality() ?? throw new InvalidOperationException("Input stream collection is empty."); } } internal class MediaStream : Stream { [CompilerGenerated] [DebuggerBrowsable(DebuggerBrowsableState.Never)] private HttpClient <http>P; [CompilerGenerated] [DebuggerBrowsable(DebuggerBrowsableState.Never)] private IStreamInfo <streamInfo>P; private readonly long _segmentLength; private Stream? _segmentStream; private long _actualPosition; [ExcludeFromCodeCoverage] public override bool CanRead => true; [ExcludeFromCodeCoverage] public override bool CanSeek => true; [ExcludeFromCodeCoverage] public override bool CanWrite => false; public override long Length => <streamInfo>P.Size.Bytes; public override long Position { get; set; } public MediaStream(HttpClient http, IStreamInfo streamInfo) { <http>P = http; <streamInfo>P = streamInfo; _segmentLength = (<streamInfo>P.IsThrottled() ? 9898989 : <streamInfo>P.Size.Bytes); base..ctor(); } private void ResetSegment() { _segmentStream?.Dispose(); _segmentStream = null; } private async ValueTask<Stream> ResolveSegmentAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (_segmentStream != null) { return _segmentStream; } return _segmentStream = await PolyfillExtensions.GetStreamAsync(requestUri: GetSegmentUrl(<streamInfo>P.Url, Position, Position + _segmentLength - 1), httpClient: <http>P, cancellationToken: cancellationToken); } public async ValueTask InitializeAsync(CancellationToken cancellationToken = default(CancellationToken)) { await ResolveSegmentAsync(cancellationToken); } private async ValueTask<int> ReadSegmentAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) { int retriesRemaining = 5; while (true) { try { return await (await ResolveSegmentAsync(cancellationToken)).ReadAsync(buffer, offset, count, cancellationToken); } catch (Exception ex) when (((ex is HttpRequestException || ex is IOException) ? true : false) && retriesRemaining > 0) { ResetSegment(); } retriesRemaining--; } } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { int bytesRead; while (true) { long requestedPosition = Position; if (_actualPosition != requestedPosition) { ResetSegment(); } if (requestedPosition >= Length) { return 0; } bytesRead = await ReadSegmentAsync(buffer, offset, count, cancellationToken); Position = (_actualPosition = requestedPosition + bytesRead); if (bytesRead > 0) { break; } ResetSegment(); } return bytesRead; } [ExcludeFromCodeCoverage] public override int Read(byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count).GetAwaiter().GetResult(); } [ExcludeFromCodeCoverage] public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] public override void SetLength(long value) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] public override long Seek(long offset, SeekOrigin origin) { if (1 == 0) { } long num = origin switch { SeekOrigin.Begin => offset, SeekOrigin.Current => Position + offset, SeekOrigin.End => Length + offset, _ => throw new ArgumentOutOfRangeException("origin"), }; if (1 == 0) { } return Position = num; } [ExcludeFromCodeCoverage] public override void Flush() { throw new NotSupportedException(); } protected override void Dispose(bool disposing) { if (disposing) { ResetSegment(); } base.Dispose(disposing); } public static string GetSegmentUrl(string streamUrl, long from, long to) { return UrlEx.SetQueryParameter(streamUrl, "range", $"{from}-{to}"); } } public class MuxedStreamInfo : IAudioStreamInfo, IStreamInfo, IVideoStreamInfo { public string Url { get; } public Container Container { get; } public FileSize Size { get; } public Bitrate Bitrate { get; } public string AudioCodec { get; } public string VideoCodec { get; } public VideoQuality VideoQuality { get; } public Resolution VideoResolution { get; } public MuxedStreamInfo(string url, Container container, FileSize size, Bitrate bitrate, string audioCodec, string videoCodec, VideoQuality videoQuality, Resolution videoResolution) { Url = url; Container = container; Size = size; Bitrate = bitrate; AudioCodec = audioCodec; VideoCodec = videoCodec; VideoQuality = videoQuality; VideoResolution = videoResolution; base..ctor(); } [ExcludeFromCodeCoverage] public override string ToString() { return $"Muxed ({VideoQuality} | {Container})"; } } public class StreamClient { [CompilerGenerated] [DebuggerBrowsable(DebuggerBrowsableState.Never)] private HttpClient <http>P; private readonly StreamController _controller; private CipherManifest? _cipherManifest; public StreamClient(HttpClient http) { <http>P = http; _controller = new StreamController(<http>P); base..ctor(); } private async ValueTask<CipherManifest> ResolveCipherManifestAsync(CancellationToken cancellationToken) { if (_cipherManifest != null) { return _cipherManifest; } return _cipherManifest = (await _controller.GetPlayerSourceAsync(cancellationToken)).CipherManifest ?? throw new YoutubeExplodeException("Failed to extract the cipher manifest."); } private async ValueTask<long?> TryGetContentLengthAsync(IStreamData streamData, string url, CancellationToken cancellationToken = default(CancellationToken)) { long? contentLength = streamData.ContentLength; if (!contentLength.HasValue) { HttpResponseMessage response2 = await <http>P.HeadAsync(url, cancellationToken); try { contentLength = response2.Content.Headers.ContentLength; if (response2.StatusCode == HttpStatusCode.NotFound) { return null; } response2.EnsureSuccessStatusCode(); } finally { ((IDisposable)response2)?.Dispose(); } } if (contentLength.HasValue) { HttpResponseMessage response = await <http>P.GetAsync(MediaStream.GetSegmentUrl(url, contentLength.Value - 2, contentLength.Value - 1), (HttpCompletionOption)1, cancellationToken); try { if (response.StatusCode == HttpStatusCode.NotFound) { return null; } response.EnsureSuccessStatusCode(); } finally { ((IDisposable)response)?.Dispose(); } } return contentLength; } private async IAsyncEnumerable<IStreamInfo> GetStreamInfosAsync(IEnumerable<IStreamData> streamDatas, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { foreach (IStreamData streamData in streamDatas) { int itag = streamData.Itag ?? throw new YoutubeExplodeException("Failed to extract the stream itag."); string url = streamData.Url ?? throw new YoutubeExplodeException("Failed to extract the stream URL."); if (!string.IsNullOrWhiteSpace(streamData.Signature)) { url = UrlEx.SetQueryParameter(value: (await ResolveCipherManifestAsync(cancellationToken)).Decipher(streamData.Signature), url: url, key: streamData.SignatureParameter ?? "sig"); } long? contentLength = await TryGetContentLengthAsync(streamData, url, cancellationToken); if (!contentLength.HasValue) { continue; } Container container = (streamData.Container ?? throw new YoutubeExplodeException("Failed to extract the stream container.")).Pipe((string s) => new Container(s)); Bitrate bitrate = (streamData.Bitrate ?? throw new YoutubeExplodeException("Failed to extract the stream bitrate.")).Pipe((long s) => new Bitrate(s)); if (!string.IsNullOrWhiteSpace(streamData.VideoCodec)) { int framerate = streamData.VideoFramerate.GetValueOrDefault(24); VideoQuality videoQuality = ((!string.IsNullOrWhiteSpace(streamData.VideoQualityLabel)) ? VideoQuality.FromLabel(streamData.VideoQualityLabel, framerate) : VideoQuality.FromItag(itag, framerate)); Resolution videoResolution = ((streamData.VideoWidth.HasValue && streamData.VideoHeight.HasValue) ? new Resolution(streamData.VideoWidth.Value, streamData.VideoHeight.Value) : videoQuality.GetDefaultVideoResolution()); if (!string.IsNullOrWhiteSpace(streamData.AudioCodec)) { yield return new MuxedStreamInfo(url, container, new FileSize(contentLength.Value), bitrate, streamData.AudioCodec, streamData.VideoCodec, videoQuality, videoResolution); } else { yield return new VideoOnlyStreamInfo(url, container, new FileSize(contentLength.Value), bitrate, streamData.VideoCodec, videoQuality, videoResolution); } } else { if (string.IsNullOrWhiteSpace(streamData.AudioCodec)) { throw new YoutubeExplodeException("Failed to extract the stream codec."); } yield return new AudioOnlyStreamInfo(url, container, new FileSize(contentLength.Value), bitrate, streamData.AudioCodec); } } } private async ValueTask<IReadOnlyList<IStreamInfo>> GetStreamInfosAsync(VideoId videoId, PlayerResponse playerResponse, CancellationToken cancellationToken = default(CancellationToken)) { List<IStreamInfo> streamInfos = new List<IStreamInfo>(); if (!string.IsNullOrWhiteSpace(playerResponse.PreviewVideoId)) { throw new VideoRequiresPurchaseException($"Video '{videoId}' requires purchase and cannot be played.", playerResponse.PreviewVideoId); } if (!playerResponse.IsPlayable) { throw new VideoUnplayableException($"Video '{videoId}' is unplayable. Reason: '{playerResponse.PlayabilityError}'."); } List<IStreamInfo> list = streamInfos; list.AddRange(await GetStreamInfosAsync(playerResponse.Streams, cancellationToken)); if (!string.IsNullOrWhiteSpace(playerResponse.DashManifestUrl)) { try { DashManifest dashManifest = await _controller.GetDashManifestAsync(playerResponse.DashManifestUrl, cancellationToken); List<IStreamInfo> list2 = streamInfos; list2.AddRange(await GetStreamInfosAsync(dashManifest.Streams, cancellationToken)); } catch (HttpRequestException) { } } if (!streamInfos.Any()) { throw new VideoUnplayableException($"Video '{videoId}' does not contain any playable streams."); } return streamInfos; } private async ValueTask<IReadOnlyList<IStreamInfo>> GetStreamInfosAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { try { return await GetStreamInfosAsync(videoId, await _controller.GetPlayerResponseAsync(videoId, cancellationToken), cancellationToken); } catch (VideoUnplayableException) { CipherManifest cipherManifest = await ResolveCipherManifestAsync(cancellationToken); return await GetStreamInfosAsync(videoId, await _controller.GetPlayerResponseAsync(videoId, cipherManifest.SignatureTimestamp, cancellationToken), cancellationToken); } } public async ValueTask<StreamManifest> GetManifestAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { int retriesRemaining = 5; while (true) { try { return new StreamManifest(await GetStreamInfosAsync(videoId, cancellationToken)); } catch (Exception ex) when (((ex is HttpRequestException || ex is IOException) ? true : false) && retriesRemaining > 0) { } retriesRemaining--; } } public async ValueTask<string> GetHttpLiveStreamUrlAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { PlayerResponse playerResponse = await _controller.GetPlayerResponseAsync(videoId, cancellationToken); if (!playerResponse.IsPlayable) { throw new VideoUnplayableException($"Video '{videoId}' is unplayable. Reason: '{playerResponse.PlayabilityError}'."); } if (string.IsNullOrWhiteSpace(playerResponse.HlsManifestUrl)) { throw new YoutubeExplodeException($"Failed to extract the HTTP Live Stream manifest URL. Video '{videoId}' is likely not a live stream."); } return playerResponse.HlsManifestUrl; } public async ValueTask<Stream> GetAsync(IStreamInfo streamInfo, CancellationToken cancellationToken = default(CancellationToken)) { MediaStream stream = new MediaStream(<http>P, streamInfo); await stream.InitializeAsync(cancellationToken); return stream; } public async ValueTask CopyToAsync(IStreamInfo streamInfo, Stream destination, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { using Stream input = await GetAsync(streamInfo, cancellationToken); await input.CopyToAsync(destination, progress, cancellationToken); } public async ValueTask DownloadAsync(IStreamInfo streamInfo, string filePath, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { using FileStream destination = File.Create(filePath); await CopyToAsync(streamInfo, destination, progress, cancellationToken); } } internal class StreamController : VideoController { public StreamController(HttpClient http) : base(http) { } public async ValueTask<PlayerSource> GetPlayerSourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { string version = Regex.Match(await base.Http.GetStringAsync("https://www.youtube.com/iframe_api", cancellationToken), "player\\\\?/([0-9a-fA-F]{8})\\\\?/").Groups[1].Value; if (string.IsNullOrWhiteSpace(version)) { throw new YoutubeExplodeException("Failed to extract the player version."); } return PlayerSource.Parse(await base.Http.GetStringAsync("https://www.youtube.com/s/player/" + version + "/player_ias.vflset/en_US/base.js", cancellationToken)); } public async ValueTask<DashManifest> GetDashManifestAsync(string url, CancellationToken cancellationToken = default(CancellationToken)) { return DashManifest.Parse(await base.Http.GetStringAsync(url, cancellationToken)); } } public class StreamManifest { public IReadOnlyList<IStreamInfo> Streams { get; } public StreamManifest(IReadOnlyList<IStreamInfo> streams) { Streams = streams; base..ctor(); } public IEnumerable<IAudioStreamInfo> GetAudioStreams() { return Streams.OfType<IAudioStreamInfo>(); } public IEnumerable<IVideoStreamInfo> GetVideoStreams() { return Streams.OfType<IVideoStreamInfo>(); } public IEnumerable<MuxedStreamInfo> GetMuxedStreams() { return Streams.OfType<MuxedStreamInfo>(); } public IEnumerable<AudioOnlyStreamInfo> GetAudioOnlyStreams() { return GetAudioStreams().OfType<AudioOnlyStreamInfo>(); } public IEnumerable<VideoOnlyStreamInfo> GetVideoOnlyStreams() { return GetVideoStreams().OfType<VideoOnlyStreamInfo>(); } } public class VideoOnlyStreamInfo : IVideoStreamInfo, IStreamInfo { public string Url { get; } public Container Container { get; } public FileSize Size { get; } public Bitrate Bitrate { get; } public string VideoCodec { get; } public VideoQuality VideoQuality { get; } public Resolution VideoResolution { get; } public VideoOnlyStreamInfo(string url, Container container, FileSize size, Bitrate bitrate, string videoCodec, VideoQuality videoQuality, Resolution videoResolution) { Url = url; Container = container; Size = size; Bitrate = bitrate; VideoCodec = videoCodec; VideoQuality = videoQuality; VideoResolution = videoResolution; base..ctor(); } [ExcludeFromCodeCoverage] public override string ToString() { return $"Video-only ({VideoQuality} | {Container})"; } } public readonly struct VideoQuality : IComparable<VideoQuality>, IEquatable<VideoQuality> { public string Label { get; } public int MaxHeight { get; } public int Framerate { get; } public bool IsHighDefinition => MaxHeight >= 1080; public VideoQuality(string label, int maxHeight, int framerate) { Label = label; MaxHeight = maxHeight; Framerate = framerate; } public VideoQuality(int maxHeight, int framerate) : this(FormatLabel(maxHeight, framerate), maxHeight, framerate) { } internal Resolution GetDefaultVideoResolution() { int maxHeight = MaxHeight; if (1 == 0) { } Resolution result = maxHeight switch { 144 => new Resolution(256, 144), 240 => new Resolution(426, 240), 360 => new Resolution(640, 360), 480 => new Resolution(854, 480), 720 => new Resolution(1280, 720), 1080 => new Resolution(1920, 1080), 1440 => new Resolution(2560, 1440), 2160 => new Resolution(3840, 2160), 2880 => new Resolution(5120, 2880), 3072 => new Resolution(4096, 3072), 4320 => new Resolution(7680, 4320), _ => new Resolution(16 * MaxHeight / 9, MaxHeight), }; if (1 == 0) { } return result; } public override string ToString() { return Label; } private static string FormatLabel(int maxHeight, int framerate) { if (framerate <= 30) { return $"{maxHeight}p"; } int num = (int)Math.Ceiling((double)framerate / 10.0) * 10; return $"{maxHeight}p{num}"; } internal static VideoQuality FromLabel(string label, int framerateFallback) { Match match = Regex.Match(label, "^(\\d+)\\D(\\d+)?"); int maxHeight = match.Groups[1].Value.ParseInt(); return new VideoQuality(label, maxHeight, (match.Groups[2].Value.NullIfWhiteSpace()?.ParseIntOrNull()).GetValueOrDefault(framerateFallback)); } internal static VideoQuality FromItag(int itag, int framerate) { if (1 == 0) { } int num = itag switch { 5 => 144, 6 => 240, 13 => 144, 17 => 144, 18 => 360, 22 => 720, 34 => 360, 35 => 480, 36 => 240, 37 => 1080, 38 => 3072, 43 => 360, 44 => 480, 45 => 720, 46 => 1080, 59 => 480, 78 => 480, 82 => 360, 83 => 480, 84 => 720, 85 => 1080, 91 => 144, 92 => 240, 93 => 360, 94 => 480, 95 => 720, 96 => 1080, 100 => 360, 101 => 480, 102 => 720, 132 => 240, 151 => 144, 133 => 240, 134 => 360, 135 => 480, 136 => 720, 137 => 1080, 138 => 4320, 142 => 240, 143 => 360, 144 => 480, 145 => 720, 146 => 1080, 160 => 144, 161 => 144, 167 => 360, 168 => 480, 169 => 720, 170 => 1080, 212 => 480, 213 => 480, 214 => 720, 215 => 720, 216 => 1080, 217 => 1080, 218 => 480, 219 => 480, 222 => 480, 223 => 480, 224 => 720, 225 => 720, 226 => 1080, 227 => 1080, 242 => 240, 243 => 360, 244 => 480, 245 => 480, 246 => 480, 247 => 720, 248 => 1080, 264 => 1440, 266 => 2160, 271 => 1440, 272 => 2160, 278 => 144, 298 => 720, 299 => 1080, 302 => 720, 303 => 1080, 308 => 1440, 313 => 2160, 315 => 2160, 330 => 144, 331 => 240, 332 => 360, 333 => 480, 334 => 720, 335 => 1080, 336 => 1440, 337 => 2160, 399 => 1080, 398 => 720, 397 => 480, 396 => 360, 395 => 240, 394 => 144, _ => throw new ArgumentException($"Unrecognized itag '{itag}'.", "itag"), }; if (1 == 0) { } int maxHeight = num; return new VideoQuality(maxHeight, framerate); } public int CompareTo(VideoQuality other) { int num = MaxHeight.CompareTo(other.MaxHeight); if (num != 0) { return num; } int num2 = Framerate.CompareTo(other.Framerate); if (num2 != 0) { return num2; } return StringComparer.OrdinalIgnoreCase.Compare(Label, other.Label); } public bool Equals(VideoQuality other) { return StringComparer.OrdinalIgnoreCase.Equals(Label, other.Label) && MaxHeight == other.MaxHeight && Framerate == other.Framerate; } public override bool Equals(object? obj) { return obj is VideoQuality other && Equals(other); } public override int GetHashCode() { return HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(Label), MaxHeight, Framerate); } public static bool operator ==(VideoQuality left, VideoQuality right) { return left.Equals(right); } public static bool operator !=(VideoQuality left, VideoQuality right) { return !(left == right); } public static bool operator >(VideoQuality left, VideoQuality right) { return left.CompareTo(right) > 0; } public static bool operator <(VideoQuality left, VideoQuality right) { return left.CompareTo(right) < 0; } } } namespace YoutubeExplode.Videos.ClosedCaptions { public class ClosedCaption { public string Text { get; } public TimeSpan Offset { get; } public TimeSpan Duration { get; } public IReadOnlyList<ClosedCaptionPart> Parts { get; } public ClosedCaption(string text, TimeSpan offset, TimeSpan duration, IReadOnlyList<ClosedCaptionPart> parts) { Text = text; Offset = offset; Duration = duration; Parts = parts; base..ctor(); } public ClosedCaptionPart? TryGetPartByTime(TimeSpan time) { return Parts.FirstOrDefault((ClosedCaptionPart p) => p.Offset >= time); } public ClosedCaptionPart GetPartByTime(TimeSpan time) { return TryGetPartByTime(time) ?? throw new InvalidOperationException($"No closed caption part found at {time}."); } [ExcludeFromCodeCoverage] public override string ToString() { return Text; } } public class ClosedCaptionClient { private readonly ClosedCaptionController _controller = new ClosedCaptionController(http); public ClosedCaptionClient(HttpClient http) { } private async IAsyncEnumerable<ClosedCaptionTrackInfo> GetClosedCaptionTrackInfosAsync(VideoId videoId, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { foreach (PlayerResponse.ClosedCaptionTrackData trackData in (await _controller.GetPlayerResponseAsync(videoId, null, cancellationToken)).ClosedCaptionTracks) { string url = trackData.Url ?? throw new YoutubeExplodeException("Failed to extract the track URL."); string languageCode = trackData.LanguageCode ?? throw new YoutubeExplodeException("Failed to extract the track language code."); string languageName = trackData.LanguageName ?? throw new YoutubeExplodeException("Failed to extract the track language name."); yield return new ClosedCaptionTrackInfo(url, new Language(languageCode, languageName), trackData.IsAutoGenerated); } } public async ValueTask<ClosedCaptionManifest> GetManifestAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { return new ClosedCaptionManifest(await GetClosedCaptionTrackInfosAsync(videoId, cancellationToken)); } private async IAsyncEnumerable<ClosedCaption> GetClosedCaptionsAsync(ClosedCaptionTrackInfo trackInfo, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { TimeSpan offset = default(TimeSpan); TimeSpan duration = default(TimeSpan); foreach (ClosedCaptionTrackResponse.CaptionData captionData in (await _controller.GetClosedCaptionTrackResponseAsync(trackInfo.Url, cancellationToken)).Captions) { string text = captionData.Text; if (string.IsNullOrEmpty(text)) { continue; } TimeSpan? offset2 = captionData.Offset; int num2; if (offset2.HasValue) { offset = offset2.GetValueOrDefault(); offset2 = captionData.Duration; int num; if (offset2.HasValue) { duration = offset2.GetValueOrDefault(); num = 1; } else { num = 0; } num2 = ((num == 0) ? 1 : 0); } else { num2 = 1; } if (num2 != 0) { continue; } List<ClosedCaptionPart> parts = new List<ClosedCaptionPart>(); foreach (ClosedCaptionTrackResponse.PartData partData in captionData.Parts) { string partText = partData.Text; if (!string.IsNullOrEmpty(partText)) { TimeSpan partOffset = partData.Offset ?? throw new YoutubeExplodeException("Failed to extract the caption part offset."); ClosedCaptionPart part = new ClosedCaptionPart(partText, partOffset); parts.Add(part); } } yield return new ClosedCaption(text, offset, duration, parts); offset = default(TimeSpan); duration = default(TimeSpan); } } public async ValueTask<ClosedCaptionTrack> GetAsync(ClosedCaptionTrackInfo trackInfo, CancellationToken cancellationToken = default(CancellationToken)) { return new ClosedCaptionTrack(await GetClosedCaptionsAsync(trackInfo, cancellationToken)); } public async ValueTask WriteToAsync(ClosedCaptionTrackInfo trackInfo, TextWriter writer, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { ClosedCaptionTrack track = await GetAsync(trackInfo, cancellationToken); StringBuilder buffer = new StringBuilder(); foreach (var (caption, i) in track.Captions.WithIndex()) { cancellationToken.ThrowIfCancellationRequested(); buffer.AppendLine((i + 1).ToString(CultureInfo.InvariantCulture)).Append(FormatTimestamp(caption.Offset)).Append(" --> ") .Append(FormatTimestamp(caption.Offset + caption.Duration)) .AppendLine() .AppendLine(PolyfillExtensions.Replace(caption.Text, "-->", "––>", StringComparison.Ordinal)); await writer.WriteLineAsync(buffer.ToString()); buffer.Clear(); progress?.Report(((double)i + 1.0) / (double)track.Captions.Count); } static string FormatTimestamp(TimeSpan value) { return Math.Floor(value.TotalHours).ToString("00", CultureInfo.InvariantCulture) + ":" + value.Minutes.ToString("00", CultureInfo.InvariantCulture) + ":" + value.Seconds.ToString("00", CultureInfo.InvariantCulture) + "," + value.Milliseconds.ToString("000", CultureInfo.InvariantCulture); } } public async ValueTask DownloadAsync(ClosedCaptionTrackInfo trackInfo, string filePath, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { using StreamWriter writer = File.CreateText(filePath); await WriteToAsync(trackInfo, writer, progress, cancellationToken); } } internal class ClosedCaptionController : VideoController { public ClosedCaptionController(HttpClient http) : base(http) { } public async ValueTask<ClosedCaptionTrackResponse> GetClosedCaptionTrackResponseAsync(string url, CancellationToken cancellationToken = default(CancellationToken)) { return ClosedCaptionTrackResponse.Parse(await PolyfillExtensions.GetStringAsync(requestUri: url.Pipe((string s) => UrlEx.SetQueryParameter(s, "format", "3")).Pipe((string s) => UrlEx.SetQueryParameter(s, "fmt", "3")), httpClient: base.Http, cancellationToken: cancellationToken)); } } public class ClosedCaptionManifest { public IReadOnlyList<ClosedCaptionTrackInfo> Tracks { get; } public ClosedCaptionManifest(IReadOnlyList<ClosedCaptionTrackInfo> tracks) { Tracks = tracks; base..ctor(); } public ClosedCaptionTrackInfo? TryGetByLanguage(string language) { string language2 = language; return Tracks.FirstOrDefault((ClosedCaptionTrackInfo t) => string.Equals(t.Language.Code, language2, StringComparison.OrdinalIgnoreCase) || string.Equals(t.Language.Name, language2, StringComparison.OrdinalIgnoreCase)); } public ClosedCaptionTrackInfo GetByLanguage(string language) { return TryGetByLanguage(language) ?? throw new InvalidOperationException("No closed caption track available for language '" + language + "'."); } } public class ClosedCaptionPart { public string Text { get; } public TimeSpan Offset { get; } public ClosedCaptionPart(string text, TimeSpan offset) { Text = text; Offset = offset; base..ctor(); } [ExcludeFromCodeCoverage] public override string ToString() { return Text; } } public class ClosedCaptionTrack { public IReadOnlyList<ClosedCaption> Captions { get; } public ClosedCaptionTrack(IReadOnlyList<ClosedCaption> captions) { Captions = captions; base..ctor(); } public ClosedCaption? TryGetByTime(TimeSpan time) { return Captions.FirstOrDefault((ClosedCaption c) => time >= c.Offset && time <= c.Offset + c.Duration); } public ClosedCaption GetByTime(TimeSpan time) { return TryGetByTime(time) ?? throw new InvalidOperationException($"No closed caption found at {time}."); } } public class ClosedCaptionTrackInfo { public string Url { get; } public Language Language { get; } public bool IsAutoGenerated { get; } public ClosedCaptionTrackInfo(string url, Language language, bool isAutoGenerated) { Url = url; Language = language; IsAutoGenerated = isAutoGenerated; base..ctor(); } [ExcludeFromCodeCoverage] public override string ToString() { return $"CC Track ({Language})"; } } public readonly struct Language : IEquatable<Language> { public string Code { get; } public string Name { get; } public Language(string code, string name) { Code = code; Name = name; } [ExcludeFromCodeCoverage] public override string ToString() { return Code + " (" + Name + ")"; } public bool Equals(Language other) { return StringComparer.OrdinalIgnoreCase.Equals(Code, other.Code); } public override bool Equals(object? obj) { return obj is Language other && Equals(other); } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(Code); } public static bool operator ==(Language left, Language right) { return left.Equals(right); } public static bool operator !=(Language left, Language right) { return !(left == right); } } } namespace YoutubeExplode.Utils { internal abstract class ClientDelegatingHandler : HttpMessageHandler { [CompilerGenerated] [DebuggerBrowsable(DebuggerBrowsableState.Never)] private HttpClient <http>P; [CompilerGenerated] [DebuggerBrowsable(DebuggerBrowsableState.Never)] private bool <disposeClient>P; protected ClientDelegatingHandler(HttpClient http, bool disposeClient = false) { <http>P = http; <disposeClient>P = disposeClient; ((HttpMessageHandler)this)..ctor(); } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpRequestMessage clonedRequest = request.Clone(); try { return await <http>P.SendAsync(clonedRequest, (HttpCompletionOption)1, cancellationToken); } finally { ((IDisposable)clonedRequest)?.Dispose(); } } protected override void Dispose(bool disposing) { if (disposing && <disposeClient>P) { ((HttpMessageInvoker)<http>P).Dispose(); } ((HttpMessageHandler)this).Dispose(disposing); } } internal static class Hash { public static byte[] Compute(HashAlgorithm algorithm, byte[] data) { using (algorithm) { return algorithm.ComputeHash(data); } } } internal static class Html { private static readonly HtmlParser HtmlParser = new HtmlParser(); public static IHtmlDocument Parse(string source) { return HtmlParser.ParseDocument(source); } } internal static class Http { private static readonly Lazy<HttpClient> HttpClientLazy = new Lazy<HttpClient>((Func<HttpClient>)(() => new HttpClient())); public static HttpClient Client => HttpClientLazy.Value; } internal static class Json { public static string Extract(string source) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; bool flag = false; foreach (var item3 in source.WithIndex()) { char item = item3.value; int item2 = item3.index; char c = ((item2 > 0) ? source[item2 - 1] : '\0'); stringBuilder.Append(item); if (item == '"' && c != '\\') { flag = !flag; } else if (item == '{' && !flag) { num++; } else if (item == '}' && !flag) { num--; } if (num == 0) { break; } } return stringBuilder.ToString(); } public static JsonElement Parse(string source) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) JsonDocument val = JsonDocument.Parse(source, default(JsonDocumentOptions)); try { JsonElement rootElement = val.RootElement; return ((JsonElement)(ref rootElement)).Clone(); } finally { ((IDisposable)val)?.Dispose(); } } public static JsonElement? TryParse(string source) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) try { return Parse(source); } catch (JsonException) { return null; } } public static string Encode(string value) { StringBuilder stringBuilder = new StringBuilder(value.Length); foreach (char c in value) { switch (c) { case '\n': stringBuilder.Append("\\n"); break; case '\r': stringBuilder.Append("\\r"); break; case '\t': stringBuilder.Append("\\t"); break; case '\\': stringBuilder.Append("\\\\"); break; case '"': stringBuilder.Append("\\\""); break; default: stringBuilder.Append(c); break; } } return stringBuilder.ToString(); } public static string Serialize(string? value) { return (value != null) ? ("\"" + Encode(value) + "\"") : "null"; } public static string Serialize(int? value) { return value.HasValue ? value.Value.ToString(CultureInfo.InvariantCulture) : "null"; } } internal static class UrlEx { private static IEnumerable<KeyValuePair<string, string>> EnumerateQueryParameters(string url) { string query = (PolyfillExtensions.Contains(url, '?') ? url.SubstringAfter("?") : url); string[] array = query.Split(new char[1] { '&' }); foreach (string parameter in array) { string key = WebUtility.UrlDecode(parameter.SubstringUntil("=")); string value = WebUtility.UrlDecode(parameter.SubstringAfter("=")); if (!string.IsNullOrWhiteSpace(key)) { yield return new KeyValuePair<string, string>(key, value); } } } public static IReadOnlyDictionary<string, string> GetQueryParameters(string url) { return EnumerateQueryParameters(url).ToDictionary<KeyValuePair<string, string>, string, string>((KeyValuePair<string, string> kvp) => kvp.Key, (KeyValuePair<string, string> kvp) => kvp.Value); } private static KeyValuePair<string, string>? TryGetQueryParameter(string url, string key) { foreach (KeyValuePair<string, string> item in EnumerateQueryParameters(url)) { if (string.Equals(item.Key, key, StringComparison.Ordinal)) { return item; } } return null; } public static string? TryGetQueryParameterValue(string url, string key) { return TryGetQueryParameter(url, key)?.Value; } public static bool ContainsQueryParameter(string url, string key) { return TryGetQueryParameterValue(url, key) != null; } public static string RemoveQueryParameter(string url, string key) { if (!ContainsQueryParameter(url, key)) { return url; } UriBuilder uriBuilder = new UriBuilder(url); StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair<string, string> item in EnumerateQueryParameters(url)) { if (!string.Equals(item.Key, key, StringComparison.Ordinal)) { stringBuilder.Append((stringBuilder.Length > 0) ? '&' : '?'); stringBuilder.Append(WebUtility.UrlEncode(item.Key)); stringBuilder.Append('='); stringBuilder.Append(WebUtility.UrlEncode(item.Value)); } } uriBuilder.Query = stringBuilder.ToString(); return uriBuilder.ToString(); } public static string SetQueryParameter(string url, string key, string value) { string text = RemoveQueryParameter(url, key); bool flag = PolyfillExtensions.Contains(text, '?'); return text + (flag ? '&' : '?') + WebUtility.UrlEncode(key) + "=" + WebUtility.UrlEncode(value); } } internal static class Xml { public static XElement Parse(string source) { return XElement.Parse(source, (LoadOptions)1).StripNamespaces(); } } } namespace YoutubeExplode.Utils.Extensions { internal static class AsyncCollectionExtensions { public static async IAsyncEnumerable<T> TakeAsync<T>(this IAsyncEnumerable<T> source, int count) { int currentCount = 0; await foreach (T i in source) { if (currentCount >= count) { break; } yield return i; currentCount++; } } public static async IAsyncEnumerable<T> SelectManyAsync<TSource, T>(this IAsyncEnumerable<TSource> source, Func<TSource, IEnumerable<T>> transform) { await foreach (TSource i in source) { foreach (T item in transform(i)) { yield return item; } } } public static async IAsyncEnumerable<T> OfTypeAsync<T>(this IAsyncEnumerable<object> source) { T match = default(T); await foreach (object i in source) { int num; if (i is T) { match = (T)i; num = 1; } else { num = 0; } if (num != 0) { yield return match; } match = default(T); } } public static async ValueTask<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source) { List<T> list = new List<T>(); await foreach (T i in source) { list.Add(i); } return list; } public static ValueTaskAwaiter<List<T>> GetAwaiter<T>(this IAsyncEnumerable<T> source) { return source.ToListAsync().GetAwaiter(); } } internal static class BinaryExtensions { public static string ToHex(this byte[] data, bool isUpperCase = true) { StringBuilder stringBuilder = new StringBuilder(2 * data.Length); foreach (byte b in data) { stringBuilder.Append(b.ToString(isUpperCase ? "X2" : "x2", CultureInfo.InvariantCulture)); } return stringBuilder.ToString(); } } internal static class CollectionExtensions { public static IEnumerable<(T value, int index)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T o in source) { yield return (o, i++); } } public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : class { foreach (T i in source) { if (i != null) { yield return i; } } } public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : struct { foreach (T? i in source) { if (i.HasValue) { yield return i.Value; } } } public static T? ElementAtOrNull<T>(this IEnumerable<T> source, int index) where T : struct { IReadOnlyList<T> readOnlyList = (source as IReadOnlyList<T>) ?? source.ToArray(); return (index < readOnlyList.Count) ? new T?(readOnlyList[index]) : null; } public static T? FirstOrNull<T>(this IEnumerable<T> source) where T : struct { using (IEnumerator<T> enumerator = source.GetEnumerator()) { if (enumerator.MoveNext()) { return enumerator.Current; } } return null; } } internal static class GenericExtensions { public static TOut Pipe<TIn, TOut>(this TIn input, Func<TIn, TOut> transform) { return transform(input); } } internal static class HttpExtensions { private class NonDisposableHttpContent : HttpContent { [CompilerGenerated] [DebuggerBrowsable(DebuggerBrowsableState.Never)] private HttpContent <content>P; public NonDisposableHttpContent(HttpContent content) { <content>P = content; ((HttpContent)this)..ctor(); } protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context) { await <content>P.CopyToAsync(stream); } protected override bool TryComputeLength(out long length) { length = 0L; return false; } } public static HttpRequestMessage Clone(this HttpRequestMessage request) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown HttpRequestMessage val = new HttpRequestMessage(request.Method, request.RequestUri) { Version = request.Version, Content = (HttpContent)(object)((request.Content != null) ? new NonDisposableHttpContent(request.Content) : null) }; string key; IEnumerable<string> value; foreach (KeyValuePair<string, IEnumerable<string>> item in (HttpHeaders)request.Headers) { PolyfillExtensions.Deconstruct(item, out key, out value); string text = key; IEnumerable<string> enumerable = value; ((HttpHeaders)val.Headers).TryAddWithoutValidation(text, enumerable); } if (request.Content != null && val.Content != null) { foreach (KeyValuePair<string, IEnumerable<string>> item2 in (HttpHeaders)request.Content.Headers) { PolyfillExtensions.Deconstruct(item2, out key, out value); string text2 = key; IEnumerable<string> enumerable2 = value; ((HttpHeaders)val.Content.Headers).TryAddWithoutValidation(text2, enumerable2); } } return val; } public static async ValueTask<HttpResponseMessage> HeadAsync(this HttpClient http, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, requestUri); try { return await http.SendAsync(request, (HttpCompletionOption)1, cancellationToken); } finally { ((IDisposable)request)?.Dispose(); } } } internal static class JsonExtensions { public static JsonElement? GetPropertyOrNull(this JsonElement element, string propertyName) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Invalid comparison between Unknown and I4 //IL_0049: Unknown result type (might be due to invalid IL or missing references) if ((int)((JsonElement)(ref element)).ValueKind != 1) { return null; } JsonElement value = default(JsonElement); if (((JsonElement)(ref element)).TryGetProperty(propertyName, ref value) && (int)((JsonElement)(ref value)).ValueKind != 7 && (int)((JsonElement)(ref value)).ValueKind > 0) { return value; } return null; } public static string? GetStringOrNull(this JsonElement element) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 return ((int)((JsonElement)(ref element)).ValueKind == 3) ? ((JsonElement)(ref element)).GetString() : null; } public static int? GetInt32OrNull(this JsonElement element) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 int value = default(int); return ((int)((JsonElement)(ref element)).ValueKind == 4 && ((JsonElement)(ref element)).TryGetInt32(ref value)) ? new int?(value) : null; } public static long? GetInt64OrNull(this JsonElement element) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 long value = default(long); return ((int)((JsonElement)(ref element)).ValueKind == 4 && ((JsonElement)(ref element)).TryGetInt64(ref value)) ? new long?(value) : null; } public static ArrayEnumerator? EnumerateArrayOrNull(this JsonElement element) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0017: Unknown result type (might be due to invalid IL or missing references) return ((int)((JsonElement)(ref element)).ValueKind == 2) ? new ArrayEnumerator?(((JsonElement)(ref element)).EnumerateArray()) : null; } public static ArrayEnumerator EnumerateArrayOrEmpty(this JsonElement element) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) return element.EnumerateArrayOrNull().GetValueOrDefault(); } public static ObjectEnumerator? EnumerateObjectOrNull(this JsonElement element) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0017: Unknown result type (might be due to invalid IL or missing references) return ((int)((JsonElement)(ref element)).ValueKind == 1) ? new ObjectEnumerator?(((JsonElement)(ref element)).EnumerateObject()) : null; } public static ObjectEnumerator EnumerateObjectOrEmpty(this JsonElement element) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) return element.EnumerateObjectOrNull().GetValueOrDefault(); } public static IEnumerable<JsonElement> EnumerateDescendantProperties(this JsonElement element, string propertyName) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) string propertyName2 = propertyName; JsonElement? property = element.GetPropertyOrNull(propertyName2); if (property.HasValue) { yield return property.Value; } IEnumerable<JsonElement> deepArrayDescendants = ((IEnumerable<JsonElement>)(object)element.EnumerateArrayOrEmpty()).SelectMany((JsonElement j) => j.EnumerateDescendantProperties(propertyName2)); foreach (JsonElement item in deepArrayDescendants) { yield return item; } IEnumerable<JsonElement> deepObjectDescendants = ((IEnumerable<JsonProperty>)(object)element.EnumerateObjectOrEmpty()).SelectMany((JsonProperty j) => ((JsonProperty)(ref j)).Value.EnumerateDescendantProperties(propertyName2)); foreach (JsonElement item2 in deepObjectDescendants) { yield return item2; } } } internal static class StreamExtensions { public static async ValueTask CopyToAsync(this Stream source, Stream destination, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { using IMemoryOwner<byte> buffer = MemoryPool<byte>.Shared.Rent(81920); long totalBytesRead = 0L; while (true) { int bytesRead = await PolyfillExtensions.ReadAsync(source, buffer.Memory, cancellationToken); if (bytesRead <= 0) { break; } await PolyfillExtensions.WriteAsync(destination, buffer.Memory.Slice(0, bytesRead), cancellationToken); totalBytesRead += bytesRead; progress?.Report(1.0 * (double)totalBytesRead / (double)source.Length); } } } internal static class StringExtensions { public static string? NullIfWhiteSpace(this string str) { return (!string.IsNullOrWhiteSpace(str)) ? str : null; } public static string SubstringUntil(this string str, string sub, StringComparison comparison = StringComparison.Ordinal) { int num = str.IndexOf(sub, comparison); return (num < 0) ? str : str.Substring(0, num); } public static string SubstringAfter(this string str, string sub, StringComparison comparison = StringComparison.Ordinal) { int num = str.IndexOf(sub, comparison); return (num < 0) ? string.Empty : str.Substring(num + sub.Length, str.Length - num - sub.Length); } public static string StripNonDigit(this string str) { StringBuilder stringBuilder = new StringBuilder(); foreach (char item in str.Where(char.IsDigit)) { stringBuilder.Append(item); } return stringBuilder.ToString(); } public static string Reverse(this string str) { StringBuilder stringBuilder = new StringBuilder(str.Length); for (int num = str.Length - 1; num >= 0; num--) { stringBuilder.Append(str[num]); } return stringBuilder.ToString(); } public static string SwapChars(this string str, int firstCharIndex, int secondCharIndex) { return new StringBuilder(str) { [firstCharIndex] = str[secondCharIndex], [secondCharIndex] = str[firstCharIndex] }.ToString(); } public static int? ParseIntOrNull(this string str) { int result; return int.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out result) ? new int?(result) : null; } public static int ParseInt(this string str) { return str.ParseIntOrNull() ?? throw new FormatException("Cannot parse integer number from string '" + str + "'."); } public static long? ParseLongOrNull(this string str) { long result; return long.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out result) ? new long?(result) : null; } public static double? ParseDoubleOrNull(this string str) { double result; return double.TryParse(str, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out result) ? new double?(result) : null; } public static TimeSpan? ParseTimeSpanOrNull(this string str, string[] formats) { TimeSpan result; return TimeSpan.TryParseExact(str, formats, DateTimeFormatInfo.InvariantInfo, out result) ? new TimeSpan?(result) : null; } public static DateTimeOffset? ParseDateTimeOffsetOrNull(this string str) { DateTimeOffset result; return DateTimeOffset.TryParse(str, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out result) ? new DateTimeOffset?(result) : null; } public static string ConcatToString<T>(this IEnumerable<T> source) { return string.Concat(source); } } internal static class UriExtensions { public static string GetDomain(this Uri uri) { return uri.Scheme + Uri.SchemeDelimiter + uri.Host; } } internal static class XElementExtensions { public static XElement StripNamespaces(this XElement element) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown XElement val = new XElement(element); foreach (XElement item in val.DescendantsAndSelf()) { item.Name = XNamespace.None.GetName(item.Name.LocalName); item.ReplaceAttributes((object)(from a in item.Attributes() where !a.IsNamespaceDeclaration where a.Name.Namespace != XNamespace.Xml && a.Name.Namespace != XNamespace.Xmlns select a).Select((Func<XAttribute, XAttribute>)((XAttribute a) => new XAttribute(XNamespace.None.GetName(a.Name.LocalName), (object)a.Value)))); } return val; } } } namespace YoutubeExplode.Search { public class ChannelSearchResult : ISearchResult, IBatchItem, IChannel { public ChannelId Id { get; } public string Url => $"https://www.youtube.com/channel/{Id}"; public string Title { get; } public IReadOnlyList<Thumbnail> Thumbnails { get; } public ChannelSearchResult(ChannelId id, string title, IReadOnlyList<Thumbnail> thumbnails) { Id = id; Title = title; Thumbnails = thumbnails; base..ctor(); } [ExcludeFromCodeCoverage] public override string ToString() { return "Channel (" + Title + ")"; } } public interface ISearchResult : IBatchItem { string Url { get; } string Title { get; } } public class PlaylistSearchResult : ISearchResult, IBatchItem, IPlaylist { public PlaylistId Id { get; } public string Url => $"https://www.youtube.com/playlist?list={Id}"; public string Title { get; } public Author? Author { get; } public IReadOnlyList<Thumbnail> Thumbnails { get; } public PlaylistSearchResult(PlaylistId id, string title, Author? author, IReadOnlyList<Thumbnail> thumbnails) { Id = id; Title = title; Author = author; Thumbnails = thumbnails; base..ctor(); } [ExcludeFromCodeCoverage] public override string ToString() { return "Playlist (" + Title + ")"; } } public class SearchClient { private readonly SearchController _controller = new SearchController(http); public SearchClient(HttpClient http) { } public async IAsyncEnumerable<Batch<ISearchResult>> GetResultBatchesAsync(string searchQuery, SearchFilter searchFilter, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { int num = -1; HashSet<string> encounteredIds = new HashSet<string>(StringComparer.Ordinal); string continuationToken = null; do { List<ISearchResult> results = new List<ISearchResult>(); SearchResponse searchResults = await _controller.GetSearchResponseAsync(searchQuery, searchFilter, continuationToken, cancellationToken); IEnumerator<SearchResponse.VideoData> enumerator = searchResults.Videos.GetEnumerator(); try { while (enumerator.MoveNext()) { SearchResponse.VideoData videoData = enumerator.Current; if (searchFilter != 0 && searchFilter != SearchFilter.Video) { Debug.Fail("Did not expect videos in search results."); break; } string videoId = videoData.Id ?? throw new YoutubeExplodeException("Failed to extract the video ID."); if (encounteredIds.Add(videoId)) { string videoTitle = videoData.Title ?? throw new YoutubeExplodeException("Failed to extract the video title."); string videoChannelTitle = videoData.Author ?? throw new YoutubeExplodeException("Failed to extract the video author."); string videoChannelId = videoData.ChannelId ?? throw new YoutubeExplodeException("Failed to extract the video channel ID."); VideoSearchResult video = new VideoSearchResult(thumbnails: videoData.Thumbnails.Select(delegate(ThumbnailData t) { string url3 = t.Url ?? throw new YoutubeExplodeException("Failed to extract the video thumbnail URL."); int width3 = t.Width ?? throw new YoutubeExplodeException("Failed to extract the video thumbnail width."); int height3 = t.Height ?? throw new YoutubeExplodeException("Failed to extract the video thumbnail height."); Resolution resolution3 = new Resolution(width3, height3); return new Thumbnail(url3, resolution3); }).Concat(Thumbnail.GetDefaultSet(videoId)).ToArray(), id: videoId, title: videoTitle, author: new Author(videoChannelId, videoChannelTitle), duration: videoData.Duration); results.Add(video); } } } finally { if (num == -1) { enumerator?.Dispose(); } } IEnumerator<SearchResponse.PlaylistData> enumerator2 = searchResults.Playl